aboutsummaryrefslogtreecommitdiffstats
path: root/vespa-http-client/src/test/java/com/yahoo/vespa/http/client/core/communication/IOThreadTest.java
blob: b313daa12cda47a706c42e5146d7bca38bf438f8 (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
// 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.core.communication;

import com.yahoo.vespa.http.client.FeedConnectException;
import com.yahoo.vespa.http.client.FeedEndpointException;
import com.yahoo.vespa.http.client.FeedProtocolException;
import com.yahoo.vespa.http.client.Result;
import com.yahoo.vespa.http.client.V3HttpAPITest;
import com.yahoo.vespa.http.client.config.Endpoint;
import com.yahoo.vespa.http.client.core.Document;
import com.yahoo.vespa.http.client.core.EndpointResult;
import com.yahoo.vespa.http.client.core.ServerResponseException;
import org.junit.Test;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class IOThreadTest {

    private static final Endpoint ENDPOINT = Endpoint.create("myhost");

    final EndpointResultQueue endpointResultQueue = mock(EndpointResultQueue.class);
    final ApacheGatewayConnection apacheGatewayConnection = mock(ApacheGatewayConnection.class);
    final String exceptionMessage = "SOME EXCEPTION FOO";
    CountDownLatch latch = new CountDownLatch(1);
    String docId1 = V3HttpAPITest.documents.get(0).getDocumentId();
    Document doc1 = new Document(V3HttpAPITest.documents.get(0).getDocumentId(),
            V3HttpAPITest.documents.get(0).getContents(), null /* context */);
    String docId2 = V3HttpAPITest.documents.get(1).getDocumentId();
    Document doc2 = new Document(V3HttpAPITest.documents.get(1).getDocumentId(),
            V3HttpAPITest.documents.get(1).getContents(), null /* context */);
    DocumentQueue documentQueue = new DocumentQueue(4);

    public IOThreadTest() {
        when(apacheGatewayConnection.getEndpoint()).thenReturn(ENDPOINT);
    }

    /**
     * Set up mock so that it can handle both failDocument() and resultReceived().
     * @param expectedDocIdFail on failure, this has to be the doc id, or the mock will fail.
     * @param expectedDocIdOk on ok, this has to be the doc id, or the mock will fail.
     * @param isTransient checked on failure, if different, the mock will fail.
     * @param expectedException checked on failure, if exception toString is different, the mock will fail.
     */
    void setupEndpointResultQueueMock(String expectedDocIdFail, String expectedDocIdOk, boolean isTransient, String expectedException) {
        doAnswer(invocation -> {
            EndpointResult endpointResult = (EndpointResult) invocation.getArguments()[0];
            assertThat(endpointResult.getOperationId(), is(expectedDocIdFail));
            assertThat(endpointResult.getDetail().getException().toString(), containsString(expectedException));
            assertThat(endpointResult.getDetail().getResultType(), is(isTransient ? Result.ResultType.TRANSITIVE_ERROR : Result.ResultType.FATAL_ERROR));

            latch.countDown();
            return null;
        }).when(endpointResultQueue).failOperation(any(), eq(0));

        doAnswer(invocation -> {
            EndpointResult endpointResult = (EndpointResult) invocation.getArguments()[0];
            assertThat(endpointResult.getOperationId(), is(expectedDocIdOk));
            assertThat(endpointResult.getDetail().getResultType(), is(Result.ResultType.OPERATION_EXECUTED));
            latch.countDown();
            return null;
        }).when(endpointResultQueue).resultReceived(any(), eq(0));
    }

    private IOThread createIOThread(int maxInFlightRequests, long localQueueTimeOut) {
        return new IOThread(null,
                            ENDPOINT,
                            endpointResultQueue,
                            new SingletonGatewayConnectionFactory(apacheGatewayConnection),
                            0,
                            0,
                            maxInFlightRequests,
                            localQueueTimeOut,
                            documentQueue,
                            0,
                            10);
    }

    @Test
    public void singleDocumentSuccess() throws Exception {
        when(apacheGatewayConnection.connect()).thenReturn(true);
        InputStream serverResponse = new ByteArrayInputStream(
                (docId1 + " OK Doc{20}fed").getBytes(StandardCharsets.UTF_8));
        when(apacheGatewayConnection.writeOperations(any())).thenReturn(serverResponse);
        setupEndpointResultQueueMock( "nope", docId1, true, exceptionMessage);
        try (IOThread ioThread = createIOThread(10000, 10000)) {
            ioThread.post(doc1);
            assert (latch.await(120, TimeUnit.SECONDS));
        }
    }

    @Test
    public void requireThatSingleDocumentWriteErrorIsHandledProperly() throws Exception {
        when(apacheGatewayConnection.connect()).thenReturn(true);
        when(apacheGatewayConnection.writeOperations(any())).thenThrow(new IOException(exceptionMessage));
        setupEndpointResultQueueMock(doc1.getOperationId(), "nope", true, exceptionMessage);
        try (IOThread ioThread = createIOThread(10000, 10000)) {
            ioThread.post(doc1);
            assert (latch.await(120, TimeUnit.SECONDS));
        }
    }

    @Test
    public void requireThatTwoDocumentsFirstWriteErrorSecondOkIsHandledProperly() throws Exception {
        when(apacheGatewayConnection.connect()).thenReturn(true);
        InputStream serverResponse = new ByteArrayInputStream(
                (docId2 + " OK Doc{20}fed").getBytes(StandardCharsets.UTF_8));
        when(apacheGatewayConnection.writeOperations(any()))
                .thenThrow(new IOException(exceptionMessage))
                .thenReturn(serverResponse);
        latch = new CountDownLatch(2);
        setupEndpointResultQueueMock(doc1.getOperationId(), doc2.getDocumentId(), true, exceptionMessage);

        try (IOThread ioThread = createIOThread(10000, 10000)) {
            ioThread.post(doc1);
            ioThread.post(doc2);
            assert (latch.await(120, TimeUnit.SECONDS));
        }
    }

    @Test
    public void testQueueTimeOutNoNoConnectionToServer() throws Exception {
        when(apacheGatewayConnection.connect()).thenReturn(false);
        InputStream serverResponse = new ByteArrayInputStream(
                ("").getBytes(StandardCharsets.UTF_8));
        when(apacheGatewayConnection.writeOperations(any()))
                .thenReturn(serverResponse);
        setupEndpointResultQueueMock(doc1.getOperationId(), "nope", true,
                "java.lang.Exception: Not sending document operation, timed out in queue after");
        try (IOThread ioThread = createIOThread(10, 10)) {
            ioThread.post(doc1);
            assert (latch.await(120, TimeUnit.SECONDS));
        }
    }

    @Test
    public void requireThatEndpointProtocolExceptionsArePropagated()
            throws IOException, ServerResponseException, InterruptedException, TimeoutException, ExecutionException {
        when(apacheGatewayConnection.connect()).thenReturn(true);
        int errorCode = 403;
        String errorMessage = "Not authorized";
        doThrow(new ServerResponseException(errorCode, errorMessage)).when(apacheGatewayConnection).handshake();
        Future<FeedEndpointException> futureException = endpointErrorCapturer(endpointResultQueue);

        try (IOThread ioThread = createIOThread(10, 10)) {
            ioThread.post(doc1);
            FeedEndpointException reportedException = futureException.get(120, TimeUnit.SECONDS);
            assertThat(reportedException, instanceOf(FeedProtocolException.class));
            FeedProtocolException actualException = (FeedProtocolException) reportedException;
            assertThat(actualException.getHttpStatusCode(), equalTo(errorCode));
            assertThat(actualException.getHttpResponseMessage(), equalTo(errorMessage));
            assertThat(actualException.getEndpoint(), equalTo(ENDPOINT));
            assertThat(actualException.getMessage(), equalTo("Endpoint 'myhost:4080' returned an error on handshake: 403 - Not authorized"));
        }
    }

    @Test
    public void requireThatEndpointConnectExceptionsArePropagated()
            throws IOException, ServerResponseException, InterruptedException, TimeoutException, ExecutionException {
        when(apacheGatewayConnection.connect()).thenReturn(true);
        String errorMessage = "generic error message";
        IOException cause = new IOException(errorMessage);
        doThrow(cause).when(apacheGatewayConnection).handshake();
        Future<FeedEndpointException> futureException = endpointErrorCapturer(endpointResultQueue);

        try (IOThread ioThread = createIOThread(10, 10)) {
            ioThread.post(doc1);
            FeedEndpointException reportedException = futureException.get(120, TimeUnit.SECONDS);
            assertThat(reportedException, instanceOf(FeedConnectException.class));
            FeedConnectException actualException = (FeedConnectException) reportedException;
            assertThat(actualException.getCause(), equalTo(cause));
            assertThat(actualException.getEndpoint(), equalTo(ENDPOINT));
            assertThat(actualException.getMessage(), equalTo("Handshake to endpoint 'myhost:4080' failed: generic error message"));
        }
    }

    private static Future<FeedEndpointException> endpointErrorCapturer(EndpointResultQueue endpointResultQueue) {
        CompletableFuture<FeedEndpointException> futureResult = new CompletableFuture<>();
        doAnswer(invocation -> {
            if (futureResult.isDone()) return null;
            FeedEndpointException reportedException = (FeedEndpointException) invocation.getArguments()[0];
            futureResult.complete(reportedException);
            return null;
        }).when(endpointResultQueue).onEndpointError(any());
        return futureResult;
    }

    private static final class SingletonGatewayConnectionFactory implements GatewayConnectionFactory {

        private final GatewayConnection singletonConnection;

        SingletonGatewayConnectionFactory(GatewayConnection singletonConnection) {
            this.singletonConnection = singletonConnection;
        }

        @Override
        public GatewayConnection newConnection() { return singletonConnection; }

    }

}