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

[#14] Autogenerate user identifier #46

Open
wants to merge 2 commits into
base: main
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
30 changes: 29 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,40 @@ To enqueue a signal to be sent by TelemetryDeck at a later time
TelemetryDeck.signal("appLaunchedRegularly")
```

## User Identifiers

When `TelemetryDeck` is started for the first time, it will create a user identifier for the user that is specific to the app installation.

* The identity is stored within the application's file folder on the user's device.

* The identifier will be removed when a user uninstalls an app. The KotlinSDK will not "bridge" the user's identity between installations.

* Users can reset the identifier at any time by using the "Clear Data" action in Settings of their device.

If you have a better user identifier available, such as an email address or a username, you can use that instead, by setting `defaultUser` (the identifier will be hashed before sending it) in configuration, or by passing the value when sending signals.


### Custom User Identifiers

If you need a more robust mechanism for keep track of the user's identity, you can replace the default behaviour by providing your own implementation of `TelemetryDeckIdentityProvider`:

```kotlin
val builder = TelemetryDeck.Builder()
.appID("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
.showDebugLogs(true)
.defaultUser("Person")
.identityProvider(YourIdentityProvider())

TelemetryDeck.start(application, builder)
```


### Environment Parameters

By default, Kotlin SDK for TelemetryDeck will include the following environment parameters for each outgoing signal


| Signal name | Provider |
| Parameter name | Provider |
|------------------------------------------------|--------------------------------|
| `TelemetryDeck.Session.started` | `SessionAppProvider` |
| `TelemetryDeck.AppInfo.buildNumber` | `EnvironmentParameterProvider` |
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package com.telemetrydeck.sdk

import android.app.Application
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.telemetrydeck.sdk.providers.FileUserIdentityProvider
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Test
import org.junit.runner.RunWith
import java.io.File

@RunWith(AndroidJUnit4::class)
class FileUserIdentityProviderTest {

private fun createSut(): FileUserIdentityProvider {
val appContext = ApplicationProvider.getApplicationContext<Application>()
val sut = FileUserIdentityProvider()
sut.register(appContext, TelemetryDeck(configuration = TelemetryManagerConfiguration("32CB6574-6732-4238-879F-582FEBEB6536"), providers = emptyList()))
return sut
}

private fun prepareIdentity(value: String) {
val appContext = ApplicationProvider.getApplicationContext<Application>()
val file = File(appContext.filesDir, "telemetrydeckid")
file.writeText(value)
}

@Test
fun providesConfigUserIdentity() {
prepareIdentity("1851B82D-3D39-469D-BED4-19E69C09AF49")

val sut = createSut()
val result = sut.calculateIdentity(null, "default user id")
assertEquals("default user id", result)
}

@Test
fun prefersSignalIdWhenProvided() {
prepareIdentity("1851B82D-3D39-469D-BED4-19E69C09AF49")

val sut = createSut()
val result = sut.calculateIdentity("signal id", "default user id")
assertEquals("signal id", result)
}

@Test
fun usesDefaultUserIdentityWhenSignalAndConfigIsNull() {
prepareIdentity("1851B82D-3D39-469D-BED4-19E69C09AF49")

val sut = createSut()
val result = sut.calculateIdentity(null, null)
assertEquals("1851B82D-3D39-469D-BED4-19E69C09AF49", result)
}

@Test
fun createsStableUserIdentity() {
val sut1 = createSut()
val first_result = sut1.calculateIdentity(null, null)
assert(!first_result.isBlank())

val sut2 = createSut()
val second_result = sut2.calculateIdentity(null, null)
assertEquals(first_result, second_result)
}

@Test
fun resetsStableUserIdentity() {
val sut1 = createSut()
val first_result = sut1.calculateIdentity(null, null)
sut1.resetIdentity()

val sut2 = createSut()
val second_result = sut2.calculateIdentity(null, null)
assertNotEquals(first_result, second_result)
}
}
19 changes: 17 additions & 2 deletions lib/src/main/java/com/telemetrydeck/sdk/TelemetryDeck.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import android.content.Context
import android.content.pm.ApplicationInfo
import com.telemetrydeck.sdk.params.Navigation
import com.telemetrydeck.sdk.providers.EnvironmentParameterProvider
import com.telemetrydeck.sdk.providers.FileUserIdentityProvider
import com.telemetrydeck.sdk.providers.PlatformContextProvider
import com.telemetrydeck.sdk.providers.SessionAppProvider
import java.lang.ref.WeakReference
Expand All @@ -20,6 +21,7 @@ class TelemetryDeck(
) : TelemetryDeckClient, TelemetryDeckSignalProcessor {
var cache: SignalCache? = null
var logger: DebugLogger? = null
var identityProvider: TelemetryDeckIdentityProvider = FileUserIdentityProvider()
private val navigationStatus: NavigationStatus = MemoryNavigationStatus()

override val signalCache: SignalCache?
Expand Down Expand Up @@ -140,6 +142,7 @@ class TelemetryDeck(
logger?.debug("Installing provider ${provider::class}.")
provider.register(context?.applicationContext as Application?, this)
}
identityProvider.register(context?.applicationContext as Application?, this)
}

private fun createSignal(
Expand All @@ -152,7 +155,8 @@ class TelemetryDeck(
for (provider in this.providers) {
enrichedPayload = provider.enrich(signalType, clientUser, enrichedPayload)
}
val userValue = clientUser ?: configuration.defaultUser ?: ""

val userValue = identityProvider.calculateIdentity(clientUser, configuration.defaultUser)

val userValueWithSalt = userValue + (configuration.salt ?: "")
val hashedUser = hashString(userValueWithSalt)
Expand Down Expand Up @@ -222,6 +226,7 @@ class TelemetryDeck(
for (provider in manager.providers) {
provider.stop()
}
manager.identityProvider.stop()
synchronized(this) {
instance = null
}
Expand Down Expand Up @@ -329,7 +334,8 @@ class TelemetryDeck(
private var sendNewSessionBeganSignal: Boolean? = null,
private var apiBaseURL: URL? = null,
private var logger: DebugLogger? = null,
private var salt: String? = null
private var salt: String? = null,
private var identityProvider: TelemetryDeckIdentityProvider? = null
) {
/**
* Set the TelemetryManager configuration.
Expand Down Expand Up @@ -396,6 +402,10 @@ class TelemetryDeck(
this.salt = salt
}

fun identityProvider(identityProvider: TelemetryDeckIdentityProvider) = apply {
this.identityProvider = identityProvider
}

/**
* Provide a custom logger implementation to be used by [TelemetryDeck] when logging internal messages.
*/
Expand Down Expand Up @@ -486,6 +496,11 @@ class TelemetryDeck(
manager.cache = MemorySignalCache()
}

val userIdentityProvider = this.identityProvider
if (userIdentityProvider != null) {
manager.identityProvider = userIdentityProvider
}

return manager
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.telemetrydeck.sdk

import android.app.Application

/**
* Generic interface for plugins which can calculate anonymous user identifier
*/
interface TelemetryDeckIdentityProvider {
/**
* Registers the provider with the telemetry manager.
*/
fun register(ctx: Application?, client: TelemetryDeckSignalProcessor)

/**
* Calling stop deactivates the provider, performs any cleanup work if necessary.
*/
fun stop()


/**
* Calculate the user identifier to be attached to a signal.
*
* @param[signalClientUser] The existing `clientUser` value of the signal (if any has been provided).
* @param[configurationDefaultUser] The default user value from the [TelemetryDeck] configuration (if any has been provided).
* @return the user identifier to be associated with the outgoing signal.
*/
fun calculateIdentity(signalClientUser: String?, configurationDefaultUser: String?): String

/**
* Permanently removes any persisted user identifier.
*/
fun resetIdentity()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package com.telemetrydeck.sdk.providers

import android.app.Application
import com.telemetrydeck.sdk.TelemetryDeckIdentityProvider
import com.telemetrydeck.sdk.TelemetryDeckSignalProcessor
import java.io.File
import java.lang.ref.WeakReference
import java.util.UUID

/**
* [FileUserIdentityProvider] attempts to provide a stable user identifier across multiple sessions.
*
* When no user identifier has been provided to [com.telemetrydeck.sdk.TelemetryDeck], [FileUserIdentityProvider] uses a file
* in the application's folder to store a randomly generated user identifier.
*
* The identifier will be removed when a user uninstalls an app. The KotlinSDK will not "bridge" the user's identity between installations.
* Users can reset the identifier at any time by using the "Clear Data" action in Settings of their device.
*
*
* */
class FileUserIdentityProvider: TelemetryDeckIdentityProvider {
private var app: WeakReference<Application?>? = null
private var manager: WeakReference<TelemetryDeckSignalProcessor>? = null
private val fileName = "telemetrydeckid"
private val fileEncoding = Charsets.UTF_8

override fun register(ctx: Application?, client: TelemetryDeckSignalProcessor) {
this.app = WeakReference(ctx)
this.manager = WeakReference(client)
}

override fun stop() {
// nothing to do here
}

override fun calculateIdentity(signalClientUser: String?, configurationDefaultUser: String?): String {
val simpleValue = signalClientUser ?: configurationDefaultUser ?: readOrCreateStableIdentity() ?: ""
return simpleValue
}

override fun resetIdentity() {
// to reset, we delete the identity file if it exists
val context = this.app?.get()?.applicationContext ?: return
val file = File(context.filesDir, fileName)
try {
if (file.exists()) {
file.delete()
}
} catch (e: Exception) {
this.manager?.get()?.debugLogger?.error(e.stackTraceToString())
}
}

private fun readOrCreateStableIdentity(): String? {
val context = this.app?.get()?.applicationContext ?: return null

try {
val file = File(context.filesDir, fileName)
if (!file.exists()) {
val newId = UUID.randomUUID().toString()
file.writeText(newId, fileEncoding)
return newId
}

return file.readText(fileEncoding)
} catch (e: Exception) {
this.manager?.get()?.debugLogger?.error(e.stackTraceToString())
return null
}
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.telemetrydeck.sdk.providers

import android.app.Application
import android.content.Context
import com.telemetrydeck.sdk.TelemetryDeckProvider
import com.telemetrydeck.sdk.TelemetryDeckSignalProcessor
import com.telemetrydeck.sdk.TelemetryProviderFallback
Expand All @@ -17,7 +16,7 @@ import java.lang.ref.WeakReference
internal class PlatformContextProvider : TelemetryDeckProvider, TelemetryProviderFallback {
private var enabled: Boolean = true
private var manager: WeakReference<TelemetryDeckSignalProcessor>? = null
private var appContext: WeakReference<Context?>? = null
private var appContext: WeakReference<Application?>? = null
private var metadata = mutableMapOf<String, String>()

override fun fallbackRegister(ctx: Application?, client: TelemetryDeckSignalProcessor) {
Expand All @@ -30,7 +29,7 @@ internal class PlatformContextProvider : TelemetryDeckProvider, TelemetryProvide

override fun register(ctx: Application?, client: TelemetryDeckSignalProcessor) {
this.manager = WeakReference(client)
this.appContext = WeakReference(ctx?.applicationContext)
this.appContext = WeakReference(ctx)

if (ctx == null) {
this.manager?.get()?.debugLogger?.error("RunContextProvider requires a context but received null. Signals will contain incomplete metadata.")
Expand Down Expand Up @@ -91,7 +90,7 @@ internal class PlatformContextProvider : TelemetryDeckProvider, TelemetryProvide
// TODO: Use onConfigurationChanged instead

private fun getDynamicAttributes(): Map<String, String> {
val ctx = this.appContext?.get()
val ctx = this.appContext?.get()?.applicationContext
?: // can't read without a context!
return emptyMap()

Expand Down
Loading
Loading