/
AsyncCompletionTest.java
410 lines (367 loc) · 14.3 KB
/
AsyncCompletionTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//
// ========================================================================
// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.server;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Stream;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.http.HttpCompliance;
import org.eclipse.jetty.http.HttpTester;
import org.eclipse.jetty.io.ChannelEndPoint;
import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.ManagedSelector;
import org.eclipse.jetty.io.SocketChannelEndPoint;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.thread.Scheduler;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
/**
* Extended Server Tester.
*/
public class AsyncCompletionTest extends HttpServerTestFixture
{
private static final Exchanger<PendingCallback> X = new Exchanger<>();
private static final AtomicBoolean __complete = new AtomicBoolean();
private static String __data = "Now is the time for all good men to come to the aid of the party";
private static class PendingCallback extends Callback.Nested
{
private CompletableFuture<Void> _pending = new CompletableFuture<>();
public PendingCallback(Callback callback)
{
super(callback);
}
@Override
public void succeeded()
{
_pending.complete(null);
}
@Override
public void failed(Throwable x)
{
_pending.completeExceptionally(x);
}
public void proceed()
{
try
{
_pending.get(10, TimeUnit.SECONDS);
getCallback().succeeded();
}
catch (Throwable th)
{
th.printStackTrace();
getCallback().failed(th);
}
}
}
@BeforeEach
public void init() throws Exception
{
__complete.set(false);
startServer(new ServerConnector(_server, new HttpConnectionFactory()
{
@Override
public Connection newConnection(Connector connector, EndPoint endPoint)
{
return configure(new ExtendedHttpConnection(getHttpConfiguration(), connector, endPoint), connector, endPoint);
}
})
{
@Override
protected ChannelEndPoint newEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey key) throws IOException
{
return new ExtendedEndPoint(channel, selectSet, key, getScheduler());
}
});
}
private static class ExtendedEndPoint extends SocketChannelEndPoint
{
public ExtendedEndPoint(SocketChannel channel, ManagedSelector selector, SelectionKey key, Scheduler scheduler)
{
super(channel, selector, key, scheduler);
}
@Override
public void write(Callback callback, ByteBuffer... buffers) throws IllegalStateException
{
PendingCallback delay = new PendingCallback(callback);
super.write(delay, buffers);
try
{
X.exchange(delay);
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
}
}
private static class ExtendedHttpConnection extends HttpConnection
{
public ExtendedHttpConnection(HttpConfiguration config, Connector connector, EndPoint endPoint)
{
super(config, connector, endPoint, HttpCompliance.RFC7230_LEGACY, false);
}
@Override
public void onCompleted()
{
__complete.compareAndSet(false,true);
super.onCompleted();
}
}
// Tests from here use these parameters
public static Stream<Arguments> tests()
{
List<Object[]> tests = new ArrayList<>();
tests.add(new Object[]{new HelloWorldHandler(), false, 200, "Hello world"});
tests.add(new Object[]{new SendErrorHandler(499, "Test async sendError"), false, 499, "Test async sendError"});
tests.add(new Object[]{new AsyncReadyCompleteHandler(), false, 200, __data});
tests.add(new Object[]{new AsyncWriteCompleteHandler(false, false), false, 200, __data});
tests.add(new Object[]{new AsyncWriteCompleteHandler(false, true), false, 200, __data});
tests.add(new Object[]{new AsyncWriteCompleteHandler(true, false), false, 200, __data});
tests.add(new Object[]{new AsyncWriteCompleteHandler(true, true), false, 200, __data});
tests.add(new Object[]{new BlockingWriteCompleteHandler(), true, 200, __data});
return tests.stream().map(Arguments::of);
}
@ParameterizedTest
@MethodSource("tests")
public void testAsyncCompletion(Handler handler, boolean blocked, int status, String message) throws Exception
{
configureServer(handler);
int base = _threadPool.getBusyThreads();
try (Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort()))
{
OutputStream os = client.getOutputStream();
// write the request
os.write("GET / HTTP/1.0\r\n\r\n".getBytes(StandardCharsets.ISO_8859_1));
os.flush();
// The write should happen but the callback is delayed
HttpTester.Response response = HttpTester.parseResponse(client.getInputStream());
assertThat(response, Matchers.notNullValue());
assertThat(response.getStatus(), is(status));
String content = response.getContent();
assertThat(content, containsString(message));
// Check that a thread is held busy in write
assertThat(_threadPool.getBusyThreads(), Matchers.greaterThan(base)); // TODO why is this the case for async?
// Getting the Delayed callback will free the thread
PendingCallback delay = X.exchange(null, 10, TimeUnit.SECONDS);
// wait for threads to return to base level
long end = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
while (_threadPool.getBusyThreads() != base + (blocked ? 1 : 0))
{
if (System.nanoTime() > end)
throw new TimeoutException();
Thread.sleep(10);
}
// We are now asynchronously waiting!
assertThat(__complete.get(), is(false));
// Do we need to wait for an unready state?
if (handler instanceof AsyncWriteCompleteHandler)
{
AsyncWriteCompleteHandler awch = (AsyncWriteCompleteHandler)handler;
if (awch._unReady)
assertThat(awch._unReadySeen.await(5, TimeUnit.SECONDS),is(true));
}
// proceed with the completion
delay.proceed();
while(!__complete.get())
{
if (System.nanoTime() > end)
throw new TimeoutException();
Thread.sleep(10);
}
}
}
private static class AsyncReadyCompleteHandler extends AbstractHandler
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
// start async
// register WriteListener
// if ready write bytes
// if ready complete
AsyncContext context = request.startAsync();
ServletOutputStream out = response.getOutputStream();
out.setWriteListener(new WriteListener()
{
byte[] bytes = __data.getBytes(StandardCharsets.ISO_8859_1);
@Override
public void onWritePossible() throws IOException
{
while (out.isReady())
{
if (bytes != null)
{
response.setContentType("text/plain");
response.setContentLength(bytes.length);
out.write(bytes);
bytes = null;
}
else
{
context.complete();
return;
}
}
}
@Override
public void onError(Throwable t)
{
t.printStackTrace();
}
});
}
}
private static class AsyncWriteCompleteHandler extends AbstractHandler
{
final boolean _unReady;
final boolean _close;
final CountDownLatch _unReadySeen = new CountDownLatch(1);
boolean _written;
AsyncWriteCompleteHandler(boolean unReady, boolean close)
{
_unReady = unReady;
_close = close;
}
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
// start async
// register WriteListener
// if ready
// if not written write bytes
// if _unReady check that isReady() returns false and return
// if _close then call close without checking isReady()
// context.complete() without checking is ready
AsyncContext context = request.startAsync();
ServletOutputStream out = response.getOutputStream();
out.setWriteListener(new WriteListener() {
byte[] bytes = __data.getBytes(StandardCharsets.ISO_8859_1);
@Override
public void onWritePossible() throws IOException
{
if (out.isReady())
{
if (!_written)
{
_written = true;
response.setContentType("text/plain");
response.setContentLength(bytes.length);
out.write(bytes);
}
if (_unReady && _unReadySeen.getCount() == 1)
{
assertThat(out.isReady(), Matchers.is(false));
_unReadySeen.countDown();
return;
}
if (_close)
{
out.close();
}
context.complete();
}
}
@Override
public void onError(Throwable t)
{
t.printStackTrace();
}
});
}
@Override
public String toString()
{
return String.format("AWCH@%x{ur=%b,c=%b}", hashCode(), _unReady, _close);
}
}
private static class BlockingWriteCompleteHandler extends AbstractHandler
{
final CountDownLatch _unReadySeen = new CountDownLatch(1);
boolean _written;
BlockingWriteCompleteHandler()
{
}
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
// Start async
// Do a blocking write in another thread
// call complete while the write is still blocking
AsyncContext context = request.startAsync();
ServletOutputStream out = response.getOutputStream();
CountDownLatch writing = new CountDownLatch(1);
context.start(() ->
{
try
{
byte[] bytes = __data.getBytes(StandardCharsets.ISO_8859_1);
response.setContentType("text/plain");
response.setContentLength(bytes.length);
writing.countDown();
out.write(bytes);
}
catch(Exception e)
{
e.printStackTrace();
}
});
try
{
writing.await(5, TimeUnit.SECONDS);
Thread.sleep(200);
context.complete();
}
catch(Exception e)
{
throw new ServletException(e);
}
}
@Override
public String toString()
{
return String.format("%s@%x{}", this.getClass().getSimpleName(), hashCode());
}
}
}