|
| 1 | +package io.sentry.android.core; |
| 2 | + |
| 3 | +import static io.sentry.cache.EnvelopeCache.PREFIX_CURRENT_SESSION_FILE; |
| 4 | +import static io.sentry.cache.EnvelopeCache.PREFIX_PREVIOUS_SESSION_FILE; |
| 5 | +import static io.sentry.cache.EnvelopeCache.STARTUP_CRASH_MARKER_FILE; |
| 6 | + |
| 7 | +import io.sentry.SentryEnvelope; |
| 8 | +import io.sentry.SentryEnvelopeItem; |
| 9 | +import io.sentry.SentryEvent; |
| 10 | +import io.sentry.SentryItemType; |
| 11 | +import io.sentry.SentryLevel; |
| 12 | +import java.io.BufferedInputStream; |
| 13 | +import java.io.BufferedReader; |
| 14 | +import java.io.ByteArrayInputStream; |
| 15 | +import java.io.File; |
| 16 | +import java.io.FileInputStream; |
| 17 | +import java.io.InputStream; |
| 18 | +import java.io.InputStreamReader; |
| 19 | +import java.io.Reader; |
| 20 | +import java.nio.charset.StandardCharsets; |
| 21 | +import java.util.ArrayList; |
| 22 | +import java.util.Date; |
| 23 | +import java.util.List; |
| 24 | +import org.jetbrains.annotations.ApiStatus; |
| 25 | +import org.jetbrains.annotations.NotNull; |
| 26 | +import org.jetbrains.annotations.Nullable; |
| 27 | + |
| 28 | +/** |
| 29 | + * Collects native crash events from the outbox directory. These events can be correlated with |
| 30 | + * tombstone events from ApplicationExitInfo to avoid sending duplicate crash reports. |
| 31 | + */ |
| 32 | +@ApiStatus.Internal |
| 33 | +public final class NativeEventCollector { |
| 34 | + |
| 35 | + private static final String NATIVE_PLATFORM = "native"; |
| 36 | + |
| 37 | + // TODO: will be replaced with the correlationId once the Native SDK supports it |
| 38 | + private static final long TIMESTAMP_TOLERANCE_MS = 5000; |
| 39 | + |
| 40 | + private final @NotNull SentryAndroidOptions options; |
| 41 | + private final @NotNull List<NativeEventData> nativeEvents = new ArrayList<>(); |
| 42 | + private boolean collected = false; |
| 43 | + |
| 44 | + public NativeEventCollector(final @NotNull SentryAndroidOptions options) { |
| 45 | + this.options = options; |
| 46 | + } |
| 47 | + |
| 48 | + /** Holds a native event along with its source file for later deletion. */ |
| 49 | + public static final class NativeEventData { |
| 50 | + private final @NotNull SentryEvent event; |
| 51 | + private final @NotNull File file; |
| 52 | + private final @NotNull SentryEnvelope envelope; |
| 53 | + private final long timestampMs; |
| 54 | + |
| 55 | + NativeEventData( |
| 56 | + final @NotNull SentryEvent event, |
| 57 | + final @NotNull File file, |
| 58 | + final @NotNull SentryEnvelope envelope, |
| 59 | + final long timestampMs) { |
| 60 | + this.event = event; |
| 61 | + this.file = file; |
| 62 | + this.envelope = envelope; |
| 63 | + this.timestampMs = timestampMs; |
| 64 | + } |
| 65 | + |
| 66 | + public @NotNull SentryEvent getEvent() { |
| 67 | + return event; |
| 68 | + } |
| 69 | + |
| 70 | + public @NotNull File getFile() { |
| 71 | + return file; |
| 72 | + } |
| 73 | + |
| 74 | + public @NotNull SentryEnvelope getEnvelope() { |
| 75 | + return envelope; |
| 76 | + } |
| 77 | + |
| 78 | + public long getTimestampMs() { |
| 79 | + return timestampMs; |
| 80 | + } |
| 81 | + |
| 82 | + /** |
| 83 | + * Extracts the correlation ID from the event's extra data. |
| 84 | + * |
| 85 | + * @return the correlation ID, or null if not present |
| 86 | + */ |
| 87 | + public @Nullable String getCorrelationId() { |
| 88 | + final @Nullable Object correlationId = event.getExtra("sentry.native.correlation_id"); |
| 89 | + if (correlationId instanceof String) { |
| 90 | + return (String) correlationId; |
| 91 | + } |
| 92 | + return null; |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + /** |
| 97 | + * Scans the outbox directory and collects all native crash events. This method should be called |
| 98 | + * once before processing tombstones. Subsequent calls are no-ops. |
| 99 | + */ |
| 100 | + public void collect() { |
| 101 | + if (collected) { |
| 102 | + return; |
| 103 | + } |
| 104 | + collected = true; |
| 105 | + |
| 106 | + final @Nullable String outboxPath = options.getOutboxPath(); |
| 107 | + if (outboxPath == null) { |
| 108 | + options |
| 109 | + .getLogger() |
| 110 | + .log(SentryLevel.DEBUG, "Outbox path is null, skipping native event collection."); |
| 111 | + return; |
| 112 | + } |
| 113 | + |
| 114 | + final File outboxDir = new File(outboxPath); |
| 115 | + if (!outboxDir.isDirectory()) { |
| 116 | + options.getLogger().log(SentryLevel.DEBUG, "Outbox path is not a directory: %s", outboxPath); |
| 117 | + return; |
| 118 | + } |
| 119 | + |
| 120 | + final File[] files = outboxDir.listFiles((d, name) -> isRelevantFileName(name)); |
| 121 | + if (files == null || files.length == 0) { |
| 122 | + options.getLogger().log(SentryLevel.DEBUG, "No envelope files found in outbox."); |
| 123 | + return; |
| 124 | + } |
| 125 | + |
| 126 | + options |
| 127 | + .getLogger() |
| 128 | + .log(SentryLevel.DEBUG, "Scanning %d files in outbox for native events.", files.length); |
| 129 | + |
| 130 | + for (final File file : files) { |
| 131 | + if (!file.isFile()) { |
| 132 | + continue; |
| 133 | + } |
| 134 | + |
| 135 | + final @Nullable NativeEventData nativeEventData = extractNativeEventFromFile(file); |
| 136 | + if (nativeEventData != null) { |
| 137 | + nativeEvents.add(nativeEventData); |
| 138 | + options |
| 139 | + .getLogger() |
| 140 | + .log( |
| 141 | + SentryLevel.DEBUG, |
| 142 | + "Found native event in outbox: %s (timestamp: %d)", |
| 143 | + file.getName(), |
| 144 | + nativeEventData.getTimestampMs()); |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + options |
| 149 | + .getLogger() |
| 150 | + .log(SentryLevel.DEBUG, "Collected %d native events from outbox.", nativeEvents.size()); |
| 151 | + } |
| 152 | + |
| 153 | + /** |
| 154 | + * Finds a native event that matches the given tombstone timestamp or correlation ID. If a match |
| 155 | + * is found, it is removed from the internal list so it won't be matched again. |
| 156 | + * |
| 157 | + * <p>This method will lazily collect native events from the outbox on first call. |
| 158 | + * |
| 159 | + * @param tombstoneTimestampMs the timestamp from ApplicationExitInfo |
| 160 | + * @param correlationId the correlation ID from processStateSummary, or null |
| 161 | + * @return the matching native event data, or null if no match found |
| 162 | + */ |
| 163 | + public @Nullable NativeEventData findAndRemoveMatchingNativeEvent( |
| 164 | + final long tombstoneTimestampMs, final @Nullable String correlationId) { |
| 165 | + |
| 166 | + // Lazily collect on first use (runs on executor thread, not main thread) |
| 167 | + collect(); |
| 168 | + |
| 169 | + // First, try to match by correlation ID (when sentry-native supports it) |
| 170 | + if (correlationId != null) { |
| 171 | + for (final NativeEventData nativeEvent : nativeEvents) { |
| 172 | + final @Nullable String nativeCorrelationId = nativeEvent.getCorrelationId(); |
| 173 | + if (correlationId.equals(nativeCorrelationId)) { |
| 174 | + options |
| 175 | + .getLogger() |
| 176 | + .log(SentryLevel.DEBUG, "Matched native event by correlation ID: %s", correlationId); |
| 177 | + nativeEvents.remove(nativeEvent); |
| 178 | + return nativeEvent; |
| 179 | + } |
| 180 | + } |
| 181 | + } |
| 182 | + |
| 183 | + // Fall back to timestamp-based matching |
| 184 | + for (final NativeEventData nativeEvent : nativeEvents) { |
| 185 | + final long timeDiff = Math.abs(tombstoneTimestampMs - nativeEvent.getTimestampMs()); |
| 186 | + if (timeDiff <= TIMESTAMP_TOLERANCE_MS) { |
| 187 | + options |
| 188 | + .getLogger() |
| 189 | + .log(SentryLevel.DEBUG, "Matched native event by timestamp (diff: %d ms)", timeDiff); |
| 190 | + nativeEvents.remove(nativeEvent); |
| 191 | + return nativeEvent; |
| 192 | + } |
| 193 | + } |
| 194 | + |
| 195 | + return null; |
| 196 | + } |
| 197 | + |
| 198 | + /** |
| 199 | + * Deletes a native event file from the outbox. |
| 200 | + * |
| 201 | + * @param nativeEventData the native event data containing the file reference |
| 202 | + * @return true if the file was deleted successfully |
| 203 | + */ |
| 204 | + public boolean deleteNativeEventFile(final @NotNull NativeEventData nativeEventData) { |
| 205 | + final File file = nativeEventData.getFile(); |
| 206 | + try { |
| 207 | + if (file.delete()) { |
| 208 | + options |
| 209 | + .getLogger() |
| 210 | + .log(SentryLevel.DEBUG, "Deleted native event file from outbox: %s", file.getName()); |
| 211 | + return true; |
| 212 | + } else { |
| 213 | + options |
| 214 | + .getLogger() |
| 215 | + .log( |
| 216 | + SentryLevel.WARNING, |
| 217 | + "Failed to delete native event file: %s", |
| 218 | + file.getAbsolutePath()); |
| 219 | + return false; |
| 220 | + } |
| 221 | + } catch (Throwable e) { |
| 222 | + options |
| 223 | + .getLogger() |
| 224 | + .log( |
| 225 | + SentryLevel.ERROR, e, "Error deleting native event file: %s", file.getAbsolutePath()); |
| 226 | + return false; |
| 227 | + } |
| 228 | + } |
| 229 | + |
| 230 | + private @Nullable NativeEventData extractNativeEventFromFile(final @NotNull File file) { |
| 231 | + try (final InputStream stream = new BufferedInputStream(new FileInputStream(file))) { |
| 232 | + final SentryEnvelope envelope = options.getEnvelopeReader().read(stream); |
| 233 | + if (envelope == null) { |
| 234 | + return null; |
| 235 | + } |
| 236 | + |
| 237 | + for (final SentryEnvelopeItem item : envelope.getItems()) { |
| 238 | + if (!SentryItemType.Event.equals(item.getHeader().getType())) { |
| 239 | + continue; |
| 240 | + } |
| 241 | + |
| 242 | + try (final Reader eventReader = |
| 243 | + new BufferedReader( |
| 244 | + new InputStreamReader( |
| 245 | + new ByteArrayInputStream(item.getData()), StandardCharsets.UTF_8))) { |
| 246 | + final SentryEvent event = |
| 247 | + options.getSerializer().deserialize(eventReader, SentryEvent.class); |
| 248 | + if (event != null && NATIVE_PLATFORM.equals(event.getPlatform())) { |
| 249 | + final long timestampMs = extractTimestampMs(event); |
| 250 | + return new NativeEventData(event, file, envelope, timestampMs); |
| 251 | + } |
| 252 | + } |
| 253 | + } |
| 254 | + } catch (Throwable e) { |
| 255 | + options |
| 256 | + .getLogger() |
| 257 | + .log(SentryLevel.DEBUG, e, "Error reading envelope file: %s", file.getAbsolutePath()); |
| 258 | + } |
| 259 | + return null; |
| 260 | + } |
| 261 | + |
| 262 | + private long extractTimestampMs(final @NotNull SentryEvent event) { |
| 263 | + final @Nullable Date timestamp = event.getTimestamp(); |
| 264 | + if (timestamp != null) { |
| 265 | + return timestamp.getTime(); |
| 266 | + } |
| 267 | + return 0; |
| 268 | + } |
| 269 | + |
| 270 | + private boolean isRelevantFileName(final @Nullable String fileName) { |
| 271 | + return fileName != null |
| 272 | + && !fileName.startsWith(PREFIX_CURRENT_SESSION_FILE) |
| 273 | + && !fileName.startsWith(PREFIX_PREVIOUS_SESSION_FILE) |
| 274 | + && !fileName.startsWith(STARTUP_CRASH_MARKER_FILE); |
| 275 | + } |
| 276 | +} |
0 commit comments