|
| 1 | +package io.sentry.samples.android |
| 2 | + |
| 3 | +import io.sentry.SentryOptions |
| 4 | +import io.sentry.protocol.SentryTransaction |
| 5 | +import java.util.concurrent.CopyOnWriteArrayList |
| 6 | + |
| 7 | +/** |
| 8 | + * Owns the single global beforeSendTransaction hook used by sample screens that inspect finished |
| 9 | + * transactions. |
| 10 | + * |
| 11 | + * Multiple sample activities can overlap briefly during configuration changes or relaunches. If |
| 12 | + * each screen installs and restores its own callback, a later uninstall can resurrect a stale |
| 13 | + * wrapper callback that still retains dead state and drops the original callback chain. |
| 14 | + * |
| 15 | + * Keep one stable callback installed and let sample screens register lightweight listeners against |
| 16 | + * it instead. |
| 17 | + */ |
| 18 | +internal object SampleBeforeSendTransactionHook { |
| 19 | + |
| 20 | + private val listeners = CopyOnWriteArrayList<(SentryTransaction, String?) -> Unit>() |
| 21 | + |
| 22 | + @Volatile private var installedCallback: SentryOptions.BeforeSendTransactionCallback? = null |
| 23 | + @Volatile private var previousCallback: SentryOptions.BeforeSendTransactionCallback? = null |
| 24 | + |
| 25 | + fun installIfNeeded(options: SentryOptions) { |
| 26 | + if (installedCallback != null) { |
| 27 | + return |
| 28 | + } |
| 29 | + |
| 30 | + synchronized(this) { |
| 31 | + if (installedCallback != null) { |
| 32 | + return |
| 33 | + } |
| 34 | + |
| 35 | + previousCallback = options.beforeSendTransaction |
| 36 | + val callback = SentryOptions.BeforeSendTransactionCallback { transaction, hint -> |
| 37 | + val previous = previousCallback |
| 38 | + |
| 39 | + val processedTransaction = |
| 40 | + if (previous == null) { |
| 41 | + transaction |
| 42 | + } else { |
| 43 | + previous.execute(transaction, hint) |
| 44 | + } |
| 45 | + |
| 46 | + processedTransaction?.let { processed -> |
| 47 | + listeners.forEach { listener -> |
| 48 | + try { |
| 49 | + listener(processed, options.dsn) |
| 50 | + } catch (e: RuntimeException) { |
| 51 | + options.logger.log( |
| 52 | + io.sentry.SentryLevel.ERROR, |
| 53 | + "Sample transaction listener failed.", |
| 54 | + e, |
| 55 | + ) |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + processedTransaction |
| 61 | + } |
| 62 | + |
| 63 | + installedCallback = callback |
| 64 | + options.beforeSendTransaction = callback |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + fun addListener(listener: (SentryTransaction, String?) -> Unit) { |
| 69 | + listeners.addIfAbsent(listener) |
| 70 | + } |
| 71 | + |
| 72 | + fun removeListener(listener: (SentryTransaction, String?) -> Unit) { |
| 73 | + listeners.remove(listener) |
| 74 | + } |
| 75 | +} |
0 commit comments