aboutsummaryrefslogtreecommitdiffstats
path: root/container-core/src/test/java/com/yahoo/container/jdisc/ThreadedRequestHandlerTestCase.java
blob: 5dc9df65eed2f9050223b19c7394992a4d321ba5 (plain) (blame)
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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc;

import com.yahoo.jdisc.Request;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.application.ContainerBuilder;
import com.yahoo.jdisc.handler.*;
import com.yahoo.jdisc.test.TestDriver;
import com.yahoo.yolean.Exceptions;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import static org.junit.jupiter.api.Assertions.*;

/**
 * @author Simon Thoresen Hult
 */
public class ThreadedRequestHandlerTestCase {

    @Test
    void requireThatNullExecutorThrowsException() {
        try {
            new ThreadedRequestHandler(null) {

                @Override
                public void handleRequest(Request request, BufferedContentChannel content, ResponseHandler handler) {

                }
            };
            fail();
        } catch (NullPointerException e) {

        }
    }

    @Test
    void requireThatHandlerSetsRequestTimeout() throws InterruptedException {
        Executor executor = Executors.newSingleThreadExecutor();
        TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
        ContainerBuilder builder = driver.newContainerBuilder();
        MyRequestHandler requestHandler = MyRequestHandler.newInstance(executor);
        builder.serverBindings().bind("http://localhost/", requestHandler);
        driver.activateContainer(builder);

        MyResponseHandler responseHandler = new MyResponseHandler();
        driver.dispatchRequest("http://localhost/", responseHandler);

        requestHandler.entryLatch.countDown();
        assertTrue(requestHandler.exitLatch.await(60, TimeUnit.SECONDS));
        assertNull(requestHandler.content.read());
        assertNotNull(requestHandler.request.getTimeout(TimeUnit.MILLISECONDS));

        assertTrue(responseHandler.latch.await(60, TimeUnit.SECONDS));
        assertNull(responseHandler.content.read());
        assertTrue(driver.close());
    }

    @Test
    void requireThatOverriddenRequestTimeoutIsUsed() throws InterruptedException {
        Executor executor = Executors.newSingleThreadExecutor();
        TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
        ContainerBuilder builder = driver.newContainerBuilder();
        MyRequestHandler requestHandler = MyRequestHandler.newWithTimeout(executor, Duration.ofSeconds(1));
        builder.serverBindings().bind("http://localhost/", requestHandler);
        driver.activateContainer(builder);

        MyResponseHandler responseHandler = new MyResponseHandler();
        driver.dispatchRequest("http://localhost/", responseHandler);

        requestHandler.entryLatch.countDown();
        assertTrue(requestHandler.exitLatch.await(60, TimeUnit.SECONDS));
        assertEquals(1, (long) requestHandler.request.getTimeout(TimeUnit.SECONDS));

        assertTrue(responseHandler.latch.await(60, TimeUnit.SECONDS));
        assertNull(responseHandler.content.read());
        assertTrue(driver.close());
    }

    @Test
    void requireThatRequestAndResponseReachHandlers() throws InterruptedException {
        Executor executor = Executors.newSingleThreadExecutor();
        TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
        ContainerBuilder builder = driver.newContainerBuilder();
        MyRequestHandler requestHandler = MyRequestHandler.newInstance(executor);
        builder.serverBindings().bind("http://localhost/", requestHandler);
        driver.activateContainer(builder);

        MyResponseHandler responseHandler = new MyResponseHandler();
        Request request = new Request(driver, URI.create("http://localhost/"));
        ContentChannel requestContent = request.connect(responseHandler);
        ByteBuffer buf = ByteBuffer.allocate(69);
        requestContent.write(buf, null);
        requestContent.close(null);
        request.release();

        requestHandler.entryLatch.countDown();
        assertTrue(requestHandler.exitLatch.await(60, TimeUnit.SECONDS));
        assertSame(request, requestHandler.request);
        assertSame(buf, requestHandler.content.read());
        assertNull(requestHandler.content.read());

        assertTrue(responseHandler.latch.await(60, TimeUnit.SECONDS));
        assertSame(requestHandler.response, responseHandler.response);
        assertNull(responseHandler.content.read());
        assertTrue(driver.close());
    }

    @Test
    void requireThatRejectedExecutionIsHandledGracefully() throws Exception {
        // Instrumentation.
        final Executor executor = new Executor() {
            @Override
            public void execute(final Runnable command) {
                throw new RejectedExecutionException("Deliberately thrown; simulating overloaded executor");
            }
        };
        final RequestHandler requestHandler = new ThreadedRequestHandler(executor) {
            @Override
            protected void handleRequest(Request request, BufferedContentChannel requestContent, ResponseHandler responseHandler) {
                throw new AssertionError("Should never get here");
            }
        };

        // Setup.
        final TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
        final ContainerBuilder builder = driver.newContainerBuilder();
        builder.serverBindings().bind("http://localhost/", requestHandler);
        driver.activateContainer(builder);
        final MyResponseHandler responseHandler = new MyResponseHandler();

        // Execution.
        try {
            driver.dispatchRequest("http://localhost/", responseHandler);
            fail("Above statement should throw exception");
        } catch (OverloadException e) {
            // As expected.
        }

        // Verification.
        assertEquals(0, responseHandler.latch.getCount(), "Response handler should be invoked synchronously in this case.");
        assertEquals(Response.Status.SERVICE_UNAVAILABLE, responseHandler.response.getStatus());
        assertNull(responseHandler.content.read());
        assertTrue(driver.close());
    }

    @Test
    void requireThatRequestContentIsClosedIfHandlerIgnoresIt() throws InterruptedException {
        Executor executor = Executors.newSingleThreadExecutor();
        TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
        ContainerBuilder builder = driver.newContainerBuilder();
        MyRequestHandler requestHandler = MyRequestHandler.newIgnoreContent(executor);
        builder.serverBindings().bind("http://localhost/", requestHandler);
        driver.activateContainer(builder);

        MyResponseHandler responseHandler = new MyResponseHandler();
        ContentChannel content = driver.connectRequest("http://localhost/", responseHandler);
        MyCompletion writeCompletion = new MyCompletion();
        content.write(ByteBuffer.allocate(69), writeCompletion);
        MyCompletion closeCompletion = new MyCompletion();
        content.close(closeCompletion);

        requestHandler.entryLatch.countDown();
        assertTrue(requestHandler.exitLatch.await(60, TimeUnit.SECONDS));
        assertTrue(writeCompletion.latch.await(60, TimeUnit.SECONDS));
        assertTrue(writeCompletion.completed);
        assertTrue(closeCompletion.latch.await(60, TimeUnit.SECONDS));
        assertTrue(writeCompletion.completed);

        assertTrue(responseHandler.latch.await(60, TimeUnit.SECONDS));
        assertSame(requestHandler.response, responseHandler.response);
        assertNull(responseHandler.content.read());
        assertTrue(driver.close());
    }

    @Test
    void requireThatResponseIsDispatchedIfHandlerIgnoresIt() throws InterruptedException {
        Executor executor = Executors.newSingleThreadExecutor();
        TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
        ContainerBuilder builder = driver.newContainerBuilder();
        MyRequestHandler requestHandler = MyRequestHandler.newIgnoreResponse(executor);
        builder.serverBindings().bind("http://localhost/", requestHandler);
        driver.activateContainer(builder);

        MyResponseHandler responseHandler = new MyResponseHandler();
        driver.dispatchRequest("http://localhost/", responseHandler);
        requestHandler.entryLatch.countDown();
        assertTrue(requestHandler.exitLatch.await(60, TimeUnit.SECONDS));
        assertNull(requestHandler.content.read());

        assertTrue(responseHandler.latch.await(60, TimeUnit.SECONDS));
        assertEquals(Response.Status.INTERNAL_SERVER_ERROR, responseHandler.response.getStatus());
        assertNull(responseHandler.content.read());
        assertTrue(driver.close());
    }

    @Test
    void requireThatRequestContentIsClosedAndResponseIsDispatchedIfHandlerIgnoresIt()
            throws InterruptedException
    {
        Executor executor = Executors.newSingleThreadExecutor();
        assertThatRequestContentIsClosedAndResponseIsDispatchedIfHandlerIgnoresIt(
                MyRequestHandler.newIgnoreAll(executor));
        assertThatRequestContentIsClosedAndResponseIsDispatchedIfHandlerIgnoresIt(
                MyRequestHandler.newThrowException(executor));
    }

    private static void assertThatRequestContentIsClosedAndResponseIsDispatchedIfHandlerIgnoresIt(
            MyRequestHandler requestHandler)
            throws InterruptedException
    {
        TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
        ContainerBuilder builder = driver.newContainerBuilder();
        builder.serverBindings().bind("http://localhost/", requestHandler);
        driver.activateContainer(builder);

        MyResponseHandler responseHandler = new MyResponseHandler();
        ContentChannel content = driver.connectRequest("http://localhost/", responseHandler);
        MyCompletion writeCompletion = new MyCompletion();
        content.write(ByteBuffer.allocate(69), writeCompletion);
        MyCompletion closeCompletion = new MyCompletion();
        content.close(closeCompletion);

        requestHandler.entryLatch.countDown();
        assertTrue(requestHandler.exitLatch.await(60, TimeUnit.SECONDS));
        assertTrue(writeCompletion.latch.await(60, TimeUnit.SECONDS));
        assertTrue(writeCompletion.completed);
        assertTrue(closeCompletion.latch.await(60, TimeUnit.SECONDS));
        assertTrue(writeCompletion.completed);

        assertTrue(responseHandler.latch.await(60, TimeUnit.SECONDS));
        assertEquals(Response.Status.INTERNAL_SERVER_ERROR, responseHandler.response.getStatus());
        assertNull(responseHandler.content.read());
        assertTrue(driver.close());
    }

    private static class MyRequestHandler extends ThreadedRequestHandler {

        final CountDownLatch entryLatch = new CountDownLatch(1);
        final CountDownLatch exitLatch = new CountDownLatch(1);
        final ReadableContentChannel content = new ReadableContentChannel();
        final boolean consumeContent;
        final boolean createResponse;
        final boolean throwException;
        final Duration timeout;
        Response response = null;
        Request request = null;

        MyRequestHandler(Executor executor,
                         boolean consumeContent,
                         boolean createResponse,
                         boolean throwException,
                         Duration timeout) {
            super(executor);
            this.consumeContent = consumeContent;
            this.createResponse = createResponse;
            this.throwException = throwException;
            this.timeout = timeout;
        }

        @Override
        public void handleRequest(Request request, BufferedContentChannel content, ResponseHandler handler) {
            try {
                if (!entryLatch.await(60, TimeUnit.SECONDS)) {
                    return;
                }
                if (throwException) {
                    throw new RuntimeException();
                }
                this.request = request;
                if (consumeContent) {
                    content.connectTo(this.content);
                }
                if (createResponse) {
                    response = new Response(Response.Status.OK);
                    handler.handleResponse(response).close(null);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                exitLatch.countDown();
            }
        }

        @Override
        public Duration getTimeout() {
            if (timeout == null) return super.getTimeout();
            return timeout;
        }

        static MyRequestHandler newInstance(Executor executor) {
            return new MyRequestHandler(executor, true, true, false, null);
        }

        static MyRequestHandler newThrowException(Executor executor) {
            return new MyRequestHandler(executor, true, true, true, null);
        }

        static MyRequestHandler newIgnoreContent(Executor executor) {
            return new MyRequestHandler(executor, false, true, false, null);
        }

        static MyRequestHandler newIgnoreResponse(Executor executor) {
            return new MyRequestHandler(executor, true, false, false, null);
        }

        static MyRequestHandler newIgnoreAll(Executor executor) {
            return new MyRequestHandler(executor, false, false, false, null);
        }

        static MyRequestHandler newWithTimeout(Executor executor, Duration timeout) {
            return new MyRequestHandler(executor, false, false, false, timeout);
        }
    }

    private static class MyResponseHandler implements ResponseHandler {

        final CountDownLatch latch = new CountDownLatch(1);
        final ReadableContentChannel content = new ReadableContentChannel();
        Response response = null;

        @Override
        public ContentChannel handleResponse(Response response) {
            this.response = response;
            latch.countDown();

            BufferedContentChannel content = new BufferedContentChannel();
            content.connectTo(this.content);
            return content;
        }
    }

    private static class MyCompletion implements CompletionHandler {

        final CountDownLatch latch = new CountDownLatch(1);
        boolean completed;

        @Override
        public void completed() {
            completed = true;
            latch.countDown();
        }

        @Override
        public void failed(Throwable t) {
            latch.countDown();
        }
    }

    @Test
    void testMaxPendingOutputStream() throws IOException, ExecutionException, InterruptedException {
        ReadableContentChannel buffer = new ReadableContentChannel();
        MaxPendingContentChannelOutputStream limited = new MaxPendingContentChannelOutputStream(buffer, 2);

        ExecutorService executor = Executors.newSingleThreadExecutor();

        limited.send(ByteBuffer.allocate(2));
        limited.send(ByteBuffer.allocate(1)); // 2 is not > 2, so OK.

        // Next write will block.
        Future<?> future = executor.submit(() -> Exceptions.uncheck(() -> limited.send(ByteBuffer.allocate(0))));
        try {
            future.get(100, TimeUnit.MILLISECONDS);
            fail("Should not be able to write now");
        }
        catch (TimeoutException expected) {
        }

        // Free buffer capacity, so write completes, then drain buffer.
        assertEquals(2, buffer.read().capacity());
        future.get();
        buffer.close(null);
        assertEquals(1, buffer.read().capacity());
        assertEquals(0, buffer.read().capacity());
        assertNull(buffer.read());

        // Buffer is closed, so further writes fail. This does not count towards pending bytes.
        try {
            limited.send(ByteBuffer.allocate(3));
            fail("Should throw");
        }
        catch (IOException expected) {
        }
        try {
            limited.send(ByteBuffer.allocate(3));
            fail("Should throw");
        }
        catch (IOException expected) {
        }
    }

}