diff --git a/OneSignalSDK/detekt/detekt-baseline-core.xml b/OneSignalSDK/detekt/detekt-baseline-core.xml
index 74e9f501d2..40db555e47 100644
--- a/OneSignalSDK/detekt/detekt-baseline-core.xml
+++ b/OneSignalSDK/detekt/detekt-baseline-core.xml
@@ -8,7 +8,7 @@
ComplexMethod:ConfigModelStoreListener.kt$ConfigModelStoreListener$private fun fetchParams()
ComplexMethod:HttpClient.kt$HttpClient$private suspend fun makeRequestIODispatcher( url: String, method: String?, jsonBody: JSONObject?, timeout: Int, headers: OptionalHeaders?, ): HttpResponse
ComplexMethod:IdentityOperationExecutor.kt$IdentityOperationExecutor$override suspend fun execute(operations: List<Operation>): ExecutionResponse
- ComplexMethod:LoginUserOperationExecutor.kt$LoginUserOperationExecutor$private suspend fun createUser( createUserOperation: LoginUserOperation, operations: List<Operation>, ): ExecutionResponse
+ ComplexMethod:LoginUserOperationExecutor.kt$LoginUserOperationExecutor$private suspend fun createUser( createUserOperation: LoginUserOperation, operations: List<Operation>, mergeIntoOnesignalId: String? = null, ): ExecutionResponse
ComplexMethod:OSDatabase.kt$OSDatabase$@Synchronized private fun internalOnUpgrade( db: SQLiteDatabase, oldVersion: Int, newVersion: Int, )
ComplexMethod:OperationModelStore.kt$OperationModelStore$override fun create(jsonObject: JSONObject?): Operation?
ComplexMethod:OperationRepo.kt$OperationRepo$internal suspend fun executeOperations(ops: List<OperationQueueItem>)
@@ -194,7 +194,7 @@
LongMethod:FeatureFlagsBackendService.kt$FeatureFlagsBackendService$override suspend fun fetchRemoteFeatureFlags(appId: String): RemoteFeatureFlagsFetchOutcome
LongMethod:HttpClient.kt$HttpClient$private suspend fun makeRequestIODispatcher( url: String, method: String?, jsonBody: JSONObject?, timeout: Int, headers: OptionalHeaders?, ): HttpResponse
LongMethod:IdentityOperationExecutor.kt$IdentityOperationExecutor$override suspend fun execute(operations: List<Operation>): ExecutionResponse
- LongMethod:LoginUserOperationExecutor.kt$LoginUserOperationExecutor$private suspend fun createUser( createUserOperation: LoginUserOperation, operations: List<Operation>, ): ExecutionResponse
+ LongMethod:LoginUserOperationExecutor.kt$LoginUserOperationExecutor$private suspend fun createUser( createUserOperation: LoginUserOperation, operations: List<Operation>, mergeIntoOnesignalId: String? = null, ): ExecutionResponse
LongMethod:LoginUserOperationExecutor.kt$LoginUserOperationExecutor$private suspend fun loginUser( loginUserOp: LoginUserOperation, operations: List<Operation>, ): ExecutionResponse
LongMethod:OperationRepo.kt$OperationRepo$internal suspend fun executeOperations(ops: List<OperationQueueItem>)
LongMethod:OperationRepo.kt$OperationRepo$private fun internalEnqueue( queueItem: OperationQueueItem, flush: Boolean, addToStore: Boolean, index: Int? = null, )
@@ -293,7 +293,7 @@
NestedBlockDepth:IdentityOperationExecutor.kt$IdentityOperationExecutor$override suspend fun execute(operations: List<Operation>): ExecutionResponse
NestedBlockDepth:InfluenceManager.kt$InfluenceManager$private fun attemptSessionUpgrade( entryAction: AppEntryAction, directId: String? = null, )
NestedBlockDepth:JSONUtils.kt$JSONUtils$fun compareJSONArrays( jsonArray1: JSONArray?, jsonArray2: JSONArray?, ): Boolean
- NestedBlockDepth:LoginUserOperationExecutor.kt$LoginUserOperationExecutor$private suspend fun createUser( createUserOperation: LoginUserOperation, operations: List<Operation>, ): ExecutionResponse
+ NestedBlockDepth:LoginUserOperationExecutor.kt$LoginUserOperationExecutor$private suspend fun createUser( createUserOperation: LoginUserOperation, operations: List<Operation>, mergeIntoOnesignalId: String? = null, ): ExecutionResponse
NestedBlockDepth:RefreshUserOperationExecutor.kt$RefreshUserOperationExecutor$private suspend fun getUser(op: RefreshUserOperation): ExecutionResponse
NestedBlockDepth:ServiceRegistration.kt$ServiceRegistrationReflection$override fun resolve(provider: IServiceProvider): Any?
NestedBlockDepth:ServiceRegistration.kt$ServiceRegistrationReflection$private fun doesHaveAllParameters( constructor: Constructor<*>, provider: IServiceProvider, ): Boolean
diff --git a/OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/operations/impl/executors/LoginUserOperationExecutor.kt b/OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/operations/impl/executors/LoginUserOperationExecutor.kt
index a325fd2a53..9a39143f76 100644
--- a/OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/operations/impl/executors/LoginUserOperationExecutor.kt
+++ b/OneSignalSDK/onesignal/core/src/main/java/com/onesignal/user/internal/operations/impl/executors/LoginUserOperationExecutor.kt
@@ -1,6 +1,7 @@
package com.onesignal.user.internal.operations.impl.executors
import android.os.Build
+import com.onesignal.OneSignalError
import com.onesignal.common.AndroidUtils
import com.onesignal.common.DeviceUtils
import com.onesignal.common.IDManager
@@ -91,15 +92,12 @@ internal class LoginUserOperationExecutor(
return ExecutionResponse(ExecutionResult.FAIL_NORETRY)
}
if (shouldCreateUserDirectly(loginUserOp, alias)) {
- // When there is no existing user to attempt to associate with the externalId provided, we go right to
- // createUser. If there is no externalId provided this is an insert, if there is this will be an
- // "upsert with retrieval" as the user may already exist.
- //
- // Under IV, also skip the optimistic SetAliasOperation: that inline op identifies the
- // target user by `onesignal_id = existingOnesignalId`, but IV's alias-resolution would
- // rewrite the call to identify by the new (not-yet-registered) `external_id`, producing
- // a 404 or idempotent success against the wrong user. createUser's identities-map path
- // handles the merge correctly through backend upsert semantics.
+ // A server anonymous user is merged by sending its onesignal_id. Under IV, skip
+ // SetAlias: alias resolution would target the new external_id and 404 or hit the wrong user.
+ anonymousUserToMerge(loginUserOp, alias)?.let { anonymousId ->
+ val merged = createUser(loginUserOp, operations, anonymousId)
+ if (!shouldAbandonMerge(merged)) return merged
+ }
return createUser(loginUserOp, operations)
} else {
// before we create a user we attempt to associate the user defined by existingOnesignalId with the
@@ -179,8 +177,10 @@ internal class LoginUserOperationExecutor(
private suspend fun createUser(
createUserOperation: LoginUserOperation,
operations: List,
+ mergeIntoOnesignalId: String? = null,
): ExecutionResponse {
val identities = mutableMapOf()
+ mergeIntoOnesignalId?.let { identities[IdentityConstants.ONESIGNAL_ID] = it }
var subscriptions = mapOf()
val properties =
PropertiesObject(
@@ -314,17 +314,29 @@ internal class LoginUserOperationExecutor(
metadata = LoginWaitMetadata(backendOneSignalId, emailSubscriptionId, smsSubscriptionId),
)
} catch (ex: BackendException) {
- Logging.error("LoginUserOperationExecutor.createUser failed: HTTP ${ex.statusCode}")
val responseType = NetworkUtils.getResponseStatusType(ex.statusCode)
-
- return when (responseType) {
- NetworkUtils.ResponseStatusType.RETRYABLE ->
- backendExecutionResponse(ExecutionResult.FAIL_RETRY, ex)
- NetworkUtils.ResponseStatusType.UNAUTHORIZED ->
- backendExecutionResponse(ExecutionResult.FAIL_UNAUTHORIZED, ex)
- else ->
- backendExecutionResponse(ExecutionResult.FAIL_NORETRY, ex)
+ val response =
+ when (responseType) {
+ NetworkUtils.ResponseStatusType.RETRYABLE ->
+ backendExecutionResponse(ExecutionResult.FAIL_RETRY, ex)
+ NetworkUtils.ResponseStatusType.UNAUTHORIZED ->
+ backendExecutionResponse(ExecutionResult.FAIL_UNAUTHORIZED, ex)
+ else ->
+ backendExecutionResponse(ExecutionResult.FAIL_NORETRY, ex)
+ }
+ // The caller retries an abandoned merge, so this failure is not the outcome.
+ if (mergeIntoOnesignalId != null && shouldAbandonMerge(response)) {
+ Logging.debug("LoginUserOperationExecutor merge attempt failed: HTTP ${ex.statusCode}")
+ if (responseType == NetworkUtils.ResponseStatusType.CONFLICT) {
+ // Hardcode user-1. The 409 line above reads like a failure to the app.
+ Logging.debug(
+ "LoginUserOperationExecutor now handling 409 response with \"code\": \"user-1\" by switching to user with \"external_id\": \"${createUserOperation.externalId}\"",
+ )
+ }
+ } else {
+ Logging.error("LoginUserOperationExecutor.createUser failed: HTTP ${ex.statusCode}")
}
+ return response
}
}
@@ -469,6 +481,37 @@ internal class LoginUserOperationExecutor(
return op.existingOnesignalId == null || alias == null
}
+ // A profile login sends the anonymous user's ID with the new external ID, so Create User attaches
+ // the external ID to that user instead of creating a new one, like the SetAlias path does.
+ private fun anonymousUserToMerge(op: LoginUserOperation, alias: String?): String? {
+ if (!op.hasProfileFields() || _identityVerificationService.ivBehaviorActive || alias == null) return null
+ return op.existingOnesignalId?.takeUnless { IDManager.isLocalId(it) }
+ }
+
+ // Drop the anonymous id only when it can be why Create User failed.
+ // A 400 is the payload, so a second request would fail the same way.
+ private fun shouldAbandonMerge(response: ExecutionResponse): Boolean {
+ if (response.result != ExecutionResult.FAIL_NORETRY) return false
+ val status = response.httpStatusCode?.let { NetworkUtils.getResponseStatusType(it) }
+ return status == NetworkUtils.ResponseStatusType.MISSING ||
+ (status == NetworkUtils.ResponseStatusType.CONFLICT && onesignalIdConflict(response.httpResponse) != false)
+ }
+
+ /** False when a parsed error does not name onesignal_id. Null when the body has none. */
+ private fun onesignalIdConflict(body: String?): Boolean? =
+ OneSignalError.fromBackendResponse(HTTP_CONFLICT, body)
+ .details
+ .filter { it.backendCode != null || conflictingAliases(it).isNotEmpty() }
+ .takeIf { it.isNotEmpty() }
+ ?.any { namesMergedUser(it) }
+
+ // user-1 is any alias clash. Retry only when conflicting_aliases names onesignal_id.
+ private fun namesMergedUser(detail: OneSignalError.Detail): Boolean =
+ conflictingAliases(detail).containsKey(IdentityConstants.ONESIGNAL_ID)
+
+ private fun conflictingAliases(detail: OneSignalError.Detail): Map<*, *> =
+ detail.meta?.get(CONFLICTING_ALIASES) as? Map<*, *> ?: emptyMap()
+
private fun backendExecutionResponse(
result: ExecutionResult,
ex: BackendException,
@@ -481,6 +524,8 @@ internal class LoginUserOperationExecutor(
companion object {
const val LOGIN_USER = "login-user"
+ private const val HTTP_CONFLICT = 409
+ private const val CONFLICTING_ALIASES = "conflicting_aliases"
}
}
diff --git a/OneSignalSDK/onesignal/core/src/test/java/com/onesignal/user/internal/operations/LoginUserOperationExecutorTests.kt b/OneSignalSDK/onesignal/core/src/test/java/com/onesignal/user/internal/operations/LoginUserOperationExecutorTests.kt
index 63bf4ed713..3805b5e8fd 100644
--- a/OneSignalSDK/onesignal/core/src/test/java/com/onesignal/user/internal/operations/LoginUserOperationExecutorTests.kt
+++ b/OneSignalSDK/onesignal/core/src/test/java/com/onesignal/user/internal/operations/LoginUserOperationExecutorTests.kt
@@ -6,6 +6,7 @@ import br.com.colman.kotest.android.extensions.robolectric.RobolectricTest
import com.onesignal.OneSignalUserProfile
import com.onesignal.common.AndroidUtils
import com.onesignal.common.DeviceUtils
+import com.onesignal.common.IDManager
import com.onesignal.common.OneSignalUtils
import com.onesignal.common.PIIHasher
import com.onesignal.common.RootToolsInternalMethods
@@ -1650,6 +1651,160 @@ class LoginUserOperationExecutorTests : FunSpec({
coVerify(exactly = 0) { identityExecutor.execute(any()) }
}
+ test("composite login from an anonymous user sends its onesignal_id so the user is merged") {
+ val mockUserBackendService = mockk()
+ coEvery { mockUserBackendService.createUser(any(), any(), any(), any()) } returns
+ CreateUserResponse(mapOf(IdentityConstants.ONESIGNAL_ID to "existing-osid"), PropertiesObject(), listOf())
+
+ val response =
+ profileExecutor(mockUserBackendService).execute(
+ listOf(LoginUserOperation(appId, localOneSignalId, "externalId", "existing-osid", OneSignalUserProfile(tags = mapOf("plan" to "pro")))),
+ )
+
+ response.result shouldBe ExecutionResult.SUCCESS
+ response.idTranslations shouldBe mapOf(localOneSignalId to "existing-osid")
+ coVerify(exactly = 1) {
+ mockUserBackendService.createUser(
+ appId,
+ mapOf(IdentityConstants.EXTERNAL_ID to "externalId", IdentityConstants.ONESIGNAL_ID to "existing-osid"),
+ any(),
+ any(),
+ )
+ }
+ }
+
+ test("composite login retries without onesignal_id when the external ID belongs to another user") {
+ val mockUserBackendService = mockk()
+ val mergeIdentities = mapOf(IdentityConstants.EXTERNAL_ID to "externalId", IdentityConstants.ONESIGNAL_ID to "existing-osid")
+ val plainIdentities = mapOf(IdentityConstants.EXTERNAL_ID to "externalId")
+ coEvery { mockUserBackendService.createUser(appId, mergeIdentities, any(), any()) } throws
+ BackendException(
+ 409,
+ """{"errors":[{"code":"user-1","meta":{"conflicting_aliases":{"external_id":"externalId","onesignal_id":"existing-osid"}}}]}""",
+ )
+ coEvery { mockUserBackendService.createUser(appId, plainIdentities, any(), any()) } returns
+ CreateUserResponse(mapOf(IdentityConstants.ONESIGNAL_ID to remoteOneSignalId), PropertiesObject(), listOf())
+
+ val response =
+ profileExecutor(mockUserBackendService).execute(
+ listOf(LoginUserOperation(appId, localOneSignalId, "externalId", "existing-osid", OneSignalUserProfile(tags = mapOf("plan" to "pro")))),
+ )
+
+ response.result shouldBe ExecutionResult.SUCCESS
+ response.idTranslations shouldBe mapOf(localOneSignalId to remoteOneSignalId)
+ coVerify(exactly = 1) { mockUserBackendService.createUser(appId, mergeIdentities, any(), any()) }
+ coVerify(exactly = 1) { mockUserBackendService.createUser(appId, plainIdentities, any(), any()) }
+ }
+
+ test("composite login retries without onesignal_id when the merge attempt is not a conflict") {
+ val mockUserBackendService = mockk()
+ val mergeIdentities = mapOf(IdentityConstants.EXTERNAL_ID to "externalId", IdentityConstants.ONESIGNAL_ID to "existing-osid")
+ val plainIdentities = mapOf(IdentityConstants.EXTERNAL_ID to "externalId")
+ coEvery { mockUserBackendService.createUser(appId, mergeIdentities, any(), any()) } throws
+ BackendException(404, """{"errors":[{"code":"user-0","title":"User not found"}]}""")
+ coEvery { mockUserBackendService.createUser(appId, plainIdentities, any(), any()) } returns
+ CreateUserResponse(mapOf(IdentityConstants.ONESIGNAL_ID to remoteOneSignalId), PropertiesObject(), listOf())
+
+ val response =
+ profileExecutor(mockUserBackendService).execute(
+ listOf(LoginUserOperation(appId, localOneSignalId, "externalId", "existing-osid", OneSignalUserProfile(tags = mapOf("plan" to "pro")))),
+ )
+
+ response.result shouldBe ExecutionResult.SUCCESS
+ response.idTranslations shouldBe mapOf(localOneSignalId to remoteOneSignalId)
+ coVerify(exactly = 1) { mockUserBackendService.createUser(appId, mergeIdentities, any(), any()) }
+ coVerify(exactly = 1) { mockUserBackendService.createUser(appId, plainIdentities, any(), any()) }
+ }
+
+ test("composite login does not retry a merge when the 409 is an alias conflict") {
+ val mockUserBackendService = mockk()
+ coEvery { mockUserBackendService.createUser(any(), any(), any(), any()) } throws
+ BackendException(
+ 409,
+ """{"errors":[{"code":"user-1","meta":{"conflicting_aliases":{"facebook":"bob","external_id":"externalId"}}}]}""",
+ )
+
+ val response =
+ profileExecutor(mockUserBackendService).execute(
+ listOf(LoginUserOperation(appId, localOneSignalId, "externalId", "existing-osid", OneSignalUserProfile(aliases = mapOf("facebook" to "bob")))),
+ )
+
+ response.result shouldBe ExecutionResult.FAIL_NORETRY
+ response.httpStatusCode shouldBe 409
+ coVerify(exactly = 1) { mockUserBackendService.createUser(any(), any(), any(), any()) }
+ }
+
+ test("composite login does not retry a merge when the payload is invalid") {
+ val mockUserBackendService = mockk()
+ coEvery { mockUserBackendService.createUser(any(), any(), any(), any()) } throws BackendException(400, "INVALID EMAIL")
+
+ val response =
+ profileExecutor(mockUserBackendService).execute(
+ listOf(
+ LoginUserOperation(
+ appId,
+ localOneSignalId,
+ "externalId",
+ "existing-osid",
+ OneSignalUserProfile(email = "not-an-email"),
+ ),
+ ),
+ )
+
+ response.result shouldBe ExecutionResult.FAIL_NORETRY
+ response.httpStatusCode shouldBe 400
+ coVerify(exactly = 1) { mockUserBackendService.createUser(any(), any(), any(), any()) }
+ }
+
+ test("composite login does not retry a merge when the 409 is user-2") {
+ val mockUserBackendService = mockk()
+ coEvery { mockUserBackendService.createUser(any(), any(), any(), any()) } throws
+ BackendException(409, """{"errors":[{"code":"user-2","title":"One or more Aliases claimed by another User"}]}""")
+
+ val response =
+ profileExecutor(mockUserBackendService).execute(
+ listOf(LoginUserOperation(appId, localOneSignalId, "externalId", "existing-osid", OneSignalUserProfile(tags = mapOf("plan" to "pro")))),
+ )
+
+ response.result shouldBe ExecutionResult.FAIL_NORETRY
+ response.httpStatusCode shouldBe 409
+ coVerify(exactly = 1) { mockUserBackendService.createUser(any(), any(), any(), any()) }
+ }
+
+ test("composite login retries without onesignal_id when the 409 body cannot be read") {
+ val mockUserBackendService = mockk()
+ val mergeIdentities = mapOf(IdentityConstants.EXTERNAL_ID to "externalId", IdentityConstants.ONESIGNAL_ID to "existing-osid")
+ val plainIdentities = mapOf(IdentityConstants.EXTERNAL_ID to "externalId")
+ coEvery { mockUserBackendService.createUser(appId, mergeIdentities, any(), any()) } throws BackendException(409, "CONFLICT")
+ coEvery { mockUserBackendService.createUser(appId, plainIdentities, any(), any()) } returns
+ CreateUserResponse(mapOf(IdentityConstants.ONESIGNAL_ID to remoteOneSignalId), PropertiesObject(), listOf())
+
+ val response =
+ profileExecutor(mockUserBackendService).execute(
+ listOf(LoginUserOperation(appId, localOneSignalId, "externalId", "existing-osid", OneSignalUserProfile(tags = mapOf("plan" to "pro")))),
+ )
+
+ response.result shouldBe ExecutionResult.SUCCESS
+ coVerify(exactly = 1) { mockUserBackendService.createUser(appId, mergeIdentities, any(), any()) }
+ coVerify(exactly = 1) { mockUserBackendService.createUser(appId, plainIdentities, any(), any()) }
+ }
+
+ test("composite login does not merge when the anonymous user is still local, or under IV") {
+ for ((existingId, ivActive) in listOf(IDManager.createLocalId() to false, "existing-osid" to true)) {
+ val mockUserBackendService = mockk()
+ coEvery { mockUserBackendService.createUser(any(), any(), any(), any(), any()) } returns
+ CreateUserResponse(mapOf(IdentityConstants.ONESIGNAL_ID to remoteOneSignalId), PropertiesObject(), listOf())
+
+ profileExecutor(mockUserBackendService, ivActive = ivActive).execute(
+ listOf(LoginUserOperation(appId, localOneSignalId, "externalId", existingId, OneSignalUserProfile(tags = mapOf("plan" to "pro")))),
+ )
+
+ coVerify(exactly = 1) {
+ mockUserBackendService.createUser(appId, mapOf(IdentityConstants.EXTERNAL_ID to "externalId"), any(), any(), any())
+ }
+ }
+ }
+
test("identity-only login still associates via SetAlias when existingOnesignalId is set") {
val mockUserBackendService = mockk()
val identityExecutor = mockk()