Skip to content

Commit

Permalink
add try-catch for OutOfMemoryError (#217)
Browse files Browse the repository at this point in the history
* add try-catch throwable
* fix: flaky test
  • Loading branch information
wasnot authored Mar 15, 2023
1 parent d71024b commit ccc007f
Show file tree
Hide file tree
Showing 8 changed files with 47 additions and 36 deletions.
10 changes: 5 additions & 5 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,15 @@ jobs:
test:
executor:
name: android/android-machine
tag: 2023.02.01
tag: 2023.02.1
steps:
- checkout
- add_google_services
- run_lint
- run_doc_check
- run_static_analysis
- android/restore-gradle-cache
- android/restore-build-cache
- add_google_services
- android/run-tests:
test-command: ./gradlew --stacktrace --info testDebug
- android/save-gradle-cache
Expand All @@ -72,7 +72,7 @@ jobs:
ui_test:
executor:
name: android/android-machine
tag: 2023.02.01
tag: 2023.02.1
steps:
- checkout
- run:
Expand All @@ -86,7 +86,7 @@ jobs:
publish_docs:
executor:
name: android/android-machine
tag: 2023.02.01
tag: 2023.02.1
steps:
- checkout
- android/restore-gradle-cache
Expand All @@ -104,7 +104,7 @@ jobs:
publish:
executor:
name: android/android-machine
tag: 2023.02.01
tag: 2023.02.1
steps:
- checkout
- android/restore-gradle-cache
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ private fun Date.asPrefix(): String = format("yyyy-MM-dd")
private fun File.files(): List<File> = listFiles()?.filter { it.isFile } ?: listOf()
private const val LOG_TAG = "Karte.Log.FileAppender"
private const val THREAD_NAME = "io.karte.android.logger.buffer"
private const val DIR_PATH = "io.karte.android/log"
private const val BUFFER_SIZE = 10000

private fun logDebug(message: String) {
Expand All @@ -58,14 +59,14 @@ private fun logDebug(message: String) {
Log.d(LOG_TAG, message)
}

internal class FileAppender internal constructor(threadName: String = THREAD_NAME) : Appender, Flushable {
internal class FileAppender internal constructor(threadName: String = THREAD_NAME, private val directoryPath: String = DIR_PATH) : Appender, Flushable {
private val handler: Handler =
Handler(HandlerThread(threadName, Process.THREAD_PRIORITY_LOWEST).apply { start() }.looper)
private val buffer = StringBuilder()

private val logDir: File?
get() = runCatching {
File(KarteApp.self.application.cacheDir, "io.karte.android/log").apply { mkdirs() }
File(KarteApp.self.application.cacheDir, directoryPath).apply { mkdirs() }
}.getOrNull()

/**Bufferの書き込み先ファイル.*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ internal class Dispatcher {
.forEach { add(it) }
}
}

init {
DataStore.setup(KarteApp.self.application.applicationContext, EventRecord.EventContract)
KarteApp.self.connectivityObserver?.subscribe(::connectivity)
Expand Down Expand Up @@ -199,7 +200,7 @@ internal class Dispatcher {
handleFailure(events)
}
}
} catch (e: Exception) {
} catch (e: Throwable) {
Logger.e(LOG_TAG, "Failed to send request.", e)
handleFailure(events)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,14 @@ val testFiles = listOf(
"2020-04-06_test.log"
)
const val THREAD_NAME = "file_appender_test"
const val DIR_PATH = "io.karte.android/log-test"

@RunWith(RobolectricTestRunner::class)
@org.robolectric.annotation.Config(sdk = [28])
abstract class BaseFileAppenderTest {
internal val fileAppender = FileAppender(THREAD_NAME)
internal val fileAppender = FileAppender(THREAD_NAME, DIR_PATH)
protected val logDir: File
get() = File(application().cacheDir, "io.karte.android/log")
get() = File(application().cacheDir, DIR_PATH)
protected val cacheFiles: List<File>
get() = logDir.listFiles()?.filter { it.isFile } ?: listOf()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,19 @@ import io.karte.android.utilities.map
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.util.ArrayList

private const val LOG_TAG = "Karte.IAMessages"

internal class MessageModel @Throws(JSONException::class)
constructor(private val data: JSONObject?, private val request: TrackRequest) {

val string: String
get() = Base64.encodeToString(data.toString().toByteArray(), Base64.NO_WRAP)
get() = runCatching {
Base64.encodeToString(data.toString().toByteArray(), Base64.NO_WRAP)
}.onFailure {
// OutOfMemory を想定
Logger.e(LOG_TAG, "Failed to encode: ${it.message}", it)
}.getOrDefault("")

val messages: List<JSONObject>
@Throws(JSONException::class)
Expand Down Expand Up @@ -99,17 +103,19 @@ constructor(private val data: JSONObject?, private val request: TrackRequest) {
}

override fun toString(): String {
return "Messages: ${messages.joinToString { message ->
val action = message.optJSONObject("action")
JSONObject()
.put(
"action", JSONObject()
.put("_id", action?.optString("_id"))
.put("shorten_id", action?.optString("shorten_id"))
)
.put("campaign", message.optJSONObject("campaign"))
.toString()
}}"
return "Messages: ${
messages.joinToString { message ->
val action = message.optJSONObject("action")
JSONObject()
.put(
"action", JSONObject()
.put("_id", action?.optString("_id"))
.put("shorten_id", action?.optString("shorten_id"))
)
.put("campaign", message.optJSONObject("campaign"))
.toString()
}
}"
}

internal interface MessageAdapter {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ import io.karte.android.inappmessaging.BuildConfig
import io.karte.android.inappmessaging.R
import io.karte.android.inappmessaging.internal.PanelWindowManager
import java.lang.ref.WeakReference
import java.util.ArrayList

private const val LOG_TAG = "Karte.IAMView"
private const val WINDOW_FLAGS_FOCUSED = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN or
Expand Down Expand Up @@ -203,14 +202,18 @@ internal open class WindowView(
)
return
}
val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// https://stackoverflow.com/questions/9247369/alpha-8-bitmaps-and-getpixel
Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8)
} else {
Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
try {
val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// https://stackoverflow.com/questions/9247369/alpha-8-bitmaps-and-getpixel
Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8)
} else {
Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
}
canvas = Canvas(bitmap)
webViewDrawingBitmap = bitmap
} catch (e: OutOfMemoryError) {
Logger.e(LOG_TAG, "OutOfMemoryError occurred: ${e.message}", e)
}
canvas = Canvas(bitmap)
webViewDrawingBitmap = bitmap
}

override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ import io.karte.android.visualtracking.VisualTracking
import io.karte.android.visualtracking.internal.tracing.Trace
import org.json.JSONException
import org.json.JSONObject
import java.util.ArrayList
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledThreadPoolExecutor
import java.util.concurrent.TimeUnit
Expand Down Expand Up @@ -91,7 +90,7 @@ internal class PairingManager(private val app: KarteApp) : ActivityLifecycleCall
} else {
throw KarteServerException(resp.body)
}
} catch (e: Exception) {
} catch (e: Throwable) {
showPairingFailedToast(context)
setPairingAccountId(null)
Logger.e(LOG_TAG, "Failed to start Pairing.", e)
Expand All @@ -115,7 +114,7 @@ internal class PairingManager(private val app: KarteApp) : ActivityLifecycleCall

val res = Client.execute(request)
finishPairingIfNeeded(res)
} catch (e: Exception) {
} catch (e: Throwable) {
Logger.e(LOG_TAG, "Failed to heartbeat.", e)
}

Expand Down Expand Up @@ -167,7 +166,7 @@ internal class PairingManager(private val app: KarteApp) : ActivityLifecycleCall
Logger.e(LOG_TAG, "Failed to send action. Response=" + res.body)
}
finishPairingIfNeeded(res)
} catch (e: Exception) {
} catch (e: Throwable) {
Logger.e(LOG_TAG, "Failed to send action info.", e)
}
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ internal object GetDefinitions {
val result =
runCatching { JSONObject(response.body) }.getOrNull()?.optJSONObject("response")
completion?.invoke(result)
} catch (e: Exception) {
} catch (e: Throwable) {
Logger.e(LOG_TAG, "Failed to get definitions.", e)
}
}
Expand Down

0 comments on commit ccc007f

Please sign in to comment.