-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathHttpTarget.java
More file actions
257 lines (239 loc) · 10.1 KB
/
HttpTarget.java
File metadata and controls
257 lines (239 loc) · 10.1 KB
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
package target;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import configuration.Config;
import configuration.TopicsRoutes;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import kafka.Producer;
import monitoring.Monitor;
import okhttp3.*;
import org.json.JSONObject;
import reactor.kafka.receiver.ReceiverRecord;
public class HttpTarget implements ITarget {
private final TopicsRoutes topicsRoutes;
private static final Duration httpTimeout = Duration.ofMillis(Config.TARGET_TIMEOUT_MS);
private static final OkHttpClient client = new OkHttpClient.Builder()
.callTimeout(httpTimeout)
.readTimeout(httpTimeout)
.writeTimeout(httpTimeout)
.connectTimeout(httpTimeout)
.connectionPool(
new ConnectionPool(
Config.CONNECTION_POOL_MAX_IDLE_CONNECTIONS,
Config.CONNECTION_POOL_KEEP_ALIVE_DURATION_MS,
TimeUnit.MILLISECONDS
)
)
.build();
private final Producer producer;
public HttpTarget(TopicsRoutes topicsRoutes, Producer producer) {
this.topicsRoutes = topicsRoutes;
this.producer = producer;
}
public CompletableFuture<Object> call(
final ReceiverRecord<String, String> record,
String batchRequestId,
String targetRequestId
) {
Monitor.processMessageStarted(record, batchRequestId, targetRequestId);
try {
return TargetRetryPolicy
.create(batchRequestId, targetRequestId)
.compose(client.newCall(createRequest(record)))
.executeAsync()
.handleAsync((response, throwable) ->
onExecutionSuccess(
response,
throwable,
record,
(new Date()).getTime(),
batchRequestId,
targetRequestId
)
);
} catch (Throwable throwable) {
Monitor.processMessageError(record, throwable, batchRequestId, targetRequestId);
if (Config.DEAD_LETTER_TOPIC != null) {
Monitor.deadLetterProduced(record, batchRequestId, targetRequestId);
return producer.produce(
Config.DEAD_LETTER_TOPIC,
record,
Optional.empty(),
Optional.of(throwable),
batchRequestId,
targetRequestId
);
}
return CompletableFuture.failedFuture(throwable);
}
}
@Override
public CompletableFuture<Object> call(
List<ReceiverRecord<String, String>> records,
String batchRequestId,
String targetRequestId
) {
Monitor.targetCallStarted(records, targetRequestId, batchRequestId);
var executionStart = new Date().getTime();
var gson = new Gson();
var body = !Config.RECORD_PICK_FIELD.isEmpty()
? gson.toJson(
(
records
.stream()
.map(r -> gson.fromJson(r.value(), JsonElement.class).getAsJsonObject())
.map(x -> x.get(Config.RECORD_PICK_FIELD))
.collect(Collectors.toList())
)
)
: records.stream().map(ReceiverRecord::value).toList().toString();
try {
var last = records.get(records.size() - 1);
var request = new Request.Builder()
.url(Config.TARGET_BASE_URL + this.topicsRoutes.getRoute(last.topic()))
.post(RequestBody.create(body, MediaType.get("application/json; charset=utf-8")))
.build();
return TargetRetryPolicy
.create(batchRequestId, targetRequestId)
.compose(client.newCall(request))
.executeAsync()
.handleAsync((response, throwable) -> {
int statusCode = response != null ? response.code() : -1;
try {
if (
Integer
.toString(statusCode)
.matches(Config.PRODUCE_TO_DEAD_LETTER_TOPIC_WHEN_STATUS_CODE_MATCH) ||
throwable != null
) {
String bodyString = "";
if (response != null && response.body() != null) {
bodyString = response.body().string();
}
return new TargetException(statusCode, bodyString, throwable);
} else {
return null;
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
Monitor.targetCallCompleted(
records,
targetRequestId,
batchRequestId,
executionStart,
statusCode,
throwable
);
}
});
} catch (Throwable throwable) {
Monitor.targetCallCompleted(records, targetRequestId, batchRequestId, executionStart, -1, throwable);
return CompletableFuture.failedFuture(throwable);
}
}
private Request createRequest(final ReceiverRecord<String, String> record) {
var gson = new Gson();
var body = !Config.RECORD_PICK_FIELD.isEmpty()
? gson.toJson(
(gson.fromJson(record.value(), JsonElement.class).getAsJsonObject().get(Config.RECORD_PICK_FIELD))
)
: record.value();
var requestBuilder = new Request.Builder()
.url(Config.TARGET_BASE_URL + this.topicsRoutes.getRoute(record.topic()))
.post(RequestBody.create(body, MediaType.get("application/json; charset=utf-8")))
.header("x-record-topic", record.topic())
.header("x-record-partition", String.valueOf(record.partition()))
.header("x-record-offset", String.valueOf(record.offset()))
.header("x-record-timestamp", String.valueOf(record.timestamp()))
.header("x-record-original-topic", this.getOriginalTopic(record));
if (Config.BODY_HEADERS_PATHS != null) {
var jsonObject = new JSONObject(record.value());
Config.BODY_HEADERS_PATHS.forEach(key -> {
if (jsonObject.has(key)) {
JSONObject headersObject = jsonObject.getJSONObject(key);
for (String headerKey : headersObject.keySet()) {
if (!headersObject.isNull(headerKey)) {
String value = headersObject.getString(headerKey);
requestBuilder.header(headerKey, value);
}
}
}
});
}
record
.headers()
.forEach(header -> {
String headerKey = header.key();
requestBuilder.header(headerKey, new String(header.value(), StandardCharsets.UTF_8));
});
return requestBuilder.build();
}
private CompletableFuture<Object> onExecutionSuccess(
Response response,
Throwable throwable,
ReceiverRecord<String, String> record,
long executionStart,
String batchRequestId,
String targetRequestId
) {
if (response == null) {
Monitor.processMessageCompleted(record, batchRequestId, targetRequestId, executionStart, -1, throwable);
if (Config.DEAD_LETTER_TOPIC != null) {
Monitor.deadLetterProduced(record, batchRequestId, targetRequestId);
return producer.produce(
Config.DEAD_LETTER_TOPIC,
record,
Optional.empty(),
Optional.of(throwable != null ? throwable : new RuntimeException("response is null")),
batchRequestId,
targetRequestId
);
}
return CompletableFuture.failedFuture(
throwable != null ? throwable : new RuntimeException("response is null")
);
}
try (Response r = response) {
if (throwable != null) {
Monitor.processMessageCompleted(record, batchRequestId, targetRequestId, executionStart, -1, throwable);
if (Config.DEAD_LETTER_TOPIC != null) {
Monitor.deadLetterProduced(record, batchRequestId, targetRequestId);
return producer.produce(
Config.DEAD_LETTER_TOPIC,
record,
Optional.empty(),
Optional.of(throwable),
batchRequestId,
targetRequestId
);
}
return CompletableFuture.failedFuture(throwable);
}
Monitor.processMessageCompleted(record, batchRequestId, targetRequestId, executionStart, r.code(), null);
if (
Integer.toString(r.code()).matches(Config.PRODUCE_TO_DEAD_LETTER_TOPIC_WHEN_STATUS_CODE_MATCH) &&
Config.DEAD_LETTER_TOPIC != null
) {
Monitor.deadLetterProduced(record, batchRequestId, targetRequestId);
return producer.produce(
Config.DEAD_LETTER_TOPIC,
record,
Optional.of(r),
Optional.empty(),
batchRequestId,
targetRequestId
);
}
return CompletableFuture.completedFuture(null);
}
}
}