Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: use property syntax all the properties that are persisted #114

Open
wants to merge 12 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ internal class MockMemoryStorage : Storage {

override fun close() {
messageBatchMap.clear()
propertiesMap.clear()
}

override fun readInt(key: StorageKeys, defaultVal: Int): Int {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,17 @@ class MainActivity : ComponentActivity() {
weight = .5f,
viewModel = viewModel
)
Spacer(modifier = Modifier.height(2.dp))
CreateRowOfApis(
names = arrayOf(
AnalyticsState.SetAnonymousId,
AnalyticsState.GetAnonymousId,
AnalyticsState.GetUserId,
AnalyticsState.GetTraits,
),
weight = .5f,
viewModel = viewModel
)
CreateLogcat(state.logDataList)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,26 @@ class MainViewModel(application: Application) : AndroidViewModel(application) {
RudderAnalyticsUtils.initialize(getApplication())
"SDK initialized"
}

AnalyticsState.SetAnonymousId -> {
RudderAnalyticsUtils.analytics.anonymousId = "Custom Anonymous ID"
"Anonymous ID is set as: ${RudderAnalyticsUtils.analytics.anonymousId}"
}

AnalyticsState.GetAnonymousId -> {
val anonymousId = RudderAnalyticsUtils.analytics.anonymousId
"Anonymous ID: $anonymousId"
}

AnalyticsState.GetUserId -> {
val userId = RudderAnalyticsUtils.analytics.userId
"User ID: $userId"
}

AnalyticsState.GetTraits -> {
val traits = RudderAnalyticsUtils.analytics.traits
"Traits: $traits"
}
}
if (log.isNotEmpty()) addLogData(LogData(Date(), log))
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,8 @@ sealed class AnalyticsState(val eventName: String) {
object StartSession: AnalyticsState("Start Session")
object StartSessionWithCustomId: AnalyticsState("Start Session with custom id")
object EndSession: AnalyticsState("End Session")
object SetAnonymousId: AnalyticsState("Set Anonymous Id")
object GetAnonymousId: AnalyticsState("Get Anonymous Id")
object GetUserId: AnalyticsState("Get User Id")
object GetTraits: AnalyticsState("Get Traits")
}
102 changes: 73 additions & 29 deletions core/src/main/kotlin/com/rudderstack/sdk/kotlin/core/Analytics.kt
Original file line number Diff line number Diff line change
Expand Up @@ -342,33 +342,6 @@ open class Analytics protected constructor(
this.pluginChain.add(plugin)
}

/**
* Sets or updates the anonymous ID for the current user identity.
*
* The `setAnonymousId` method is used to update the `anonymousID` value within the `UserIdentityStore`.
* This ID is typically generated automatically to track users who have not yet been identified
* (e.g., before they log in or sign up). This function dispatches an action to modify the `UserIdentityState`,
* ensuring that the new ID is correctly stored and managed.
*
* @param anonymousId The new anonymous ID to be set for the current user. This ID should be a unique,
* non-null string used to represent the user anonymously.
*/
fun setAnonymousId(anonymousId: String) {
if (!isAnalyticsActive()) return

userIdentityState.dispatch(SetAnonymousIdAction(anonymousId))
storeAnonymousId()
}

/**
* The `getAnonymousId` method always retrieves the current anonymous ID.
*/
fun getAnonymousId(): String? {
if (!isAnalyticsActive()) return null

return userIdentityState.value.anonymousId
}

/**
* Resets the user identity, clearing the user ID, traits, and external IDs.
* If clearAnonymousId is true, clears the existing anonymous ID and generate a new one.
Expand Down Expand Up @@ -404,11 +377,82 @@ open class Analytics protected constructor(
}
}

override fun getPlatformType(): PlatformType = PlatformType.Server

/**
* Update or get the stored anonymous ID.
*
* The `analyticsInstance.anonymousId` is used to update and get the `anonymousID` value.
* This ID is typically generated automatically to track users who have not yet been identified
* (e.g., before they log in or sign up).
*
* This can return null if the analytics is shut down.
*
* Set the anonymousId:
* ```kotlin
* analyticsInstance.anonymousId = "Custom Anonymous ID"
* ```
*
* Get the anonymousId:
* ```kotlin
* val anonymousId = analyticsInstance.anonymousId
* ```
*/
var anonymousId: String?
get() {
if (!isAnalyticsActive()) return null
return userIdentityState.value.anonymousId
}
set(value) {
if (!isAnalyticsActive()) return

value?.let { anonymousId ->
userIdentityState.dispatch(SetAnonymousIdAction(anonymousId))
storeAnonymousId()
}
}

/**
* Get the user ID.
*
* The `analyticsInstance.userId` is used to get the `userId` value.
* This ID is assigned when an identify event is made.
*
* This can return null if the analytics is shut down.
*
* Get the userId:
* ```kotlin
* val userId = analyticsInstance.userId
* ```
*/
val userId: String?
get() {
if (!isAnalyticsActive()) return null
return userIdentityState.value.userId
}

/**
* Get the user traits.
*
* The `analyticsInstance.traits` is used to get the `traits` value.
* This traits is assigned when an identify event is made.
*
* This can return null if the analytics is shut down.
*
* Get the traits:
* ```kotlin
* val traits = analyticsInstance.traits
* ```
*/
val traits: RudderTraits?
get() {
if (!isAnalyticsActive()) return null
return userIdentityState.value.traits
}

private fun storeAnonymousId() {
analyticsScope.launch(storageDispatcher) {
userIdentityState.value.storeAnonymousId(storage = storage)
}
}

override fun getPlatformType(): PlatformType = PlatformType.Server
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ internal class EventQueue(
endPoint = BATCH_ENDPOINT,
authHeaderString = writeKey.encodeToBase64(),
isGZIPEnabled = gzipEnabled,
anonymousIdHeaderString = analytics.getAnonymousId() ?: String.empty()
anonymousIdHeaderString = analytics.anonymousId ?: String.empty()
)
}
) {
Expand Down
113 changes: 113 additions & 0 deletions core/src/test/kotlin/com/rudderstack/sdk/kotlin/core/AnalyticsTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
package com.rudderstack.sdk.kotlin.core

import com.rudderstack.sdk.kotlin.core.internals.models.emptyJsonObject
import com.rudderstack.sdk.kotlin.core.internals.storage.Storage
import com.rudderstack.sdk.kotlin.core.internals.storage.provideBasicStorage
import com.rudderstack.sdk.kotlin.core.internals.utils.MockMemoryStorage
import com.rudderstack.sdk.kotlin.core.internals.utils.empty
import io.mockk.every
import io.mockk.mockkStatic
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertNull
import junit.framework.TestCase.assertTrue
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import org.junit.Before
import org.junit.Test

private const val CUSTOM_ANONYMOUS_ID = "custom-anonymous-id"
private const val USER_ID = "user-id"
private val TRAITS: JsonObject = buildJsonObject { put("key-1", "value-1") }

class AnalyticsTest {

private val configuration = provideConfiguration()

private lateinit var analytics: Analytics
private lateinit var mockStorage: Storage

@Before
fun setup() {
mockStorage = MockMemoryStorage()

mockkStatic(::provideBasicStorage)
every { provideBasicStorage(any()) } returns mockStorage

analytics = Analytics(configuration = configuration)
}

@Test
fun `when anonymousId is fetched, then it should return UUID as the anonymousId`() {
val anonymousId = analytics.anonymousId

// This pattern ensures the string follows the UUID v4 format.
val uuidRegex = Regex("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
assertTrue(anonymousId?.matches(uuidRegex) == true)
}

@Test
fun `given custom anonymousId is set, when anonymousId is fetched, then it should return the custom anonymousId`() {
analytics.anonymousId = CUSTOM_ANONYMOUS_ID

val anonymousId = analytics.anonymousId

assertEquals(CUSTOM_ANONYMOUS_ID, anonymousId)
}

@Test
fun `given empty string is set as anonymousId, when anonymousId is fetched, then it should return the empty value`() {
analytics.anonymousId = String.empty()

val anonymousId = analytics.anonymousId

assertEquals(String.empty(), anonymousId)
}

@Test
fun `given sdk is shutdown, when anonymousId is fetched, then it should return null`() {
analytics.shutdown()

val anonymousId = analytics.anonymousId

assertNull(anonymousId)
}

@Test
fun `given userId and traits are set, when they are fetched, then the set values are returned`() {
// userId and traits can be set only through identify api
analytics.identify(userId = USER_ID, traits = TRAITS)

val userId = analytics.userId
val traits = analytics.traits

assertEquals(USER_ID, userId)
assertEquals(TRAITS, traits)
}

@Test
fun `given userId and traits are not set, when they are fetched, then empty values are returned`() {
val userId = analytics.userId
val traits = analytics.traits

assertEquals(String.empty(), userId)
assertEquals(emptyJsonObject, traits)
}

@Test
fun `given sdk is shutdown, when userId and traits are fetched, then it should return null`() {
analytics.shutdown()

val userId = analytics.userId
val traits = analytics.traits

assertNull(userId)
assertNull(traits)
}
}

private fun provideConfiguration() =
Configuration(
writeKey = "<writeKey>",
dataPlaneUrl = "<data_plane_url>",
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package com.rudderstack.sdk.kotlin.core.internals.utils

import com.rudderstack.sdk.kotlin.core.internals.storage.LibraryVersion
import com.rudderstack.sdk.kotlin.core.internals.storage.Storage
import com.rudderstack.sdk.kotlin.core.internals.storage.StorageKeys

internal class MockMemoryStorage : Storage {

private val propertiesMap: MutableMap<String, Any> = mutableMapOf()
private val messageBatchMap: MutableList<String> = mutableListOf()

override suspend fun write(key: StorageKeys, value: Boolean) {
if (key != StorageKeys.EVENT) {
propertiesMap[key.key] = value
}
}

override suspend fun write(key: StorageKeys, value: Int) {
if (key != StorageKeys.EVENT) {
propertiesMap[key.key] = value
}
}

override suspend fun write(key: StorageKeys, value: Long) {
if (key != StorageKeys.EVENT) {
propertiesMap[key.key] = value
}
}

override suspend fun write(key: StorageKeys, value: String) {
if (key == StorageKeys.EVENT) {
messageBatchMap.add(value)
} else {
propertiesMap[key.key] = value
}
}

override suspend fun remove(key: StorageKeys) {
propertiesMap.remove(key.key)
}

override fun remove(filePath: String) {
messageBatchMap.remove(filePath)
}

override suspend fun rollover() {
messageBatchMap.clear()
}

override fun close() {
messageBatchMap.clear()
propertiesMap.clear()
}

override fun readInt(key: StorageKeys, defaultVal: Int): Int {
return (propertiesMap[key.key] as? Int) ?: defaultVal
}

override fun readBoolean(key: StorageKeys, defaultVal: Boolean): Boolean {
return (propertiesMap[key.key] as? Boolean) ?: defaultVal
}

override fun readLong(key: StorageKeys, defaultVal: Long): Long {
return (propertiesMap[key.key] as? Long) ?: defaultVal
}

override fun readString(key: StorageKeys, defaultVal: String): String {
return if (key == StorageKeys.EVENT) {
messageBatchMap.joinToString()
} else {
(propertiesMap[key.key] as? String) ?: defaultVal
}
}

override fun readFileList(): List<String> {
return messageBatchMap
}

override fun getLibraryVersion(): LibraryVersion {
return object : LibraryVersion {
override fun getPackageName(): String = "com.rudderstack.sdk.kotlin.core"

override fun getVersionName() = "1.0.0"
}
}
}
Loading