Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit 79c8091d authored by George Lin's avatar George Lin
Browse files

Create InstanceIdSequence only when necessary

Before InstanceIdSequence can be created whenever AppSessionId is
created. The change makes sure that InstanceIdSequence can only be
created when createNewId() is called.

Test: Manaully tested that the logs are still correct
Bug: 306655749
Flag: None
Change-Id: I8cd22f9e69e25d9210c27e721c08ba1c1cc61397
parent a1870dff
Loading
Loading
Loading
Loading
+16 −4
Original line number Diff line number Diff line
@@ -15,6 +15,7 @@
 */
package com.android.customization.module.logging

import android.util.Log
import com.android.internal.logging.InstanceId
import com.android.internal.logging.InstanceIdSequence
import javax.inject.Inject
@@ -23,9 +24,9 @@ import javax.inject.Singleton
@Singleton
class AppSessionId @Inject constructor() {

    private val idSequence = InstanceIdSequence(INSTANCE_ID_MAX)
    private var idSequence: InstanceIdSequence? = null

    private var sessionId: InstanceId = newInstanceId()
    private var sessionId: InstanceId? = null

    fun createNewId(): AppSessionId {
        sessionId = newInstanceId()
@@ -33,12 +34,23 @@ class AppSessionId @Inject constructor() {
    }

    fun getId(): Int {
        return sessionId.hashCode()
        val id =
            sessionId
                ?: newInstanceId().also {
                    Log.w(
                        TAG,
                        "Session ID should not be null. We should always call createNewId() before calling getId()."
                    )
                    sessionId = it
                }
        return id.hashCode()
    }

    private fun newInstanceId(): InstanceId = idSequence.newInstanceId()
    private fun newInstanceId(): InstanceId =
        (idSequence ?: InstanceIdSequence(INSTANCE_ID_MAX).also { idSequence = it }).newInstanceId()

    companion object {
        private const val TAG = "AppSessionId"
        // At most 20 bits: ~1m possibilities, ~0.5% probability of collision in 100 values
        private const val INSTANCE_ID_MAX = 1 shl 20
    }