aboutsummaryrefslogtreecommitdiffstats
path: root/vespa-feed-client/src/test/java/ai/vespa/feed/client/impl/HttpFeedClientTest.java
blob: c79bb7b46061d105e33492d6432ed2e233d72147 (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
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.feed.client.impl;

import ai.vespa.feed.client.DocumentId;
import ai.vespa.feed.client.FeedClient;
import ai.vespa.feed.client.FeedException;
import ai.vespa.feed.client.HttpResponse;
import ai.vespa.feed.client.OperationParameters;
import ai.vespa.feed.client.OperationStats;
import ai.vespa.feed.client.Result;
import ai.vespa.feed.client.ResultException;
import org.junit.jupiter.api.Test;

import java.net.URI;
import java.time.Duration;
import java.util.Collections;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 * @author jonmv
 */
class HttpFeedClientTest {

    @Test
    void testFeeding() throws ExecutionException, InterruptedException {
        DocumentId id = DocumentId.of("ns", "type", "0");
        AtomicReference<BiFunction<DocumentId, HttpRequest, CompletableFuture<HttpResponse>>> dispatch = new AtomicReference<>();
        class MockRequestStrategy implements RequestStrategy {
            @Override public OperationStats stats() { throw new UnsupportedOperationException(); }
            @Override public FeedClient.CircuitBreaker.State circuitBreakerState() { return FeedClient.CircuitBreaker.State.CLOSED; }
            @Override public void destroy() { throw new UnsupportedOperationException(); }
            @Override public void await() { throw new UnsupportedOperationException(); }
            @Override public CompletableFuture<HttpResponse> enqueue(DocumentId documentId, HttpRequest request) { return dispatch.get().apply(documentId, request); }
        }
        FeedClient client = new HttpFeedClient(new FeedClientBuilderImpl(Collections.singletonList(URI.create("https://dummy:123"))).setDryrun(true),
                                               new DryrunCluster(),
                                               new MockRequestStrategy());

        // Update is a PUT, and 200 OK is a success.
        dispatch.set((documentId, request) -> {
            try {
                assertEquals(id, documentId);
                assertEquals("/document/v1/ns/type/docid/0",
                             request.path());
                assertEquals("PUT", request.method());
                assertEquals("json", new String(request.body(), UTF_8));

                HttpResponse response = HttpResponse.of(200,
                                                        ("""
                                                         {
                                                           "pathId": "/document/v1/ns/type/docid/0",
                                                           "id": "id:ns:type::0"
                                                         }""").getBytes(UTF_8));
                return CompletableFuture.completedFuture(response);
            }
            catch (Throwable thrown) {
                CompletableFuture<HttpResponse> failed = new CompletableFuture<>();
                failed.completeExceptionally(thrown);
                return failed;
            }
        });
        Result result = client.update(id,
                                      "json",
                                      OperationParameters.empty())
                              .get();
        assertEquals(Result.Type.success, result.type());
        assertEquals(id, result.documentId());
        assertEquals(Optional.empty(), result.resultMessage());
        assertEquals(Optional.empty(), result.traceMessage());

        // Remove is a DELETE, and 412 OK is a conditionNotMet.
        dispatch.set((documentId, request) -> {
            try {
                assertEquals(id, documentId);
                assertEquals("/document/v1/ns/type/docid/0?tracelevel=1",
                             request.path());
                assertEquals("DELETE", request.method());
                assertNull(request.body());

                HttpResponse response = HttpResponse.of(412,
                                                        ("""
                                                         {
                                                           "pathId": "/document/v1/ns/type/docid/0",
                                                           "id": "id:ns:type::0",
                                                           "message": "Relax, take it easy.",
                                                           "trace": [
                                                             {
                                                               "message": "For there is nothing that we can do."
                                                             },
                                                             {
                                                               "fork": [
                                                                 {
                                                                   "message": "Relax, take is easy."
                                                                 },
                                                                 {
                                                                   "message": "Blame it on me or blame it on you."
                                                                 }
                                                               ]
                                                             }
                                                           ]
                                                         }""").getBytes(UTF_8));
                return CompletableFuture.completedFuture(response);
            }
            catch (Throwable thrown) {
                CompletableFuture<HttpResponse> failed = new CompletableFuture<>();
                failed.completeExceptionally(thrown);
                return failed;
            }
        });
        result = client.remove(id,
                               OperationParameters.empty().tracelevel(1))
                       .get();
        assertEquals(Result.Type.conditionNotMet, result.type());
        assertEquals(id, result.documentId());
        assertEquals(Optional.of("Relax, take it easy."), result.resultMessage());
        assertEquals(Optional.of("""
                                 [
                                     {
                                       "message": "For there is nothing that we can do."
                                     },
                                     {
                                       "fork": [
                                         {
                                           "message": "Relax, take is easy."
                                         },
                                         {
                                           "message": "Blame it on me or blame it on you."
                                         }
                                       ]
                                     }
                                   ]"""), result.traceMessage());

        // Put is a POST, and a Vespa error is a ResultException.
        dispatch.set((documentId, request) -> {
            try {
                assertEquals(id, documentId);
                assertEquals("/document/v1/ns/type/docid/0?create=true&condition=false&timeout=5000ms&route=route",
                             request.path());
                assertEquals("json", new String(request.body(), UTF_8));

                HttpResponse response = HttpResponse.of(502,
                                                        ("""
                                                         {
                                                           "pathId": "/document/v1/ns/type/docid/0",
                                                           "id": "id:ns:type::0",
                                                           "message": "Ooops! ... I did it again.",
                                                           "trace": [ { "message": "I played with your heart. Got lost in the game." } ]
                                                         }""").getBytes(UTF_8));
                return CompletableFuture.completedFuture(response);
            }
            catch (Throwable thrown) {
                CompletableFuture<HttpResponse> failed = new CompletableFuture<>();
                failed.completeExceptionally(thrown);
                return failed;
            }
        });
        ExecutionException expected = assertThrows(ExecutionException.class,
                                                   () ->  client.put(id,
                                                                     "json",
                                                                     OperationParameters.empty()
                                                                                        .createIfNonExistent(true)
                                                                                        .testAndSetCondition("false")
                                                                                        .route("route")
                                                                                        .timeout(Duration.ofSeconds(5)))
                                                                .get());
        assertTrue(expected.getCause() instanceof ResultException);
        assertEquals("Ooops! ... I did it again.", expected.getCause().getMessage());
        assertEquals("[ { \"message\": \"I played with your heart. Got lost in the game.\" } ]", ((ResultException) expected.getCause()).getTrace().get());


        // Handler error is a FeedException.
        dispatch.set((documentId, request) -> {
            try {
                assertEquals(id, documentId);
                assertEquals("/document/v1/ns/type/docid/0",
                             request.path());
                assertEquals("json", new String(request.body(), UTF_8));

                HttpResponse response = HttpResponse.of(500,
                                                        ("""
                                                         {
                                                           "pathId": "/document/v1/ns/type/docid/0",
                                                           "id": "id:ns:type::0",
                                                           "message": "Alla ska i jorden.",
                                                           "trace": [ { "message": "Din tid den kom, och senn så for den." } ]
                                                         }""").getBytes(UTF_8));
                return CompletableFuture.completedFuture(response);
            }
            catch (Throwable thrown) {
                CompletableFuture<HttpResponse> failed = new CompletableFuture<>();
                failed.completeExceptionally(thrown);
                return failed;
            }
        });
        expected = assertThrows(ExecutionException.class,
                                () -> client.put(id,
                                                 "json",
                                                 OperationParameters.empty())
                                            .get());
        assertEquals("Status 500 executing 'POST /document/v1/ns/type/docid/0': Alla ska i jorden.", expected.getCause().getMessage());
    }

    @Test
    void testHandshake() {
        // dummy:123 does not exist, and results in a host-not-found exception.
        FeedException exception = assertThrows(FeedException.class,
                                                   () -> new HttpFeedClient(new FeedClientBuilderImpl(Collections.singletonList(URI.create("https://dummy:123")))));
        String message = exception.getMessage();
        assertTrue(message.startsWith("failed handshake with server after "), message);
        assertTrue(message.contains("java.net.UnknownHostException"), message);

        HttpResponse oldResponse = HttpResponse.of(400, "{\"pathId\":\"/document/v1/test/build/docid/foo\",\"message\":\"Could not read document, no document?\"}".getBytes(UTF_8));
        HttpResponse okResponse = HttpResponse.of(200, null);
        AtomicReference<HttpResponse> response = new AtomicReference<>(oldResponse);
        Cluster cluster = (request, vessel) -> {
            try {
                assertNull(request.body());
                assertEquals("POST", request.method());
                assertEquals("/document/v1/feeder/handshake/docid/dummy?dryRun=true", request.path());
                vessel.complete(response.get());
            }
            catch (Throwable t) {
                vessel.completeExceptionally(t);
            }
        };

        // Old server, and speed-test.
        assertEquals("server does not support speed test; upgrade to a newer version",
                     assertThrows(FeedException.class,
                                  () -> new HttpFeedClient(new FeedClientBuilderImpl(Collections.singletonList(URI.create("https://dummy:123"))).setSpeedTest(true),
                                                           cluster,
                                                           null))
                             .getMessage());

        // Old server.
        new HttpFeedClient(new FeedClientBuilderImpl(Collections.singletonList(URI.create("https://dummy:123"))),
                           cluster,
                           null);

        // New server.
        response.set(okResponse);
        new HttpFeedClient(new FeedClientBuilderImpl(Collections.singletonList(URI.create("https://dummy:123"))),
                           cluster,
                           null);
    }

}