-
-
Notifications
You must be signed in to change notification settings - Fork 467
Expand file tree
/
Copy pathAsyncHttpTransport.java
More file actions
371 lines (336 loc) · 13.3 KB
/
AsyncHttpTransport.java
File metadata and controls
371 lines (336 loc) · 13.3 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
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
package io.sentry.transport;
import io.sentry.DateUtils;
import io.sentry.Hint;
import io.sentry.ILogger;
import io.sentry.RequestDetails;
import io.sentry.SentryDate;
import io.sentry.SentryDateProvider;
import io.sentry.SentryEnvelope;
import io.sentry.SentryLevel;
import io.sentry.SentryOptions;
import io.sentry.UncaughtExceptionHandlerIntegration;
import io.sentry.cache.IEnvelopeCache;
import io.sentry.clientreport.DiscardReason;
import io.sentry.hints.Cached;
import io.sentry.hints.DiskFlushNotification;
import io.sentry.hints.Enqueable;
import io.sentry.hints.Retryable;
import io.sentry.hints.SubmissionResult;
import io.sentry.util.HintUtils;
import io.sentry.util.LogUtils;
import io.sentry.util.Objects;
import java.io.IOException;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* {@link ITransport} implementation that executes request asynchronously in a blocking manner using
* {@link java.net.HttpURLConnection}.
*/
public final class AsyncHttpTransport implements ITransport {
private final @NotNull QueuedThreadPoolExecutor executor;
private final @NotNull IEnvelopeCache envelopeCache;
private final @NotNull SentryOptions options;
private final @NotNull RateLimiter rateLimiter;
private final @NotNull ITransportGate transportGate;
private final @NotNull HttpConnection connection;
private volatile @Nullable Runnable currentRunnable = null;
public AsyncHttpTransport(
final @NotNull SentryOptions options,
final @NotNull RateLimiter rateLimiter,
final @NotNull ITransportGate transportGate,
final @NotNull RequestDetails requestDetails) {
this(
initExecutor(
options.getMaxQueueSize(),
options.getEnvelopeDiskCache(),
options.getLogger(),
options.getDateProvider()),
options,
rateLimiter,
transportGate,
new HttpConnection(options, requestDetails, rateLimiter));
}
public AsyncHttpTransport(
final @NotNull QueuedThreadPoolExecutor executor,
final @NotNull SentryOptions options,
final @NotNull RateLimiter rateLimiter,
final @NotNull ITransportGate transportGate,
final @NotNull HttpConnection httpConnection) {
this.executor = Objects.requireNonNull(executor, "executor is required");
this.envelopeCache =
Objects.requireNonNull(options.getEnvelopeDiskCache(), "envelopeCache is required");
this.options = Objects.requireNonNull(options, "options is required");
this.rateLimiter = Objects.requireNonNull(rateLimiter, "rateLimiter is required");
this.transportGate = Objects.requireNonNull(transportGate, "transportGate is required");
this.connection = Objects.requireNonNull(httpConnection, "httpConnection is required");
}
@Override
public void send(final @NotNull SentryEnvelope envelope, final @NotNull Hint hint)
throws IOException {
// For now no caching on envelopes
IEnvelopeCache currentEnvelopeCache = envelopeCache;
boolean cached = false;
if (HintUtils.hasType(hint, Cached.class)) {
currentEnvelopeCache = NoOpEnvelopeCache.getInstance();
cached = true;
options.getLogger().log(SentryLevel.DEBUG, "Captured Envelope is already cached");
}
final SentryEnvelope filteredEnvelope = rateLimiter.filter(envelope, hint);
if (filteredEnvelope == null) {
if (cached) {
envelopeCache.discard(envelope);
}
} else {
SentryEnvelope envelopeThatMayIncludeClientReport;
if (HintUtils.hasType(
hint, UncaughtExceptionHandlerIntegration.UncaughtExceptionHint.class)) {
envelopeThatMayIncludeClientReport =
options.getClientReportRecorder().attachReportToEnvelope(filteredEnvelope);
} else {
envelopeThatMayIncludeClientReport = filteredEnvelope;
}
final Future<?> future =
executor.submit(
new EnvelopeSender(envelopeThatMayIncludeClientReport, hint, currentEnvelopeCache));
if (future != null && future.isCancelled()) {
options
.getClientReportRecorder()
.recordLostEnvelope(DiscardReason.QUEUE_OVERFLOW, envelopeThatMayIncludeClientReport);
} else {
HintUtils.runIfHasType(
hint,
Enqueable.class,
enqueable -> {
enqueable.markEnqueued();
options.getLogger().log(SentryLevel.DEBUG, "Envelope enqueued");
});
}
}
}
@Override
public void flush(long timeoutMillis) {
executor.waitTillIdle(timeoutMillis);
}
private static QueuedThreadPoolExecutor initExecutor(
final int maxQueueSize,
final @NotNull IEnvelopeCache envelopeCache,
final @NotNull ILogger logger,
final @NotNull SentryDateProvider dateProvider) {
final RejectedExecutionHandler storeEvents =
(r, executor) -> {
if (r instanceof EnvelopeSender) {
final EnvelopeSender envelopeSender = (EnvelopeSender) r;
if (!HintUtils.hasType(envelopeSender.hint, Cached.class)) {
envelopeCache.storeEnvelope(envelopeSender.envelope, envelopeSender.hint);
}
markHintWhenSendingFailed(envelopeSender.hint, true);
logger.log(SentryLevel.WARNING, "Envelope rejected");
}
};
return new QueuedThreadPoolExecutor(
1, maxQueueSize, new AsyncConnectionThreadFactory(), storeEvents, logger, dateProvider);
}
@Override
public @NotNull RateLimiter getRateLimiter() {
return rateLimiter;
}
@Override
public boolean isHealthy() {
boolean anyRateLimitActive = rateLimiter.isAnyRateLimitActive();
boolean didRejectRecently = executor.didRejectRecently();
return !anyRateLimitActive && !didRejectRecently;
}
@Override
public void close() throws IOException {
close(false);
}
@Override
public void close(final boolean isRestarting) throws IOException {
rateLimiter.close();
executor.shutdown();
options.getLogger().log(SentryLevel.DEBUG, "Shutting down");
try {
// only stop sending events on a real shutdown, not on a restart
if (!isRestarting) {
// We need a small timeout to be able to save to disk any rejected envelope
long timeout = options.getFlushTimeoutMillis();
if (!executor.awaitTermination(timeout, TimeUnit.MILLISECONDS)) {
options
.getLogger()
.log(
SentryLevel.WARNING,
"Failed to shutdown the async connection async sender within "
+ timeout
+ " ms. Trying to force it now.");
executor.shutdownNow();
if (currentRunnable != null) {
// We store to disk any envelope that is currently being sent
executor.getRejectedExecutionHandler().rejectedExecution(currentRunnable, executor);
}
}
}
} catch (InterruptedException e) {
// ok, just give up then...
options
.getLogger()
.log(SentryLevel.DEBUG, "Thread interrupted while closing the connection.");
Thread.currentThread().interrupt();
}
}
/**
* It marks the hints when sending has failed, so it's not necessary to wait the timeout
*
* @param hint the Hints
* @param retry if event should be retried or not
*/
private static void markHintWhenSendingFailed(final @NotNull Hint hint, final boolean retry) {
HintUtils.runIfHasType(hint, SubmissionResult.class, result -> result.setResult(false));
HintUtils.runIfHasType(hint, Retryable.class, retryable -> retryable.setRetry(retry));
}
private static final class AsyncConnectionThreadFactory implements ThreadFactory {
private int cnt;
@Override
public @NotNull Thread newThread(final @NotNull Runnable r) {
final Thread ret = new Thread(r, "SentryAsyncConnection-" + cnt++);
ret.setDaemon(true);
return ret;
}
}
private final class EnvelopeSender implements Runnable {
private final @NotNull SentryEnvelope envelope;
private final @NotNull Hint hint;
private final @NotNull IEnvelopeCache envelopeCache;
private final TransportResult failedResult = TransportResult.error();
EnvelopeSender(
final @NotNull SentryEnvelope envelope,
final @NotNull Hint hint,
final @NotNull IEnvelopeCache envelopeCache) {
this.envelope = Objects.requireNonNull(envelope, "Envelope is required.");
this.hint = hint;
this.envelopeCache = Objects.requireNonNull(envelopeCache, "EnvelopeCache is required.");
}
@Override
public void run() {
currentRunnable = this;
TransportResult result = this.failedResult;
try {
result = flush();
options.getLogger().log(SentryLevel.DEBUG, "Envelope flushed");
} catch (Throwable e) {
options.getLogger().log(SentryLevel.ERROR, e, "Envelope submission failed");
throw e;
} finally {
final TransportResult finalResult = result;
HintUtils.runIfHasType(
hint,
SubmissionResult.class,
(submissionResult) -> {
options
.getLogger()
.log(
SentryLevel.DEBUG,
"Marking envelope submission result: %s",
finalResult.isSuccess());
submissionResult.setResult(finalResult.isSuccess());
});
currentRunnable = null;
}
}
private @NotNull TransportResult flush() {
TransportResult result = this.failedResult;
envelope.getHeader().setSentAt(null);
boolean cached = envelopeCache.storeEnvelope(envelope, hint);
HintUtils.runIfHasType(
hint,
DiskFlushNotification.class,
(diskFlushNotification) -> {
if (diskFlushNotification.isFlushable(envelope.getHeader().getEventId())) {
diskFlushNotification.markFlushed();
options.getLogger().log(SentryLevel.DEBUG, "Disk flush envelope fired");
} else {
options
.getLogger()
.log(
SentryLevel.DEBUG,
"Not firing envelope flush as there's an ongoing transaction");
}
});
if (transportGate.isConnected()) {
final SentryEnvelope envelopeWithClientReport =
options.getClientReportRecorder().attachReportToEnvelope(envelope);
try {
@NotNull SentryDate now = options.getDateProvider().now();
envelopeWithClientReport
.getHeader()
.setSentAt(DateUtils.nanosToDate(now.nanoTimestamp()));
result = connection.send(envelopeWithClientReport);
if (result.isSuccess()) {
envelopeCache.discard(envelope);
} else {
final String message;
if (result.getResponseCode() == 413) {
message =
"Envelope was discarded by the server because it was too large."
+ " Consider reducing the size of events, breadcrumbs, or attachments."
+ " You can use the `SentryOptions.onOversizedEvent` callback"
+ " to customize how oversized events are handled.";
} else {
message =
"The transport failed to send the envelope with response code "
+ result.getResponseCode();
}
options.getLogger().log(SentryLevel.ERROR, message);
if (result.getResponseCode() >= 400) {
envelopeCache.discard(envelope);
// ignore e.g. 429 as we're not the ones actively dropping
if (result.getResponseCode() != 429) {
options
.getClientReportRecorder()
.recordLostEnvelope(DiscardReason.SEND_ERROR, envelopeWithClientReport);
}
}
throw new IllegalStateException(message);
}
} catch (IOException e) {
// Failure due to IO is allowed to retry the event
HintUtils.runIfHasType(
hint,
Retryable.class,
(retryable) -> {
retryable.setRetry(true);
},
(hint, clazz) -> {
if (!cached) {
LogUtils.logNotInstanceOf(clazz, hint, options.getLogger());
options
.getClientReportRecorder()
.recordLostEnvelope(DiscardReason.NETWORK_ERROR, envelopeWithClientReport);
}
});
throw new IllegalStateException("Sending the event failed.", e);
}
} else {
// If transportGate is blocking from sending, allowed to retry
HintUtils.runIfHasType(
hint,
Retryable.class,
(retryable) -> {
retryable.setRetry(true);
},
(hint, clazz) -> {
if (!cached) {
LogUtils.logNotInstanceOf(clazz, hint, options.getLogger());
options
.getClientReportRecorder()
.recordLostEnvelope(DiscardReason.NETWORK_ERROR, envelope);
}
});
}
return result;
}
}
}