summaryrefslogtreecommitdiffstats
path: root/vespa-http-client/src/test/java/com/yahoo/vespa/http/client/QueueBoundsTest.java
blob: 0813cb36078f7b9225900e995186c21a3f3fd396 (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
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.http.client;

import com.yahoo.vespa.http.client.config.Cluster;
import com.yahoo.vespa.http.client.config.ConnectionParams;
import com.yahoo.vespa.http.client.config.Endpoint;
import com.yahoo.vespa.http.client.config.FeedParams;
import com.yahoo.vespa.http.client.config.SessionParams;
import com.yahoo.vespa.http.client.handlers.V3MockParsingRequestHandler;
import org.junit.Test;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import static com.yahoo.vespa.http.client.TestUtils.writeDocument;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;

/**
 *
 * @author Einar M R Rosenvinge
 */
@SuppressWarnings("deprecation")
public class QueueBoundsTest {

    public static final List<TestDocument> documents;

    static {
        List<TestDocument> docs = new ArrayList<>();
        docs.add(new TestDocument("id:music:music::http://music.yahoo.com/bobdylan/BestOf",
                              ("<document documenttype=\"music\" documentid=\"id:music:music::http://music.yahoo.com/bobdylan/BestOf\">\n" +
                               "  <title>Best of Bob Dylan</title>\n" +
                               "</document>\n").getBytes(StandardCharsets.UTF_8)));
        docs.add(new TestDocument("id:music:music::http://music.yahoo.com/oleivars/BestOf",
                              ("<document documenttype=\"music\" documentid=\"id:music:music::http://music.yahoo.com/oleivars/BestOf\">\n" +
                               "  <title>Best of Ole Ivars</title>\n" +
                               "</document>\n").getBytes(StandardCharsets.UTF_8)));
        docs.add(new TestDocument("id:music:music::http://music.yahoo.com/bjarnefritjofs/BestOf",
                              ("<document documenttype=\"music\" documentid=\"id:music:music::http://music.yahoo.com/bjarnefritjofs/BestOf\">\n" +
                               "  <title>Best of Bjarne Fritjofs</title>\n" +
                               "</document>\n").getBytes(StandardCharsets.UTF_8)));
        docs.add(new TestDocument("id:music:music::http://music.yahoo.com/larryingvars/BestOf",
                              ("<document documenttype=\"music\" documentid=\"id:music:music::http://music.yahoo.com/larryingvars/BestOf\">\n" +
                               "  <title>Best of Larry Ingvars</title>\n" +
                               "</document>\n").getBytes(StandardCharsets.UTF_8)));
        documents = Collections.unmodifiableList(docs);
    }

    @Test
    public void requireThatFullInputQueueBlocksAndUnblocks() throws Exception {
        V3MockParsingRequestHandler mockXmlParsingRequestHandler = new V3MockParsingRequestHandler();
        mockXmlParsingRequestHandler.setScenario(V3MockParsingRequestHandler.Scenario.DONT_ACCEPT_VERSION);
        try (Server server = new Server(mockXmlParsingRequestHandler, 0);
             Session session =
                     new com.yahoo.vespa.http.client.core.api.SessionImpl(
                             new SessionParams.Builder()
                                     .addCluster(new Cluster.Builder()
                                                         .addEndpoint(Endpoint.create("localhost", server.getPort(), false))
                                                         .build())
                                     .setFeedParams(new FeedParams.Builder()
                                                            .setMaxChunkSizeBytes(1)
                                                            .setMaxInFlightRequests(1)
                                                            .setLocalQueueTimeOut(40000)
                                                            .build())
                                     .setConnectionParams(new ConnectionParams.Builder()
                                                                  .setNumPersistentConnectionsPerEndpoint(1)
                                                                  .build())
                                     .setClientQueueSize(2)
                                     .build(),
                             SessionFactory.createTimeoutExecutor(),
                             Clock.systemUTC())) {
            FeederThread feeder = new FeederThread(session);
            try {
                feeder.start();
                assertFeedNotBlocking(feeder, 0);
                assertThat(session.results().size(), is(0));
                assertFeedNotBlocking(feeder, 1);
                assertThat(session.results().size(), is(0));
                CountDownLatch lastPostFeed = assertFeedBlocking(feeder, 2);
                assertThat(session.results().size(), is(0));

                mockXmlParsingRequestHandler.setScenario(V3MockParsingRequestHandler.Scenario.ALL_OK);
                lastPostFeed.await(60, TimeUnit.SECONDS);
                assertThat(lastPostFeed.getCount(), equalTo(0L));
                assertResultQueueSize(session, 3, 60, TimeUnit.SECONDS);
            } finally {
                feeder.stop();
            }
        }
    }

    @Test
    public void requireThatFullIntermediateQueueBlocksAndUnblocks() throws Exception {
        V3MockParsingRequestHandler slowHandler =
                new V3MockParsingRequestHandler("B", HttpServletResponse.SC_OK,
                                                   V3MockParsingRequestHandler.Scenario.DELAYED_RESPONSE);

        try (Server serverA = new Server(new V3MockParsingRequestHandler("A"), 0);
             Server serverB = new Server(slowHandler, 0);
             com.yahoo.vespa.http.client.core.api.SessionImpl session = new com.yahoo.vespa.http.client.core.api.SessionImpl(
                     new SessionParams.Builder()
                             .addCluster(new Cluster.Builder()
                                                 .addEndpoint(Endpoint.create("localhost", serverA.getPort(), false))
                                                 .build())
                             .addCluster(new Cluster.Builder()
                                                 .addEndpoint(Endpoint.create("localhost", serverB.getPort(), false))
                                                 .build())
                             .setFeedParams(new FeedParams.Builder()
                                                    .setMaxChunkSizeBytes(1)
                                                    .build())
                             .setConnectionParams(new ConnectionParams.Builder()
                                                          .setNumPersistentConnectionsPerEndpoint(1)
                                                          .build())
                             .setClientQueueSize(6)  //3  per cluster
                             .build(), SessionFactory.createTimeoutExecutor(),
                     Clock.systemUTC())) {

            FeederThread feeder = new FeederThread(session);
            try {
                feeder.start();
                assertFeedNotBlocking(feeder, 0);
                assertFeedNotBlocking(feeder, 1);
                assertFeedNotBlocking(feeder, 2);

                //A input queue size now: 3
                //B input queue size now: 3
                //feeder thread not blocked
                //intermediate result queue size now: 3
                //result queue size now: 0
                assertResultQueueSize(session, 0, 60, TimeUnit.SECONDS);
                assertIncompleteResultQueueSize(session, 3, 60, TimeUnit.SECONDS);

                assertResultQueueSize(session, 0, 60, TimeUnit.SECONDS);
                assertIncompleteResultQueueSize(session, 3, 60, TimeUnit.SECONDS);

                //server B is slow, server A is fast


                //A input queue size now: 0
                //B input queue size now: 2, IOThread writing 1 and blocked because of no response yet
                //feeder thread still not blocked
                //intermediate result queue size now: 3
                //result queue size now: 0
                assertResultQueueSize(session, 0, 60, TimeUnit.SECONDS);
                assertIncompleteResultQueueSize(session, 3, 60, TimeUnit.SECONDS);

                CountDownLatch lastPostFeed = assertFeedBlocking(feeder, 3);

                //A input queue size now: 0
                //B input queue size now: 2, IOThread writing 1 and blocked because of no response yet
                //feeder thread blocking with 1 op
                //intermediate result queue size now: 3
                //result queue size now: 0

                slowHandler.poke();

                //A input queue size now: 0
                //B input queue size now: 2, IOThread writing 1 and blocked because of no response again
                //feeder thread unblocked
                //intermediate result queue size now: 3
                //result queue size now: 1

                lastPostFeed.await(60, TimeUnit.SECONDS);
                assertThat(lastPostFeed.getCount(), equalTo(0L));

                slowHandler.pokeAllAndUnblockFromNowOn();

                //A input queue size now: 0
                //B input queue size now: 0, IOThread not blocked
                //feeder thread unblocked
                //intermediate result queue size now: 0
                //result queue size now: 4

                assertResultQueueSize(session, 4, 60, TimeUnit.SECONDS);
            } finally {
                slowHandler.pokeAllAndUnblockFromNowOn();
                feeder.stop();
            }
        }
    }

    @Test
    public void testErrorRecovery() throws Exception {
        V3MockParsingRequestHandler mockXmlParsingRequestHandler = new V3MockParsingRequestHandler();
        mockXmlParsingRequestHandler.setScenario(V3MockParsingRequestHandler.Scenario.DONT_ACCEPT_VERSION);
        try (Server server = new Server(mockXmlParsingRequestHandler, 0);
             Session session =
                     new com.yahoo.vespa.http.client.core.api.SessionImpl(
                             new SessionParams.Builder()
                                     .addCluster(new Cluster.Builder()
                                             .addEndpoint(Endpoint.create("localhost", server.getPort(), false))
                                             .build())
                                     .setFeedParams(new FeedParams.Builder()
                                             .setMaxChunkSizeBytes(1)
                                             .setMaxInFlightRequests(1)
                                             .setLocalQueueTimeOut(3000)
                                             .build())
                                     .setConnectionParams(new ConnectionParams.Builder()
                                             .setNumPersistentConnectionsPerEndpoint(1)
                                             .setMaxRetries(1)
                                             .build())
                                     .setClientQueueSize(1)
                                     .build(),
                             SessionFactory.createTimeoutExecutor(),
                             Clock.systemUTC())) {
            FeederThread feeder = new FeederThread(session);
            feeder.start();
            try {
                {
                    System.out.println("We start with failed connection, post a document.");
                    assertFeedNotBlocking(feeder, 0);
                    assertEquals(0, session.results().size());

                    CountDownLatch lastPostFeed = assertFeedBlocking(feeder, 1);
                    System.out.println("No result so far.");
                    assertEquals(0, session.results().size());
                    System.out.println("Make connection ok.");
                    mockXmlParsingRequestHandler.setScenario(V3MockParsingRequestHandler.Scenario.ALL_OK);
                    assert(lastPostFeed.await(120, TimeUnit.SECONDS));
                    assertEquals(0L, lastPostFeed.getCount());
                    assertResultQueueSize(session, 2, 120, TimeUnit.SECONDS);
                }

                System.out.println("Take down connection");

                mockXmlParsingRequestHandler.setScenario(V3MockParsingRequestHandler.Scenario.DONT_ACCEPT_VERSION);
                {
                    assertFeedNotBlocking(feeder, 2);
                    System.out.println("Fed one document, fit in queue.");
                    assertEquals(2, session.results().size());
                    System.out.println("Fed one document more, wait for failure.");

                    assertFeedNotBlocking(feeder, 3);
                    System.out.println("Wait for results for all three documents.");
                    while (session.results().size() != 3) {
                        Thread.sleep(1);
                    }
                    System.out.println("Back to ok, test feeding again.");
                    mockXmlParsingRequestHandler.setScenario(V3MockParsingRequestHandler.Scenario.ALL_OK);
                    assertResultQueueSize(session, 4, 120, TimeUnit.SECONDS);
                }
                int errors = 0;
                for (Result result : session.results()) {
                    assertEquals(1, result.getDetails().size());
                    if (! result.isSuccess()) {
                        errors++;
                    }
                }
                assertEquals(1, errors);
            } finally {
                feeder.stop();
            }
        }
    }

    private void assertResultQueueSize(Session session, int size, long timeout, TimeUnit timeUnit) throws InterruptedException {
        long timeoutMs = TimeUnit.MILLISECONDS.convert(timeout, timeUnit);
        long waitTimeMs = 0;
        while (true) {
            if (session.results().size() == size) {
                break;
            }
            Thread.sleep(100);
            waitTimeMs += 100;
            if (waitTimeMs > timeoutMs) {
                fail("Queue never reached size " + size + " before timeout of " + timeout + " " + timeUnit + ". Size now: " + session.results().size());
            }
        }
    }

    private void assertIncompleteResultQueueSize(com.yahoo.vespa.http.client.core.api.SessionImpl session, int size, long timeout, TimeUnit timeUnit) throws InterruptedException {
        long timeoutMs = TimeUnit.MILLISECONDS.convert(timeout, timeUnit);
        long waitTimeMs = 0;
        while (true) {
            if (session.getIncompleteResultQueueSize() == size) {
                break;
            }
            Thread.sleep(100);
            waitTimeMs += 100;
            if (waitTimeMs > timeoutMs) {
                fail("Queue of incomplete results never reached size " + size + " before timeout of " + timeout + " " + timeUnit + ". Size now: " + session.getIncompleteResultQueueSize());
            }
        }
    }

    private CountDownLatch assertFeedBlocking(FeederThread feeder, int idx) throws InterruptedException {
        CountDownLatch preFeed = new CountDownLatch(1);
        CountDownLatch postFeed = new CountDownLatch(1);
        feeder.documents.add(new Triplet<>(preFeed, documents.get(idx), postFeed));
        preFeed.await(60, TimeUnit.SECONDS);
        assertThat(preFeed.getCount(), equalTo(0L));
        postFeed.await(2, TimeUnit.SECONDS);
        assertThat(feeder.getState(), not(equalTo(Thread.State.RUNNABLE)));
        assertThat(postFeed.getCount(), equalTo(1L));
        return postFeed;
    }

    private void assertFeedNotBlocking(FeederThread feeder, int idx) throws InterruptedException {
        CountDownLatch preFeed = new CountDownLatch(1);
        CountDownLatch postFeed = new CountDownLatch(1);
        feeder.documents.add(new Triplet<>(preFeed, documents.get(idx), postFeed));
        preFeed.await(60, TimeUnit.SECONDS);
        assertThat(preFeed.getCount(), equalTo(0L));
        postFeed.await(60, TimeUnit.SECONDS);
        assertThat(postFeed.getCount(), equalTo(0L));
    }

    public static class Triplet<F, S, T> {
        public final F first;
        public final S second;
        public final T third;

        public Triplet(final F first, final S second, final T third) {
            this.first = first;
            this.second = second;
            this.third = third;
        }
    }

    private class FeederThread implements Runnable {
        private final Session session;
        private final BlockingQueue<Triplet<CountDownLatch, TestDocument, CountDownLatch>> documents = new LinkedBlockingQueue<>();
        private final Thread thread;
        private volatile boolean shouldRun = true;

        FeederThread(Session session) {
            this.session = session;
            this.thread = new Thread(this);
        }

        public void start() {
            this.thread.start();
        }

        public void stop() {
            shouldRun = false;
            thread.interrupt();
        }

        public Thread.State getState() {
            return thread.getState();
        }

        @Override
        public void run() {
            try {
                while (shouldRun) {
                    Triplet<CountDownLatch, TestDocument, CountDownLatch> triplet = documents.poll(200, TimeUnit.MILLISECONDS);
                    if (triplet == null) {
                        continue;
                    }
                    triplet.first.countDown();
                    writeDocument(session, triplet.second);
                    triplet.third.countDown();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            } catch (InterruptedException e) {
                //ignore
            } catch (RuntimeException re) {
                if (re.getCause() == null || (!(re.getCause() instanceof InterruptedException))) {
                    re.printStackTrace();
                }
            }

        }

    }
}