2222import java .io .Serializable ;
2323import java .lang .reflect .Field ;
2424import java .net .HttpURLConnection ;
25+ import java .net .InetSocketAddress ;
2526import java .net .Socket ;
2627import java .net .URI ;
2728import java .net .URL ;
3334import java .util .Map ;
3435import java .util .Set ;
3536import java .util .concurrent .CountDownLatch ;
37+ import java .util .concurrent .ExecutorService ;
38+ import java .util .concurrent .Executors ;
3639import java .util .concurrent .TimeUnit ;
3740import java .util .concurrent .atomic .AtomicBoolean ;
3841import java .util .concurrent .atomic .AtomicInteger ;
6669import org .apache .catalina .startup .Tomcat ;
6770import org .apache .catalina .startup .TomcatBaseTest ;
6871import org .apache .catalina .valves .TesterAccessLogValve ;
72+ import org .apache .coyote .InputBuffer ;
6973import org .apache .coyote .Request ;
74+ import org .apache .coyote .http11 .Constants ;
75+ import org .apache .coyote .http11 .Http11InputBuffer ;
76+ import org .apache .coyote .http11 .InputFilter ;
77+ import org .apache .coyote .http11 .filters .ChunkedInputFilter ;
7078import org .apache .juli .logging .Log ;
7179import org .apache .juli .logging .LogFactory ;
7280import org .apache .tomcat .util .buf .ByteChunk ;
81+ import org .apache .tomcat .util .net .ApplicationBufferHandler ;
7382
7483public class TestNonBlockingAPI extends TomcatBaseTest {
7584
@@ -626,7 +635,8 @@ private void doTestNonBlockingReadChunked(String[] requestBody, String expectedT
626635 // No file system docBase required
627636 Context ctx = getProgrammaticRootContext ();
628637
629- NBReadServlet servlet = new NBReadServlet (false , true , expectedTrailerFieldValue );
638+ ReadProgress readProgress = new ReadProgress ();
639+ NBReadServlet servlet = new NBReadServlet (false , true , expectedTrailerFieldValue , readProgress );
630640 String servletName = NBReadServlet .class .getName ();
631641 Tomcat .addServlet (ctx , servletName , servlet );
632642 ctx .addServletMapping ("/" , servletName );
@@ -635,6 +645,7 @@ private void doTestNonBlockingReadChunked(String[] requestBody, String expectedT
635645
636646 tomcat .start ();
637647
648+ int firstBodyLength = requestBody [0 ].getBytes (StandardCharsets .ISO_8859_1 ).length ;
638649 // Add the headers to the first part of the chunked body
639650 // @formatter:off
640651 requestBody [0 ] =
@@ -647,14 +658,18 @@ private void doTestNonBlockingReadChunked(String[] requestBody, String expectedT
647658
648659 Client client = new Client ();
649660 client .setPort (getPort ());
650- client .setRequest (requestBody );
651- /*
652- * Reduce default pause to speed up test execution. Pause only needs to be long enough that each part of the
653- * request is read separately.
654- */
655- client .setRequestPause (200 );
656661 client .connect ();
657- client .sendRequest ();
662+ int bodyBytesSent = 0 ;
663+ for (int i = 0 ; i < requestBody .length ; i ++) {
664+ client .setRequest (new String [] { requestBody [i ] });
665+ client .sendRequest ();
666+ bodyBytesSent += i == 0 ? firstBodyLength :
667+ requestBody [i ].getBytes (StandardCharsets .ISO_8859_1 ).length ;
668+ if (i + 1 < requestBody .length ) {
669+ // Include chunk headers and trailers, which need not produce an application read callback.
670+ readProgress .awaitConsumed (bodyBytesSent );
671+ }
672+ }
658673
659674 client .setUseContentLength (true );
660675 client .readResponse (true );
@@ -665,13 +680,95 @@ private void doTestNonBlockingReadChunked(String[] requestBody, String expectedT
665680
666681
667682 private static class Client extends SimpleHttpClient {
683+ @ Override
684+ protected OutputStream createOutputStream (Socket socket ) throws IOException {
685+ socket .setTcpNoDelay (true );
686+ return super .createOutputStream (socket );
687+ }
688+
668689 @ Override
669690 public boolean isResponseBodyOK () {
670691 return "OK" .equals (getResponseBody ());
671692 }
672693 }
673694
674695
696+ private static class ReadProgress implements InputBuffer {
697+
698+ private InputBuffer buffer ;
699+ private long bytesRead ;
700+ private long exhaustedAt = -1 ;
701+
702+ void observe (AsyncContext context ) throws ServletException {
703+ try {
704+ org .apache .catalina .connector .Request request =
705+ (org .apache .catalina .connector .Request ) CTX_REQUEST_FIELD .get (context );
706+ Http11InputBuffer input = (Http11InputBuffer ) request .getCoyoteRequest ().getInputBuffer ();
707+ Field filtersField = Http11InputBuffer .class .getDeclaredField ("filterLibrary" );
708+ filtersField .setAccessible (true );
709+ InputFilter [] filters = (InputFilter []) filtersField .get (input );
710+ ChunkedInputFilter chunked = (ChunkedInputFilter ) filters [Constants .CHUNKED_FILTER ];
711+ Field bufferField = ChunkedInputFilter .class .getDeclaredField ("buffer" );
712+ bufferField .setAccessible (true );
713+ buffer = (InputBuffer ) bufferField .get (chunked );
714+ // Observe the original raw input without changing the chunk parser or its buffered data.
715+ chunked .setBuffer (this );
716+ } catch (ReflectiveOperationException e ) {
717+ throw new ServletException (e );
718+ }
719+ }
720+
721+ @ Override
722+ public int doRead (ApplicationBufferHandler handler ) throws IOException {
723+ int read = buffer .doRead (handler );
724+ synchronized (this ) {
725+ if (read > 0 ) {
726+ bytesRead += read ;
727+ } else if (read == 0 ) {
728+ exhaustedAt = bytesRead ;
729+ notifyAll ();
730+ }
731+ }
732+ return read ;
733+ }
734+
735+ @ Override
736+ public int available () {
737+ int available = buffer .available ();
738+ if (available == 0 ) {
739+ synchronized (this ) {
740+ exhaustedAt = bytesRead ;
741+ notifyAll ();
742+ }
743+ }
744+ return available ;
745+ }
746+
747+ synchronized void awaitConsumed (int expected ) throws IOException {
748+ long deadline = System .nanoTime () + TimeUnit .SECONDS .toNanos (10 );
749+ while (exhaustedAt < expected ) {
750+ long remaining = deadline - System .nanoTime ();
751+ if (remaining <= 0 ) {
752+ throw new IOException ("Chunk parser did not exhaust fragment ending at byte " + expected );
753+ }
754+ try {
755+ TimeUnit .NANOSECONDS .timedWait (this , remaining );
756+ } catch (InterruptedException e ) {
757+ Thread .currentThread ().interrupt ();
758+ throw new IOException (e );
759+ }
760+ }
761+ }
762+ }
763+
764+
765+ private static class WriteProgress {
766+ final CountDownLatch blocked = new CountDownLatch (1 );
767+ final CountDownLatch resumed = new CountDownLatch (1 );
768+ final CountDownLatch completed = new CountDownLatch (1 );
769+ }
770+
771+
675772 @ Test
676773 public void testNonBlockingWrite () throws Exception {
677774 testNonBlockingWriteInternal (false );
@@ -684,12 +781,13 @@ public void testNonBlockingWriteWithKeepAlive() throws Exception {
684781
685782 private void testNonBlockingWriteInternal (boolean keepAlive ) throws Exception {
686783 AtomicBoolean asyncContextIsComplete = new AtomicBoolean (false );
784+ WriteProgress writeProgress = new WriteProgress ();
687785
688786 Tomcat tomcat = getTomcatInstance ();
689787 // No file system docBase required
690788 Context ctx = getProgrammaticRootContext ();
691789
692- NBWriteServlet servlet = new NBWriteServlet (asyncContextIsComplete );
790+ NBWriteServlet servlet = new NBWriteServlet (asyncContextIsComplete , false , true , writeProgress );
693791 String servletName = NBWriteServlet .class .getName ();
694792 Tomcat .addServlet (ctx , servletName , servlet );
695793 ctx .addServletMapping ("/" , servletName );
@@ -700,7 +798,10 @@ private void testNonBlockingWriteInternal(boolean keepAlive) throws Exception {
700798 tomcat .start ();
701799
702800 SocketFactory factory = SocketFactory .getDefault ();
703- Socket s = factory .createSocket ("localhost" , getPort ());
801+ Socket s = factory .createSocket ();
802+ // Keep the receive buffer smaller than the response to ensure that writes encounter backpressure.
803+ s .setReceiveBufferSize (CHUNK_SIZE );
804+ s .connect (new InetSocketAddress ("localhost" , getPort ()), 10000 );
704805
705806 InputStream is = s .getInputStream ();
706807 byte [] buffer = new byte [8192 ];
@@ -724,22 +825,15 @@ private void testNonBlockingWriteInternal(boolean keepAlive) throws Exception {
724825 .getBytes (StandardCharsets .ISO_8859_1 ));
725826 os .flush ();
726827
828+ Assert .assertTrue ("Server did not encounter write backpressure" ,
829+ writeProgress .blocked .await (10 , TimeUnit .SECONDS ));
830+
727831 int read = 0 ;
728- int readSinceLastPause = 0 ;
729832 while (read != -1 ) {
730833 read = is .read (buffer );
731- if (readSinceLastPause == 0 ) {
732- log .info ("Reading data" );
733- }
734834 if (read > 0 ) {
735835 result .append (buffer , 0 , read );
736836 }
737- readSinceLastPause += read ;
738- if (readSinceLastPause > WRITE_SIZE / 16 ) {
739- log .info ("Read " + readSinceLastPause + " bytes, pause 500ms" );
740- readSinceLastPause = 0 ;
741- Thread .sleep (500 );
742- }
743837 }
744838
745839 os .close ();
@@ -839,7 +933,10 @@ private void testNonBlockingWriteInternal(boolean keepAlive) throws Exception {
839933 }
840934
841935 Assert .assertEquals (WRITE_SIZE , totalBodyRead );
842- Assert .assertTrue ("AsyncContext should have been completed." , asyncContextIsComplete .get ());
936+ Assert .assertTrue ("Server did not resume writing after backpressure" ,
937+ writeProgress .resumed .await (10 , TimeUnit .SECONDS ));
938+ Assert .assertTrue ("AsyncContext should have been completed." ,
939+ writeProgress .completed .await (10 , TimeUnit .SECONDS ) && asyncContextIsComplete .get ());
843940 }
844941
845942
@@ -1039,19 +1136,29 @@ public static class NBReadServlet extends TesterServlet {
10391136 private final boolean async ;
10401137 private final boolean ignoreIsReady ;
10411138 private final String expectedTrailerFieldValue ;
1139+ private final transient ReadProgress readProgress ;
10421140 transient TestReadListener listener ;
10431141
10441142 public NBReadServlet (boolean ignoreIsReady , boolean async , String expectedTrailerFieldValue ) {
1143+ this (ignoreIsReady , async , expectedTrailerFieldValue , null );
1144+ }
1145+
1146+ private NBReadServlet (boolean ignoreIsReady , boolean async , String expectedTrailerFieldValue ,
1147+ ReadProgress readProgress ) {
10451148 this .async = async ;
10461149 this .ignoreIsReady = ignoreIsReady ;
10471150 this .expectedTrailerFieldValue = expectedTrailerFieldValue ;
1151+ this .readProgress = readProgress ;
10481152 }
10491153
10501154 @ Override
10511155 protected void service (HttpServletRequest req , HttpServletResponse resp ) throws ServletException , IOException {
10521156 // step 1 - start async
10531157 AsyncContext actx = req .startAsync ();
10541158 actx .setTimeout (Long .MAX_VALUE );
1159+ if (readProgress != null ) {
1160+ readProgress .observe (actx );
1161+ }
10551162 actx .addListener (new AsyncListener () {
10561163
10571164 @ Override
@@ -1095,6 +1202,7 @@ public static class NBWriteServlet extends TesterServlet {
10951202 private final AtomicBoolean asyncContextIsComplete ;
10961203 private final boolean unlimited ;
10971204 private final boolean listenerCompletesOnError ;
1205+ private final transient WriteProgress writeProgress ;
10981206 public transient volatile TestWriteListener wlistener ;
10991207
11001208 public NBWriteServlet (AtomicBoolean asyncContextIsComplete ) {
@@ -1104,9 +1212,15 @@ public NBWriteServlet(AtomicBoolean asyncContextIsComplete) {
11041212
11051213 public NBWriteServlet (AtomicBoolean asyncContextIsComplete , boolean unlimited ,
11061214 boolean listenerCompletesOnError ) {
1215+ this (asyncContextIsComplete , unlimited , listenerCompletesOnError , null );
1216+ }
1217+
1218+ private NBWriteServlet (AtomicBoolean asyncContextIsComplete , boolean unlimited ,
1219+ boolean listenerCompletesOnError , WriteProgress writeProgress ) {
11071220 this .asyncContextIsComplete = asyncContextIsComplete ;
11081221 this .unlimited = unlimited ;
11091222 this .listenerCompletesOnError = listenerCompletesOnError ;
1223+ this .writeProgress = writeProgress ;
11101224 }
11111225
11121226
@@ -1139,12 +1253,15 @@ public void onError(AsyncEvent event) throws IOException {
11391253 public void onComplete (AsyncEvent event ) throws IOException {
11401254 log .info ("onComplete" );
11411255 asyncContextIsComplete .set (true );
1256+ if (writeProgress != null ) {
1257+ writeProgress .completed .countDown ();
1258+ }
11421259 }
11431260 });
11441261 // step 2 - notify on read
11451262 ServletOutputStream out = resp .getOutputStream ();
11461263 resp .setBufferSize (200 * 1024 );
1147- wlistener = new TestWriteListener (actx , unlimited );
1264+ wlistener = new TestWriteListener (actx , unlimited , writeProgress );
11481265 out .setWriteListener (wlistener );
11491266 }
11501267
@@ -1239,6 +1356,8 @@ public void onError(Throwable throwable) {
12391356
12401357 private static class TestAsyncReadListener extends TestReadListener {
12411358
1359+ private final ExecutorService executor = Executors .newSingleThreadExecutor ();
1360+
12421361 AtomicInteger isReadyCount = new AtomicInteger (0 );
12431362 AtomicInteger notReadyCount = new AtomicInteger (0 );
12441363 AtomicInteger containerThreadCount = new AtomicInteger (0 );
@@ -1263,7 +1382,7 @@ public void onDataAvailable() throws IOException {
12631382 } else {
12641383 nonContainerThreadCount .incrementAndGet ();
12651384 }
1266- new Thread () {
1385+ executor . execute ( new Runnable () {
12671386 @ Override
12681387 public void run () {
12691388 try {
@@ -1287,18 +1406,20 @@ public void run() {
12871406 onError (ioe );
12881407 }
12891408 }
1290- }. start ( );
1409+ });
12911410 }
12921411
12931412 @ Override
12941413 public void onAllDataRead () {
1414+ executor .shutdown ();
12951415 super .onAllDataRead ();
12961416 log .info ("isReadyCount=" + isReadyCount + " notReadyCount=" + notReadyCount + " containerThreadCount=" +
12971417 containerThreadCount + " nonContainerThreadCount=" + nonContainerThreadCount );
12981418 }
12991419
13001420 @ Override
13011421 public void onError (Throwable throwable ) {
1422+ executor .shutdown ();
13021423 super .onError (throwable );
13031424 log .info ("isReadyCount=" + isReadyCount + " notReadyCount=" + notReadyCount + " containerThreadCount=" +
13041425 containerThreadCount + " nonContainerThreadCount=" + nonContainerThreadCount );
@@ -1308,19 +1429,30 @@ public void onError(Throwable throwable) {
13081429 private static class TestWriteListener implements WriteListener {
13091430 AsyncContext ctx ;
13101431 private final boolean unlimited ;
1432+ private final WriteProgress writeProgress ;
13111433 int written = 0 ;
13121434 public volatile boolean onErrorInvoked = false ;
13131435
1314- TestWriteListener (AsyncContext ctx , boolean unlimited ) {
1436+ TestWriteListener (AsyncContext ctx , boolean unlimited , WriteProgress writeProgress ) {
13151437 this .ctx = ctx ;
13161438 this .unlimited = unlimited ;
1439+ this .writeProgress = writeProgress ;
13171440 }
13181441
13191442 @ Override
13201443 public void onWritePossible () throws IOException {
1444+ if (writeProgress != null && writeProgress .blocked .getCount () == 0 ) {
1445+ writeProgress .resumed .countDown ();
1446+ }
13211447 long start = System .currentTimeMillis ();
13221448 int before = written ;
1323- while ((written < WRITE_SIZE || unlimited ) && ctx .getResponse ().getOutputStream ().isReady ()) {
1449+ while (written < WRITE_SIZE || unlimited ) {
1450+ if (!ctx .getResponse ().getOutputStream ().isReady ()) {
1451+ if (writeProgress != null ) {
1452+ writeProgress .blocked .countDown ();
1453+ }
1454+ break ;
1455+ }
13241456 ctx .getResponse ().getOutputStream ().write (DATA , written , CHUNK_SIZE );
13251457 written += CHUNK_SIZE ;
13261458 }
@@ -1336,6 +1468,8 @@ public void onWritePossible() throws IOException {
13361468 // it is illegal to call complete
13371469 // if there is a write in progress
13381470 ctx .complete ();
1471+ } else if (writeProgress != null ) {
1472+ writeProgress .blocked .countDown ();
13391473 }
13401474 }
13411475
@@ -2355,4 +2489,4 @@ public void onError(Throwable throwable) {
23552489 throwable .printStackTrace ();
23562490 }
23572491 }
2358- }
2492+ }
0 commit comments