package org.thoughtcrime.securesms.messages import android.app.Application import android.app.Notification import android.app.Service import android.content.Context import android.content.Intent import android.os.IBinder import androidx.annotation.VisibleForTesting import androidx.core.app.NotificationCompat import io.reactivex.rxjava3.disposables.Disposable import io.reactivex.rxjava3.kotlin.subscribeBy import io.reactivex.rxjava3.schedulers.Schedulers import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import org.signal.core.models.ServiceId import org.signal.core.util.AppForegroundObserver import org.signal.core.util.SafeForegroundService import org.signal.core.util.SleepTimer import org.signal.core.util.UptimeSleepTimer import org.signal.core.util.concurrent.SignalExecutors import org.signal.core.util.logging.Log import org.signal.network.config.ProxyConfig import org.signal.network.config.SignalServiceConfiguration import org.signal.storage.keyvalue.isDecisionPending import org.signal.storageservice.storage.protos.groups.local.DecryptedGroup import org.thoughtcrime.securesms.BuildConfig import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.clockskew.ClockSkewDetector import org.thoughtcrime.securesms.crypto.ReentrantSessionLock import org.thoughtcrime.securesms.database.SignalDatabase import org.thoughtcrime.securesms.dependencies.AppDependencies import org.thoughtcrime.securesms.groups.GroupsV2ProcessingLock import org.thoughtcrime.securesms.groups.v2.processing.GroupsV2StateProcessor import org.thoughtcrime.securesms.jobmanager.Job import org.thoughtcrime.securesms.jobmanager.impl.BackoffUtil import org.thoughtcrime.securesms.jobs.PushProcessMessageErrorJob import org.thoughtcrime.securesms.jobs.PushProcessMessageJob import org.thoughtcrime.securesms.jobs.RequestGroupV2InfoJob import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.messages.MessageDecryptor.FollowUpOperation import org.thoughtcrime.securesms.messages.protocol.BufferedProtocolStore import org.thoughtcrime.securesms.net.ConnectivityState import org.thoughtcrime.securesms.net.InternetConnectivityMonitor import org.thoughtcrime.securesms.notifications.NotificationChannels import org.thoughtcrime.securesms.notifications.NotificationIds import org.thoughtcrime.securesms.recipients.RecipientIds import org.thoughtcrime.securesms.util.AlarmSleepTimer import org.thoughtcrime.securesms.util.Environment import org.thoughtcrime.securesms.util.SignalLocalMetrics import org.thoughtcrime.securesms.util.SignalTrace import org.thoughtcrime.securesms.util.asChain import org.whispersystems.signalservice.api.messages.EnvelopeResponse import org.whispersystems.signalservice.api.websocket.SignalWebSocket import org.whispersystems.signalservice.api.websocket.WebSocketConnectionState import org.whispersystems.signalservice.api.websocket.WebSocketUnavailableException import org.whispersystems.signalservice.internal.push.Envelope import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicReference import java.util.concurrent.locks.ReentrantLock import kotlin.concurrent.withLock import kotlin.math.round import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds /** * The application-level manager of our incoming message processing. * * This class is responsible for keeping the authenticated websocket open based on the app's state for incoming messages and * observing new inbound messages received over the websocket. */ class IncomingMessageObserver( private val context: Application, private val authWebSocket: SignalWebSocket.AuthenticatedWebSocket, private val unauthWebSocket: SignalWebSocket.UnauthenticatedWebSocket ) { companion object { private val TAG = Log.tag(IncomingMessageObserver::class.java) private const val WEB_SOCKET_KEEP_ALIVE_TOKEN = "MessageRetrieval" private val ALL_GROUPS_LOCK_TIMEOUT = 30.seconds /** How long we wait for the websocket to time out before we try to connect again. */ private val websocketReadTimeout: Long get() = if (censored) 30.seconds.inWholeMilliseconds else 1.minutes.inWholeMilliseconds /** How long the websocket is allowed to keep running after the user backgrounds the app. Higher numbers allow us to rely on FCM less. */ private val maxBackgroundTime: Long get() = if (censored) 10.seconds.inWholeMilliseconds else 2.minutes.inWholeMilliseconds private val INSTANCE_COUNT = AtomicInteger(0) private val censored: Boolean get() = AppDependencies.signalServiceNetworkAccess.isCensored() private val networkConfiguration: SignalServiceConfiguration get() = AppDependencies.signalServiceNetworkAccess.getConfiguration() /** * Stops the foreground service for websocket users. */ @JvmStatic fun stopForegroundService(context: Context) { SafeForegroundService.stop(context, ForegroundService::class.java) } } private val decryptionDrainedListeners: MutableList = CopyOnWriteArrayList() private val connectionLock = ReentrantLock() private val connectionConditionsChanged = connectionLock.newCondition() @Volatile private var connectionConditionsVersion: Long = 0 /** Tracks Internet connection as reported by [InternetConnectivityMonitor]. Starts fail-open (assume online) until the first report. */ @Volatile private var internetConnection: ConnectivityState = ConnectivityState.MONITORING_UNAVAILABLE private val internetConnectivityMonitor = InternetConnectivityMonitor( context = context, onConnectivityUpdated = { state -> internetConnection = state if (state.isAssumedOnline) { // Staying online through a transport swap only resets backoff; we rely on the OS to tear down sockets on the interface that went away. AppDependencies.libsignalNetwork.onNetworkChange() AppDependencies.signalServiceNetworkAccess.onNetworkChange() } else { Log.w(TAG, "Lost network connection. Resetting the drained state.") decryptionDrained = false authWebSocket.disconnect() // TODO [no-more-rest] Move the connection listener to a neutral location so this isn't passed in unauthWebSocket.disconnect() } notifyConnectionConditionsChanged() }, onProxyChanged = { // Building the network seeds networkProxyState, so its placeholder can't read as a change. AppDependencies.libsignalNetwork val proxyConfig = ProxyConfig.resolve(networkConfiguration, BuildConfig.SIGNAL_URL) if (AppDependencies.networkProxyState.currentConfig != proxyConfig) { Log.i(TAG, "Proxy config changed, resetting network...") AppDependencies.resetNetwork() AppDependencies.startNetwork() } } ) private val messageContentProcessor = MessageContentProcessor.create(context) private val appState = AtomicReference(AppState(false, System.currentTimeMillis())) private var webSocketStateDisposable = Disposable.disposed() private val clockSkewScope = CoroutineScope(Dispatchers.Default) @Volatile private var terminated = false @Volatile var decryptionDrained = false private set private val appForegroundListener = object : AppForegroundObserver.Listener { override fun onForeground() { SignalExecutors.BOUNDED.execute { onAppForegrounded() } } override fun onBackground() { SignalExecutors.BOUNDED.execute { onAppBackgrounded() } } } private val keepAliveChangeListener: () -> Unit = { SignalExecutors.BOUNDED.execute { notifyConnectionConditionsChanged() } } init { if (INSTANCE_COUNT.incrementAndGet() != 1) { throw AssertionError("Multiple observers!") } MessageRetrievalThread().start() val registered = SignalStore.account.isRegistered && !SignalStore.account.isUnauthorizedReceived if (registered && SignalStore.settings.shouldStayConnectedInBackground()) { SignalExecutors.UNBOUNDED.execute { if (!SafeForegroundService.start(context, ForegroundService::class.java)) { Log.w(TAG, "Unable to start foreground service for websocket!") } } } AppForegroundObserver.addListener(appForegroundListener) internetConnectivityMonitor.register() webSocketStateDisposable = authWebSocket .state .observeOn(Schedulers.computation()) .subscribeBy { if (it == WebSocketConnectionState.CONNECTED) { notifyConnectionConditionsChanged() } } authWebSocket.addKeepAliveChangeListener(keepAliveChangeListener) clockSkewScope.launch { ClockSkewDetector.detected.collect { detected -> if (detected) { Log.w(TAG, "Clock skew detected. Disconnecting.") authWebSocket.disconnect() } notifyConnectionConditionsChanged() } } } fun notifyRegistrationStateChanged() { notifyConnectionConditionsChanged() } fun notifyRestoreDecisionMade() { Log.i(TAG, "Restore decision made, can restart network and process messages") AppDependencies.resetNetwork() } fun addDecryptionDrainedListener(listener: Runnable) { decryptionDrainedListeners.add(listener) if (decryptionDrained) { listener.run() } } fun removeDecryptionDrainedListener(listener: Runnable) { decryptionDrainedListeners.remove(listener) } private fun onAppForegrounded() { appState.updateAndGet { it.copy(isForeground = true) } ClockSkewDetector.recheck() BackgroundService.start(context) notifyConnectionConditionsChanged() } private fun onAppBackgrounded() { appState.updateAndGet { it.copy(isForeground = false, lastInteractionTime = System.currentTimeMillis()) } ClockSkewDetector.recheck() notifyConnectionConditionsChanged() } private fun isConnectionNecessary(): Boolean { val appStateSnapshot = appState.get() val isForeground = appStateSnapshot.isForeground val lastInteractionTime = appStateSnapshot.lastInteractionTime val timeIdle = if (isForeground) 0 else System.currentTimeMillis() - lastInteractionTime val registered = SignalStore.account.isRegistered val unauthorizedReceived = SignalStore.account.isUnauthorizedReceived val fcmEnabled = SignalStore.account.fcmEnabled val hasNetwork = internetConnection.isAssumedOnline val hasProxy = SignalStore.proxy.isProxyEnabled val stayConnected = SignalStore.settings.shouldStayConnectedInBackground() val websocketAlreadyOpen = isConnectionAvailable() val clockSkewDetected = ClockSkewDetector.isDetected val clockSkew = ClockSkewDetector.skew val lastInteractionString = if (isForeground) "N/A" else timeIdle.toString() + " ms (" + (if (timeIdle < maxBackgroundTime) "within limit" else "over limit") + ")" val conclusion = registered && !unauthorizedReceived && !clockSkewDetected && (isForeground || timeIdle < maxBackgroundTime || stayConnected) && hasNetwork val needsConnectionString = if (conclusion) "Needs Connection" else "Does Not Need Connection" Log.d( TAG, "[$needsConnectionString] Network: $hasNetwork, Foreground: $isForeground, Time Since Last Interaction: $lastInteractionString, FCM: $fcmEnabled, WS Open or Keep-alives: $websocketAlreadyOpen, Registered: $registered, Unauthorized: $unauthorizedReceived, Proxy: $hasProxy, Stay connected: $stayConnected, Clock skew: $clockSkewDetected ($clockSkew)" ) return conclusion } private fun isConnectionAvailable(): Boolean { val hasNetwork = internetConnection.isAssumedOnline return !SignalStore.account.isUnauthorizedReceived && SignalStore.account.isRegistered && (authWebSocket.stateSnapshot == WebSocketConnectionState.CONNECTED || (authWebSocket.hasKeepAliveTokens() && hasNetwork)) } /** Conditions are evaluated outside of [connectionLock] so notifiers never block on them. We only park if nothing signaled since the version we evaluated against. */ private fun waitForConnectionNecessary() { try { var observedVersion = connectionConditionsVersion while (!terminated) { if (!ClockSkewDetector.isDetected && (isConnectionNecessary() || isConnectionAvailable())) { return } connectionLock.withLock { if (!terminated && connectionConditionsVersion == observedVersion) { connectionConditionsChanged.await() } observedVersion = connectionConditionsVersion } } } catch (e: InterruptedException) { throw AssertionError(e) } } private fun notifyConnectionConditionsChanged() { connectionLock.withLock { connectionConditionsVersion++ connectionConditionsChanged.signalAll() } } fun terminate() { Log.w(TAG, "Termination! ${this.hashCode()}", Throwable()) INSTANCE_COUNT.decrementAndGet() AppForegroundObserver.removeListener(appForegroundListener) authWebSocket.removeKeepAliveChangeListener(keepAliveChangeListener) internetConnectivityMonitor.unregister() webSocketStateDisposable.dispose() clockSkewScope.cancel() terminated = true authWebSocket.removeKeepAliveToken(WEB_SOCKET_KEEP_ALIVE_TOKEN) authWebSocket.disconnect() notifyConnectionConditionsChanged() } @VisibleForTesting fun processEnvelope(bufferedProtocolStore: BufferedProtocolStore, envelope: Envelope, serverDeliveredTimestamp: Long, batchCache: BatchCache): ProcessingResult? { return when (envelope.type) { Envelope.Type.SERVER_DELIVERY_RECEIPT -> { processReceipt(envelope) null } Envelope.Type.PREKEY_MESSAGE, Envelope.Type.DOUBLE_RATCHET, Envelope.Type.UNIDENTIFIED_SENDER, Envelope.Type.PLAINTEXT_CONTENT -> { SignalTrace.beginSection("IncomingMessageObserver#processMessage") val result = processMessage(bufferedProtocolStore, envelope, serverDeliveredTimestamp, batchCache) SignalTrace.endSection() result } else -> { Log.w(TAG, "Received envelope of unknown type: " + envelope.type) null } } } private fun processMessage(bufferedProtocolStore: BufferedProtocolStore, envelope: Envelope, serverDeliveredTimestamp: Long, batchCache: BatchCache): ProcessingResult { val localReceiveMetric = SignalLocalMetrics.MessageReceive.start() SignalTrace.beginSection("IncomingMessageObserver#decryptMessage") val result = MessageDecryptor.decrypt(context, bufferedProtocolStore, envelope, serverDeliveredTimestamp) SignalTrace.endSection() localReceiveMetric.onEnvelopeDecrypted() var isNetworkResetRequired = false SignalLocalMetrics.MessageLatency.onMessageReceived(envelope.serverTimestamp!!, serverDeliveredTimestamp, envelope.urgent!!) when (result) { is MessageDecryptor.Result.Success -> { val job = PushProcessMessageJob.processOrDefer(messageContentProcessor, result, localReceiveMetric, batchCache) isNetworkResetRequired = isNetworkResetRequired(result, bufferedProtocolStore.pni) if (job != null) { return ProcessingResult( followUpOperations = result.followUpOperations + FollowUpOperation { job.asChain() }, isNetworkResetRequired = isNetworkResetRequired ) } } is MessageDecryptor.Result.Error -> { return ProcessingResult( result.followUpOperations + FollowUpOperation { val jobs = mutableListOf() if (result.errorMetadata.groupMasterKey != null) { val groupId = result.errorMetadata.groupId!! if (!SignalDatabase.groups.getGroup(groupId).isPresent) { Log.w(TAG, "Decryption error in group, but group not found. Creating placeholder for groupId: $groupId") SignalDatabase.groups.create( groupMasterKey = result.errorMetadata.groupMasterKey!!, groupState = DecryptedGroup(revision = GroupsV2StateProcessor.RESTORE_PLACEHOLDER_REVISION), groupSendEndorsements = null ) jobs += RequestGroupV2InfoJob(groupId) } } jobs += PushProcessMessageErrorJob( result.toMessageState(), result.errorMetadata.toExceptionMetadata(), result.envelope.clientTimestamp!! ) AppDependencies.jobManager.startChain(jobs) } ) } is MessageDecryptor.Result.Ignore -> { // No action needed } else -> { throw AssertionError("Unexpected result! ${result.javaClass.simpleName}") } } return ProcessingResult( followUpOperations = result.followUpOperations, isNetworkResetRequired = isNetworkResetRequired ) } /** * True iff this envelope's PniChangeNumber sync actually changed our PNI within this batch. * Comparing the batch-start PNI against the current value makes the check idempotent — a * redelivered envelope finds the PNI already applied and won't re-trigger a websocket reset. */ private fun isNetworkResetRequired(result: MessageDecryptor.Result.Success, pniAtBatchStart: ServiceId.PNI?): Boolean { return result.content.syncMessage?.pniChangeNumber != null && SignalStore.account.pni != pniAtBatchStart } private fun processReceipt(envelope: Envelope) { val serviceId = ServiceId.parseOrNull(envelope.sourceServiceId, envelope.sourceServiceIdBinary) if (serviceId == null) { Log.w(TAG, "Invalid envelope sourceServiceId!") return } val senderId = RecipientIds.from(serviceId) Log.i(TAG, "Received server receipt. Sender: $senderId, Device: ${envelope.sourceDeviceId}, Timestamp: ${envelope.clientTimestamp}") SignalDatabase.messages.incrementDeliveryReceiptCount(envelope.clientTimestamp!!, senderId, System.currentTimeMillis()) SignalDatabase.messageLog.deleteEntryForRecipient(envelope.clientTimestamp!!, senderId, envelope.sourceDeviceId!!) } private fun MessageDecryptor.Result.toMessageState(): MessageState { return when (this) { is MessageDecryptor.Result.DecryptionError -> MessageState.DECRYPTION_ERROR is MessageDecryptor.Result.Ignore -> MessageState.NOOP is MessageDecryptor.Result.InvalidVersion -> MessageState.INVALID_VERSION is MessageDecryptor.Result.LegacyMessage -> MessageState.LEGACY_MESSAGE is MessageDecryptor.Result.Success -> MessageState.DECRYPTED_OK is MessageDecryptor.Result.UnsupportedDataMessage -> MessageState.UNSUPPORTED_DATA_MESSAGE } } private fun MessageDecryptor.ErrorMetadata.toExceptionMetadata(): ExceptionMetadata { return ExceptionMetadata( this.sender, this.senderDevice, this.groupId ) } private inner class MessageRetrievalThread : Thread("MessageRetrievalService"), Thread.UncaughtExceptionHandler { private var sleepTimer: SleepTimer private val canProcessMessages: Boolean init { Log.i(TAG, "Initializing! (${this.hashCode()})") uncaughtExceptionHandler = this sleepTimer = if (SignalStore.settings.shouldStayConnectedInBackground()) AlarmSleepTimer(context) else UptimeSleepTimer() canProcessMessages = !SignalStore.registration.restoreDecisionState.isDecisionPending } override fun run() { var attempts = 0 while (!terminated) { Log.i(TAG, "Waiting for websocket state change....") if (attempts > 1) { val backoff = BackoffUtil.exponentialBackoff(attempts, TimeUnit.SECONDS.toMillis(30)) Log.w(TAG, "Too many failed connection attempts, attempts: $attempts backing off: $backoff") sleepTimer.sleep(backoff) } waitForConnectionNecessary() if (terminated) { break } Log.i(TAG, "Making websocket connection....") val webSocketDisposable = authWebSocket.state.subscribe { state: WebSocketConnectionState -> Log.d(TAG, "WebSocket State: $state") // Any change to a non-connected state means that we are not drained if (state != WebSocketConnectionState.CONNECTED) { decryptionDrained = false } if (state == WebSocketConnectionState.CONNECTED) { SignalStore.misc.lastWebSocketConnectTime = System.currentTimeMillis() } } try { authWebSocket.connect() var isConnectionNecessary = false while (!terminated && !ClockSkewDetector.isDetected && (isConnectionNecessary().also { isConnectionNecessary = it } || isConnectionAvailable())) { if (isConnectionNecessary) { authWebSocket.registerKeepAliveToken(WEB_SOCKET_KEEP_ALIVE_TOKEN) } else { authWebSocket.removeKeepAliveToken(WEB_SOCKET_KEEP_ALIVE_TOKEN) } try { if (canProcessMessages) { Log.d(TAG, "Reading message...") val hasMore = authWebSocket.readMessageBatch(websocketReadTimeout, 30) { batch -> Log.i(TAG, "Retrieved ${batch.size} envelopes!") val startTime = System.currentTimeMillis() GroupsV2ProcessingLock.acquireAllGroupsProcessingLock(ALL_GROUPS_LOCK_TIMEOUT).use { ReentrantSessionLock.INSTANCE.acquire().use { val batchCommitted = processBatchInTransaction(batch) if (!batchCommitted) { Log.w(TAG, "Batch transaction rolled back, falling back to per-message processing") processMessagesIndividually(batch) } } } val duration = System.currentTimeMillis() - startTime val timePerMessage: Float = duration / batch.size.toFloat() Log.d(TAG, "Decrypted ${batch.size} envelopes in $duration ms (~${round(timePerMessage * 100) / 100} ms per message)") } attempts = 0 SignalLocalMetrics.PushWebsocketFetch.onProcessedBatch() if (!hasMore && !decryptionDrained) { if (Environment.IS_BENCHMARK) { SignalTrace.endSection() } Log.i(TAG, "Decryptions newly-drained.") decryptionDrained = true for (listener in decryptionDrainedListeners.toList()) { listener.run() } } else if (!hasMore) { Log.w(TAG, "Got tombstone, but we thought the network was already drained!") } } else { Log.d(TAG, "Reading and dropping message...") authWebSocket.readMessageBatch(websocketReadTimeout, 30) { batch -> Log.w(TAG, "Retrieved ${batch.size} envelopes but dropping until we can finish backup restore.") } attempts = 0 } } catch (e: WebSocketUnavailableException) { if (ClockSkewDetector.isDetected) { Log.i(TAG, "Pipe unavailable because of clock skew, not reconnecting") } else { Log.i(TAG, "Pipe unexpectedly unavailable, connecting") authWebSocket.connect() } } catch (e: TimeoutException) { Log.w(TAG, "Application level read timeout...") attempts = 0 } } if (!appState.get().isForeground) { BackgroundService.stop(context) } } catch (e: Throwable) { if (ClockSkewDetector.isDetected) { Log.w(TAG, "Websocket torn down because of clock skew. Not counting as a failed attempt.", e) } else { attempts++ Log.w(TAG, e) } } finally { Log.w(TAG, "Disconnecting auth websocket") authWebSocket.disconnect() webSocketDisposable.dispose() decryptionDrained = false } Log.i(TAG, "Looping...") } Log.w(TAG, "Terminated! (${this.hashCode()})") } /** * Attempts to process the entire batch in a single transaction for performance. * * @return true if the transaction committed, false if the batch was rolled back. */ private fun processBatchInTransaction(batch: List): Boolean { val allFollowUpOperations = mutableListOf() val bufferedStore = BufferedProtocolStore.create() val batchCache = ReusedBatchCache() var processedCount = 0 var networkResetRequired = false val committed = SignalDatabase.tryRunInTransaction { for (response in batch) { SignalTrace.beginSection("IncomingMessageObserver#perMessageTransaction") val result = when (response) { is EnvelopeResponse.Parsed -> { processEnvelope(bufferedStore, response.envelope, response.serverDeliveredTimestamp, batchCache) } is EnvelopeResponse.Unparseable -> { Log.w(TAG, "Unparseable envelope. Nothing to process, but we'll still ack it.") null } } bufferedStore.flushToDisk() SignalTrace.endSection() if (result?.followUpOperations?.isNotEmpty() == true) { allFollowUpOperations += result.followUpOperations } processedCount++ if (result?.isNetworkResetRequired == true) { networkResetRequired = true Log.w(TAG, "Self identity changed mid-batch after envelope $processedCount of ${batch.size}. Committing what we have; the remainder will be redelivered to the new connection.") break } } } if (committed) { batchCache.flushAndClear() if (allFollowUpOperations.isNotEmpty()) { Log.d(TAG, "Running ${allFollowUpOperations.size} follow-up operations...") val jobs = allFollowUpOperations.mapNotNull { it.run() } AppDependencies.jobManager.addAllChains(jobs) } for (i in 0 until processedCount) { sendAckSafely(batch[i], i, batch.size) } if (networkResetRequired) { AppDependencies.resetNetwork() AppDependencies.startNetwork() } } return committed } /** * If something prevented us from processing the entire batch in a single transaction, we process each message individually. */ private fun processMessagesIndividually(batch: List) { val bufferedStore = BufferedProtocolStore.create() val batchCache = ReusedBatchCache() for ((index, response) in batch.withIndex()) { SignalTrace.beginSection("IncomingMessageObserver#perMessageTransaction") val results = when (response) { is EnvelopeResponse.Parsed -> SignalDatabase.runInTransaction { val result = processEnvelope(bufferedStore, response.envelope, response.serverDeliveredTimestamp, batchCache) bufferedStore.flushToDisk() result } is EnvelopeResponse.Unparseable -> { Log.w(TAG, "Unparseable envelope. Nothing to process, but we'll still ack it.") null } } SignalTrace.endSection() if (results?.followUpOperations?.isNotEmpty() == true) { val jobs = results.followUpOperations.mapNotNull { it.run() } AppDependencies.jobManager.addAllChains(jobs) } sendAckSafely(response, index, batch.size) if (results?.isNetworkResetRequired == true) { Log.w(TAG, "Self identity changed mid-batch after envelope ${index + 1} of ${batch.size}. Stopping individual processing; the remainder will be redelivered to the new connection.") AppDependencies.resetNetwork() AppDependencies.startNetwork() break } } batchCache.flushAndClear() } /** * Best-effort ack. Failures just mean the server will redeliver — and for a redelivered * PniChangeNumber sync, [isNetworkResetRequired] sees the PNI is already applied and won't * re-trigger a reset, so we don't loop. */ private fun sendAckSafely(response: EnvelopeResponse, index: Int, size: Int) { try { authWebSocket.sendAck(response) } catch (e: Exception) { Log.w(TAG, "Failed to send ack for envelope $index of $size. The server will redeliver.", e) } } override fun uncaughtException(t: Thread, e: Throwable) { Log.w(TAG, "Uncaught exception in message thread!", e) } } /** * Keeps the process alive for websocket users. */ class ForegroundService : SafeForegroundService() { override val tag: String = TAG override val notificationId: Int = NotificationIds.INCOMING_MESSAGE_OBSERVER override fun getForegroundNotification(intent: Intent): Notification { return NotificationCompat.Builder(applicationContext, NotificationChannels.getInstance().BACKGROUND) .setContentTitle(applicationContext.getString(R.string.MessageRetrievalService_signal)) .setContentText(applicationContext.getString(R.string.MessageRetrievalService_background_connection_enabled)) .setPriority(NotificationCompat.PRIORITY_MIN) .setWhen(0) .setSmallIcon(R.drawable.ic_signal_background_connection) .build() } } /** * A service that exists just to encourage the system to keep our process alive a little longer. */ class BackgroundService : Service() { override fun onBind(intent: Intent?): IBinder? = null override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { Log.d(TAG, "Background service started.") return START_STICKY } override fun onDestroy() { Log.d(TAG, "Background service destroyed.") } companion object { fun start(context: Context) { try { context.startService(Intent(context, BackgroundService::class.java)) } catch (e: Exception) { Log.w(TAG, "Failed to start background service.", e) } } fun stop(context: Context) { context.stopService(Intent(context, BackgroundService::class.java)) } } } private data class AppState( val isForeground: Boolean, val lastInteractionTime: Long ) data class ProcessingResult( val followUpOperations: List, val isNetworkResetRequired: Boolean = false ) }