Skip to content
Merged
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
6 changes: 3 additions & 3 deletions OneSignalSDK/detekt/detekt-baseline-core.xml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<ID>ComplexMethod:ConfigModelStoreListener.kt$ConfigModelStoreListener$private fun fetchParams()</ID>
<ID>ComplexMethod:HttpClient.kt$HttpClient$private suspend fun makeRequestIODispatcher( url: String, method: String?, jsonBody: JSONObject?, timeout: Int, headers: OptionalHeaders?, ): HttpResponse</ID>
<ID>ComplexMethod:IdentityOperationExecutor.kt$IdentityOperationExecutor$override suspend fun execute(operations: List&lt;Operation>): ExecutionResponse</ID>
<ID>ComplexMethod:LoginUserOperationExecutor.kt$LoginUserOperationExecutor$private suspend fun createUser( createUserOperation: LoginUserOperation, operations: List&lt;Operation>, ): ExecutionResponse</ID>
<ID>ComplexMethod:LoginUserOperationExecutor.kt$LoginUserOperationExecutor$private suspend fun createUser( createUserOperation: LoginUserOperation, operations: List&lt;Operation>, mergeIntoOnesignalId: String? = null, ): ExecutionResponse</ID>
<ID>ComplexMethod:OSDatabase.kt$OSDatabase$@Synchronized private fun internalOnUpgrade( db: SQLiteDatabase, oldVersion: Int, newVersion: Int, )</ID>
<ID>ComplexMethod:OperationModelStore.kt$OperationModelStore$override fun create(jsonObject: JSONObject?): Operation?</ID>
<ID>ComplexMethod:OperationRepo.kt$OperationRepo$internal suspend fun executeOperations(ops: List&lt;OperationQueueItem>)</ID>
Expand Down Expand Up @@ -194,7 +194,7 @@
<ID>LongMethod:FeatureFlagsBackendService.kt$FeatureFlagsBackendService$override suspend fun fetchRemoteFeatureFlags(appId: String): RemoteFeatureFlagsFetchOutcome</ID>
<ID>LongMethod:HttpClient.kt$HttpClient$private suspend fun makeRequestIODispatcher( url: String, method: String?, jsonBody: JSONObject?, timeout: Int, headers: OptionalHeaders?, ): HttpResponse</ID>
<ID>LongMethod:IdentityOperationExecutor.kt$IdentityOperationExecutor$override suspend fun execute(operations: List&lt;Operation>): ExecutionResponse</ID>
<ID>LongMethod:LoginUserOperationExecutor.kt$LoginUserOperationExecutor$private suspend fun createUser( createUserOperation: LoginUserOperation, operations: List&lt;Operation>, ): ExecutionResponse</ID>
<ID>LongMethod:LoginUserOperationExecutor.kt$LoginUserOperationExecutor$private suspend fun createUser( createUserOperation: LoginUserOperation, operations: List&lt;Operation>, mergeIntoOnesignalId: String? = null, ): ExecutionResponse</ID>
<ID>LongMethod:LoginUserOperationExecutor.kt$LoginUserOperationExecutor$private suspend fun loginUser( loginUserOp: LoginUserOperation, operations: List&lt;Operation>, ): ExecutionResponse</ID>
<ID>LongMethod:OperationRepo.kt$OperationRepo$internal suspend fun executeOperations(ops: List&lt;OperationQueueItem>)</ID>
<ID>LongMethod:OperationRepo.kt$OperationRepo$private fun internalEnqueue( queueItem: OperationQueueItem, flush: Boolean, addToStore: Boolean, index: Int? = null, )</ID>
Expand Down Expand Up @@ -293,7 +293,7 @@
<ID>NestedBlockDepth:IdentityOperationExecutor.kt$IdentityOperationExecutor$override suspend fun execute(operations: List&lt;Operation>): ExecutionResponse</ID>
<ID>NestedBlockDepth:InfluenceManager.kt$InfluenceManager$private fun attemptSessionUpgrade( entryAction: AppEntryAction, directId: String? = null, )</ID>
<ID>NestedBlockDepth:JSONUtils.kt$JSONUtils$fun compareJSONArrays( jsonArray1: JSONArray?, jsonArray2: JSONArray?, ): Boolean</ID>
<ID>NestedBlockDepth:LoginUserOperationExecutor.kt$LoginUserOperationExecutor$private suspend fun createUser( createUserOperation: LoginUserOperation, operations: List&lt;Operation>, ): ExecutionResponse</ID>
<ID>NestedBlockDepth:LoginUserOperationExecutor.kt$LoginUserOperationExecutor$private suspend fun createUser( createUserOperation: LoginUserOperation, operations: List&lt;Operation>, mergeIntoOnesignalId: String? = null, ): ExecutionResponse</ID>
<ID>NestedBlockDepth:RefreshUserOperationExecutor.kt$RefreshUserOperationExecutor$private suspend fun getUser(op: RefreshUserOperation): ExecutionResponse</ID>
<ID>NestedBlockDepth:ServiceRegistration.kt$ServiceRegistrationReflection$override fun resolve(provider: IServiceProvider): Any?</ID>
<ID>NestedBlockDepth:ServiceRegistration.kt$ServiceRegistrationReflection$private fun doesHaveAllParameters( constructor: Constructor&lt;*>, provider: IServiceProvider, ): Boolean</ID>
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -179,8 +177,10 @@ internal class LoginUserOperationExecutor(
private suspend fun createUser(
createUserOperation: LoginUserOperation,
operations: List<Operation>,
mergeIntoOnesignalId: String? = null,
): ExecutionResponse {
val identities = mutableMapOf<String, String>()
mergeIntoOnesignalId?.let { identities[IdentityConstants.ONESIGNAL_ID] = it }
var subscriptions = mapOf<String, SubscriptionObject>()
val properties =
PropertiesObject(
Expand Down Expand Up @@ -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}")
Comment thread
abdulraqeeb33 marked this conversation as resolved.
Resolved
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
}
}

Expand Down Expand Up @@ -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<String, Any?>()

private fun backendExecutionResponse(
result: ExecutionResult,
ex: BackendException,
Expand All @@ -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"
Comment thread
abdulraqeeb33 marked this conversation as resolved.
Resolved
}
}

Expand Down
Loading
Loading