From 8e3b4422a933f87c1a36a6efd583ebf0803891a1 Mon Sep 17 00:00:00 2001 From: Harsh Shandilya Date: Sat, 3 Dec 2022 17:46:03 +0530 Subject: feat(app): add implementations for SentryLeakUploader --- .../passwordstore/util/leaks/SentryLeakUploader.kt | 67 ++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 app/src/nonFree/java/app/passwordstore/util/leaks/SentryLeakUploader.kt (limited to 'app/src/nonFree/java') diff --git a/app/src/nonFree/java/app/passwordstore/util/leaks/SentryLeakUploader.kt b/app/src/nonFree/java/app/passwordstore/util/leaks/SentryLeakUploader.kt new file mode 100644 index 00000000..d8889350 --- /dev/null +++ b/app/src/nonFree/java/app/passwordstore/util/leaks/SentryLeakUploader.kt @@ -0,0 +1,67 @@ +package app.passwordstore.util.leaks + +import io.sentry.Sentry +import io.sentry.SentryEvent +import leakcanary.EventListener +import leakcanary.EventListener.Event +import shark.HeapAnalysisSuccess +import shark.Leak +import shark.LeakTrace +import shark.LibraryLeak + +object SentryLeakUploader : EventListener { + + override fun onEvent(event: Event) { + when (event) { + is Event.HeapAnalysisDone<*> -> { + if (event.heapAnalysis !is HeapAnalysisSuccess) return + val heapAnalysis = event.heapAnalysis as HeapAnalysisSuccess + val allLeakTraces = + heapAnalysis.allLeaks.toList().flatMap { leak -> + leak.leakTraces.map { leakTrace -> leak to leakTrace } + } + + allLeakTraces.forEach { (leak, leakTrace) -> + val exception = FakeReportingException(leak.shortDescription) + val sentryEvent = + SentryEvent(exception).apply { + val leakContexts = mutableMapOf() + addHeapAnalysis(heapAnalysis, leakContexts) + addLeak(leak, leakContexts) + addLeakTrace(leakTrace, leakContexts) + contexts["Leak"] = leakContexts + // grouping leaks + fingerprints = listOf(leak.signature) + } + Sentry.captureEvent(sentryEvent) + } + } + else -> {} + } + } + + private fun addHeapAnalysis( + heapAnalysis: HeapAnalysisSuccess, + leakContexts: MutableMap + ) { + leakContexts["heapDumpPath"] = heapAnalysis.heapDumpFile.absolutePath + heapAnalysis.metadata.forEach { (key, value) -> leakContexts[key] = value } + leakContexts["analysisDurationMs"] = heapAnalysis.analysisDurationMillis + } + + private fun addLeak(leak: Leak, leakContexts: MutableMap) { + leakContexts["libraryLeak"] = leak is LibraryLeak + if (leak is LibraryLeak) { + leakContexts["libraryLeakPattern"] = leak.pattern.toString() + leakContexts["libraryLeakDescription"] = leak.description + } + } + + private fun addLeakTrace(leakTrace: LeakTrace, leakContexts: MutableMap) { + leakTrace.retainedHeapByteSize?.let { leakContexts["retainedHeapByteSize"] = it } + leakContexts["signature"] = leakTrace.signature + leakContexts["leakTrace"] = leakTrace.toString() + } + + class FakeReportingException(message: String) : RuntimeException(message) +} -- cgit v1.2.3