use of org.eclipse.jetty.util.Callback in project jetty.project by eclipse.
the class SelectorManagerTest method testConnectTimeoutBeforeSuccessfulConnect.
@Slow
@Test
public void testConnectTimeoutBeforeSuccessfulConnect() throws Exception {
ServerSocketChannel server = ServerSocketChannel.open();
server.bind(new InetSocketAddress("localhost", 0));
SocketAddress address = server.getLocalAddress();
final AtomicLong timeoutConnection = new AtomicLong();
final long connectTimeout = 1000;
SelectorManager selectorManager = new SelectorManager(executor, scheduler) {
@Override
protected EndPoint newEndPoint(SelectableChannel channel, ManagedSelector selector, SelectionKey key) throws IOException {
SocketChannelEndPoint endp = new SocketChannelEndPoint(channel, selector, key, getScheduler());
endp.setIdleTimeout(connectTimeout / 2);
return endp;
}
@Override
protected boolean doFinishConnect(SelectableChannel channel) throws IOException {
try {
long timeout = timeoutConnection.get();
if (timeout > 0)
TimeUnit.MILLISECONDS.sleep(timeout);
return super.doFinishConnect(channel);
} catch (InterruptedException e) {
return false;
}
}
@Override
public Connection newConnection(SelectableChannel channel, EndPoint endpoint, Object attachment) throws IOException {
((Callback) attachment).succeeded();
return new AbstractConnection(endpoint, executor) {
@Override
public void onFillable() {
}
};
}
@Override
protected void connectionFailed(SelectableChannel channel, Throwable ex, Object attachment) {
((Callback) attachment).failed(ex);
}
};
selectorManager.setConnectTimeout(connectTimeout);
selectorManager.start();
try {
SocketChannel client1 = SocketChannel.open();
client1.configureBlocking(false);
client1.connect(address);
long timeout = connectTimeout * 2;
timeoutConnection.set(timeout);
final CountDownLatch latch1 = new CountDownLatch(1);
selectorManager.connect(client1, new Callback() {
@Override
public void failed(Throwable x) {
latch1.countDown();
}
});
Assert.assertTrue(latch1.await(connectTimeout * 3, TimeUnit.MILLISECONDS));
Assert.assertFalse(client1.isOpen());
// Wait for the first connect to finish, as the selector thread is waiting in finishConnect().
Thread.sleep(timeout);
// Verify that after the failure we can connect successfully.
try (SocketChannel client2 = SocketChannel.open()) {
client2.configureBlocking(false);
client2.connect(address);
timeoutConnection.set(0);
final CountDownLatch latch2 = new CountDownLatch(1);
selectorManager.connect(client2, new Callback() {
@Override
public void succeeded() {
latch2.countDown();
}
});
Assert.assertTrue(latch2.await(connectTimeout * 5, TimeUnit.MILLISECONDS));
Assert.assertTrue(client2.isOpen());
}
} finally {
selectorManager.stop();
}
}
use of org.eclipse.jetty.util.Callback in project jetty.project by eclipse.
the class StreamCloseTest method testPushedStreamResetIsClosed.
@Test
public void testPushedStreamResetIsClosed() throws Exception {
final CountDownLatch serverLatch = new CountDownLatch(1);
start(new ServerSessionListener.Adapter() {
@Override
public Stream.Listener onNewStream(final Stream stream, HeadersFrame frame) {
PushPromiseFrame pushFrame = new PushPromiseFrame(stream.getId(), 0, newRequest("GET", new HttpFields()));
stream.push(pushFrame, new Promise.Adapter<>(), new Stream.Listener.Adapter() {
@Override
public void onReset(Stream pushedStream, ResetFrame frame) {
Assert.assertTrue(pushedStream.isReset());
Assert.assertTrue(pushedStream.isClosed());
HeadersFrame response = new HeadersFrame(stream.getId(), new MetaData.Response(HttpVersion.HTTP_2, 200, new HttpFields()), null, true);
stream.headers(response, Callback.NOOP);
serverLatch.countDown();
}
});
return null;
}
});
Session session = newClient(new Session.Listener.Adapter());
HeadersFrame frame = new HeadersFrame(newRequest("GET", new HttpFields()), null, true);
final CountDownLatch clientLatch = new CountDownLatch(2);
session.newStream(frame, new Promise.Adapter<>(), new Stream.Listener.Adapter() {
@Override
public Stream.Listener onPush(final Stream pushedStream, PushPromiseFrame frame) {
pushedStream.reset(new ResetFrame(pushedStream.getId(), ErrorCode.REFUSED_STREAM_ERROR.code), new Callback() {
@Override
public void succeeded() {
Assert.assertTrue(pushedStream.isReset());
Assert.assertTrue(pushedStream.isClosed());
clientLatch.countDown();
}
});
return null;
}
@Override
public void onHeaders(Stream stream, HeadersFrame frame) {
clientLatch.countDown();
}
});
Assert.assertTrue(serverLatch.await(5, TimeUnit.SECONDS));
Assert.assertTrue(clientLatch.await(5, TimeUnit.SECONDS));
}
use of org.eclipse.jetty.util.Callback in project jetty.project by eclipse.
the class StreamCloseTest method testRequestDataClosedResponseDataClosedClosesStream.
@Test
public void testRequestDataClosedResponseDataClosedClosesStream() throws Exception {
final CountDownLatch serverDataLatch = new CountDownLatch(1);
start(new ServerSessionListener.Adapter() {
@Override
public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) {
MetaData.Response metaData = new MetaData.Response(HttpVersion.HTTP_2, 200, new HttpFields());
HeadersFrame response = new HeadersFrame(stream.getId(), metaData, null, false);
Callback.Completable completable = new Callback.Completable();
stream.headers(response, completable);
return new Stream.Listener.Adapter() {
@Override
public void onData(final Stream stream, DataFrame frame, final Callback callback) {
Assert.assertTrue(((HTTP2Stream) stream).isRemotelyClosed());
// We must copy the data that we send asynchronously.
ByteBuffer data = frame.getData();
ByteBuffer copy = ByteBuffer.allocate(data.remaining());
copy.put(data).flip();
completable.thenRun(() -> stream.data(new DataFrame(stream.getId(), copy, frame.isEndStream()), new Callback() {
@Override
public void succeeded() {
Assert.assertTrue(stream.isClosed());
Assert.assertEquals(0, stream.getSession().getStreams().size());
callback.succeeded();
serverDataLatch.countDown();
}
}));
}
};
}
});
final CountDownLatch completeLatch = new CountDownLatch(1);
Session session = newClient(new Session.Listener.Adapter());
HeadersFrame frame = new HeadersFrame(newRequest("GET", new HttpFields()), null, false);
FuturePromise<Stream> promise = new FuturePromise<>();
session.newStream(frame, promise, new Stream.Listener.Adapter() {
@Override
public void onData(Stream stream, DataFrame frame, Callback callback) {
// The sent data callback may not be notified yet here.
callback.succeeded();
completeLatch.countDown();
}
});
final Stream stream = promise.get(5, TimeUnit.SECONDS);
Assert.assertFalse(stream.isClosed());
Assert.assertFalse(((HTTP2Stream) stream).isLocallyClosed());
final CountDownLatch clientDataLatch = new CountDownLatch(1);
stream.data(new DataFrame(stream.getId(), ByteBuffer.wrap(new byte[512]), true), new Callback() {
@Override
public void succeeded() {
// Here the stream may be just locally closed or fully closed.
clientDataLatch.countDown();
}
});
Assert.assertTrue(clientDataLatch.await(5, TimeUnit.SECONDS));
Assert.assertTrue(serverDataLatch.await(5, TimeUnit.SECONDS));
Assert.assertTrue(completeLatch.await(5, TimeUnit.SECONDS));
Assert.assertTrue(stream.isClosed());
Assert.assertEquals(0, stream.getSession().getStreams().size());
}
use of org.eclipse.jetty.util.Callback in project jetty.project by eclipse.
the class StreamCountTest method testServerAllowsOneStreamEnforcedByClient.
@Test
public void testServerAllowsOneStreamEnforcedByClient() throws Exception {
start(new ServerSessionListener.Adapter() {
@Override
public Map<Integer, Integer> onPreface(Session session) {
Map<Integer, Integer> settings = new HashMap<>();
settings.put(SettingsFrame.MAX_CONCURRENT_STREAMS, 1);
return settings;
}
@Override
public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) {
return new Stream.Listener.Adapter() {
@Override
public void onData(Stream stream, DataFrame frame, Callback callback) {
if (frame.isEndStream()) {
HttpFields fields = new HttpFields();
MetaData.Response metaData = new MetaData.Response(HttpVersion.HTTP_2, 200, fields);
stream.headers(new HeadersFrame(stream.getId(), metaData, null, true), callback);
} else {
callback.succeeded();
}
}
};
}
});
final CountDownLatch settingsLatch = new CountDownLatch(1);
Session session = newClient(new Session.Listener.Adapter() {
@Override
public void onSettings(Session session, SettingsFrame frame) {
settingsLatch.countDown();
}
});
Assert.assertTrue(settingsLatch.await(5, TimeUnit.SECONDS));
HttpFields fields = new HttpFields();
MetaData.Request metaData = newRequest("GET", fields);
HeadersFrame frame1 = new HeadersFrame(metaData, null, false);
FuturePromise<Stream> streamPromise1 = new FuturePromise<>();
final CountDownLatch responseLatch = new CountDownLatch(1);
session.newStream(frame1, streamPromise1, new Stream.Listener.Adapter() {
@Override
public void onHeaders(Stream stream, HeadersFrame frame) {
if (frame.isEndStream())
responseLatch.countDown();
}
});
Stream stream1 = streamPromise1.get(5, TimeUnit.SECONDS);
HeadersFrame frame2 = new HeadersFrame(metaData, null, false);
FuturePromise<Stream> streamPromise2 = new FuturePromise<>();
session.newStream(frame2, streamPromise2, new Stream.Listener.Adapter());
try {
streamPromise2.get(5, TimeUnit.SECONDS);
Assert.fail();
} catch (ExecutionException x) {
// Expected
}
stream1.data(new DataFrame(stream1.getId(), BufferUtil.EMPTY_BUFFER, true), Callback.NOOP);
Assert.assertTrue(responseLatch.await(5, TimeUnit.SECONDS));
}
use of org.eclipse.jetty.util.Callback in project jetty.project by eclipse.
the class StreamResetTest method testResetAfterAsyncRequestBlockingWriteStalledByFlowControl.
@Test
public void testResetAfterAsyncRequestBlockingWriteStalledByFlowControl() throws Exception {
int windowSize = FlowControlStrategy.DEFAULT_WINDOW_SIZE;
CountDownLatch writeLatch = new CountDownLatch(1);
start(new HttpServlet() {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
AsyncContext asyncContext = request.startAsync();
asyncContext.start(() -> {
try {
// Make sure we are in async wait before writing.
Thread.sleep(1000);
response.getOutputStream().write(new byte[10 * windowSize]);
asyncContext.complete();
} catch (IOException x) {
writeLatch.countDown();
} catch (Throwable x) {
x.printStackTrace();
}
});
}
});
Deque<Object> dataQueue = new ArrayDeque<>();
AtomicLong received = new AtomicLong();
CountDownLatch latch = new CountDownLatch(1);
Session client = newClient(new Session.Listener.Adapter());
MetaData.Request request = newRequest("GET", new HttpFields());
HeadersFrame frame = new HeadersFrame(request, null, true);
FuturePromise<Stream> promise = new FuturePromise<>();
client.newStream(frame, promise, new Stream.Listener.Adapter() {
@Override
public void onData(Stream stream, DataFrame frame, Callback callback) {
dataQueue.offer(frame);
dataQueue.offer(callback);
// Do not consume the data yet.
if (received.addAndGet(frame.getData().remaining()) == windowSize)
latch.countDown();
}
});
Stream stream = promise.get(5, TimeUnit.SECONDS);
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
// Reset and consume.
stream.reset(new ResetFrame(stream.getId(), ErrorCode.CANCEL_STREAM_ERROR.code), Callback.NOOP);
dataQueue.stream().filter(item -> item instanceof Callback).map(item -> (Callback) item).forEach(Callback::succeeded);
Assert.assertTrue(writeLatch.await(5, TimeUnit.SECONDS));
}
Aggregations