Skip to content

Commit cc4e011

Browse files
authored
Store what the reconnect sync, its retries and channel update responses write in one database transaction each (#7084)
* Run the database reads and writes of the sync retries and channel update responses in one store write each * Remove the messages and store the channel in one store write on truncation and deletion responses
1 parent d4f88b4 commit cc4e011

4 files changed

Lines changed: 336 additions & 42 deletions

File tree

‎stream-chat-android-client/src/main/java/io/getstream/chat/android/client/internal/state/plugin/logic/channel/internal/ChannelUpdateResponseHandler.kt‎

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import io.getstream.chat.android.client.extensions.internal.removeMember
2121
import io.getstream.chat.android.client.internal.state.plugin.logic.internal.LogicRegistry
2222
import io.getstream.chat.android.client.internal.state.plugin.state.global.internal.MutableGlobalState
2323
import io.getstream.chat.android.client.persistance.repository.RepositoryFacade
24+
import io.getstream.chat.android.client.persistance.repository.write
2425
import io.getstream.chat.android.core.utils.date.max
2526
import io.getstream.chat.android.models.Channel
2627
import io.getstream.chat.android.models.ChannelData
@@ -43,8 +44,8 @@ import java.util.Date
4344
* the members it added or removed, counted the same way as `member.added` and `member.removed`, so a member event
4445
* processed before the response is kept and the later event changes nothing.
4546
*
46-
* The stored channel is read, merged and written outside the lock of the event handler, as the event and query paths
47-
* also do: an event batch written in between is replaced until the next event or query.
47+
* The stored channel is read, merged and written in one write of the store, so no event batch is stored in between.
48+
* A truncation or a deletion removes the messages in the same write that stores the channel.
4849
*
4950
* A failure here is logged and never changes the result of the request.
5051
*/
@@ -92,11 +93,13 @@ internal class ChannelUpdateResponseHandler(
9293
* Applies the channel returned by a truncation and removes the messages it removed.
9394
*/
9495
suspend fun onChannelTruncated(channel: Channel) = safely("onChannelTruncated") {
95-
channel.truncatedAt?.let { truncatedAt ->
96-
repos.deleteChannelMessagesBefore(channel.cid, truncatedAt)
97-
activeChannel(channel)?.truncate(truncatedAt)
96+
val truncatedAt = channel.truncatedAt
97+
repos.write {
98+
truncatedAt?.let { repos.deleteChannelMessagesBefore(channel.cid, it) }
99+
saveChannel(channel) { it }
98100
}
99-
applyChannel(channel)
101+
truncatedAt?.let { activeChannel(channel)?.truncate(it) }
102+
applyChannelToState(channel)
100103
}
101104

102105
/**
@@ -105,8 +108,10 @@ internal class ChannelUpdateResponseHandler(
105108
*/
106109
suspend fun onChannelDeleted(channel: Channel) = safely("onChannelDeleted") {
107110
val deletedAt = channel.deletedAt ?: return@safely
108-
repos.deleteChannelMessagesBefore(channel.cid, deletedAt)
109-
repos.setChannelDeletedAt(channel.cid, deletedAt)
111+
repos.write {
112+
repos.deleteChannelMessagesBefore(channel.cid, deletedAt)
113+
repos.setChannelDeletedAt(channel.cid, deletedAt)
114+
}
110115
activeChannel(channel)?.deleteChannel(deletedAt)
111116
refreshChannelLists(channel.cid)
112117
}
@@ -143,6 +148,10 @@ internal class ChannelUpdateResponseHandler(
143148

144149
private suspend fun applyChannel(channel: Channel, addedMembers: List<Member> = emptyList()) {
145150
saveChannel(channel) { stored -> addedMembers.fold(stored) { acc, member -> acc.addMember(member) } }
151+
applyChannelToState(channel, addedMembers)
152+
}
153+
154+
private fun applyChannelToState(channel: Channel, addedMembers: List<Member> = emptyList()) {
146155
val channelLogic = activeChannel(channel) ?: return
147156
val stateUpdatedAt = channelLogic.messagesUpdateLogic.channelState().channelData.value.updatedAt
148157
if (stateUpdatedAt.isAfter(channel.updatedAt)) {
@@ -157,12 +166,12 @@ internal class ChannelUpdateResponseHandler(
157166
/**
158167
* Stores the [channel] merged into the stored one, keeping the stored members, then applies [updateMembers].
159168
*/
160-
private suspend fun saveChannel(channel: Channel, updateMembers: (Channel) -> Channel) {
169+
private suspend fun saveChannel(channel: Channel, updateMembers: (Channel) -> Channel) = repos.write {
161170
// A channel not stored yet is left to the next query: the response has no messages or reads.
162-
val stored = repos.selectChannel(channel.cid) ?: return
171+
val stored = repos.selectChannel(channel.cid) ?: return@write
163172
if (stored.updatedAt.isAfter(channel.updatedAt)) {
164173
logger.d { "[saveChannel] stored ${channel.cid} is newer than the response" }
165-
return
174+
return@write
166175
}
167176
val merged = stored.mergeChannelFromEvent(channel).copy(
168177
hidden = channel.hidden ?: stored.hidden,

‎stream-chat-android-client/src/main/java/io/getstream/chat/android/client/internal/state/sync/internal/SyncManager.kt‎

Lines changed: 46 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ import io.getstream.chat.android.client.internal.state.plugin.logic.querychannel
3838
import io.getstream.chat.android.client.internal.state.plugin.state.global.internal.MutableGlobalState
3939
import io.getstream.chat.android.client.parser2.SyncedEvents
4040
import io.getstream.chat.android.client.persistance.repository.RepositoryFacade
41+
import io.getstream.chat.android.client.persistance.repository.write
4142
import io.getstream.chat.android.client.query.CreateChannelParams
4243
import io.getstream.chat.android.client.setup.state.ClientState
4344
import io.getstream.chat.android.client.sync.SyncState
@@ -619,16 +620,18 @@ internal class SyncManager(
619620
return
620621
}
621622
logger.d { "[updateAllReadStateForDate] userId: $userId, currentDate: $currentDate" }
622-
val syncState = repos.selectSyncState(userId)?.let { selectedState ->
623-
logger.v {
624-
"[updateAllReadStateForDate] selectedState.activeCids.zie: ${selectedState.activeChannelIds.size}"
625-
}
626-
when (selectedState.markedAllReadAt?.before(currentDate)) {
627-
true -> selectedState.copy(markedAllReadAt = currentDate).also { newState ->
628-
repos.insertSyncState(newState)
623+
val syncState = repos.write {
624+
repos.selectSyncState(userId)?.let { selectedState ->
625+
logger.v {
626+
"[updateAllReadStateForDate] selectedState.activeCids.zie: ${selectedState.activeChannelIds.size}"
629627
}
628+
when (selectedState.markedAllReadAt?.before(currentDate)) {
629+
true -> selectedState.copy(markedAllReadAt = currentDate).also { newState ->
630+
repos.insertSyncState(newState)
631+
}
630632

631-
else -> selectedState
633+
else -> selectedState
634+
}
632635
}
633636
} ?: SyncState(userId)
634637
setSyncState(syncState)
@@ -660,26 +663,32 @@ internal class SyncManager(
660663
rescueStuckInProgress("channels") {
661664
val cids = repos.selectChannelCidsBySyncStatus(SyncStatus.IN_PROGRESS)
662665
logger.d { "[rescueEntitiesStuckInProgress] cids.size: ${cids.size}" }
666+
// A write for each, so one that fails keeps the ones before it handed back.
663667
cids.forEach { cid ->
664-
val channel = repos.selectChannel(cid) ?: return@forEach
665-
repos.insertChannel(channel.copy(syncStatus = SyncStatus.SYNC_NEEDED))
668+
repos.write {
669+
repos.selectChannel(cid)?.let { repos.insertChannel(it.copy(syncStatus = SyncStatus.SYNC_NEEDED)) }
670+
}
666671
}
667672
}
668673
rescueStuckInProgress("messages") {
669-
// An old delete left in progress almost always reached the backend and lost only its result, and the
670-
// retry would just remove it locally. A delete for the current user has no local date to tell its age.
671-
repos.markDeletesInProgressAsCompleted(deletedBefore = Date(now() - syncMaxThreshold.millis))
672-
val messageIds = repos.selectMessageIdsBySyncState(SyncStatus.IN_PROGRESS)
673-
logger.d { "[rescueEntitiesStuckInProgress] messageIds.size: ${messageIds.size}" }
674-
// Status only, since every insert of a deleted message is dropped
675-
messageIds.forEach { id -> repos.updateMessageSyncStatus(id, SyncStatus.SYNC_NEEDED) }
674+
repos.write {
675+
// An old delete left in progress almost always reached the backend and lost only its result, and the
676+
// retry would just remove it locally. A delete for the current user has no local date to tell its age.
677+
repos.markDeletesInProgressAsCompleted(deletedBefore = Date(now() - syncMaxThreshold.millis))
678+
val messageIds = repos.selectMessageIdsBySyncState(SyncStatus.IN_PROGRESS)
679+
logger.d { "[rescueEntitiesStuckInProgress] messageIds.size: ${messageIds.size}" }
680+
// Status only, since every insert of a deleted message is dropped
681+
messageIds.forEach { id -> repos.updateMessageSyncStatus(id, SyncStatus.SYNC_NEEDED) }
682+
}
676683
}
677684
rescueStuckInProgress("reactions") {
678685
val reactionIds = repos.selectReactionIdsBySyncStatus(SyncStatus.IN_PROGRESS)
679686
logger.d { "[rescueEntitiesStuckInProgress] reactionIds.size: ${reactionIds.size}" }
680687
reactionIds.forEach { id ->
681-
val reaction = repos.selectReactionById(id) ?: return@forEach
682-
repos.insertReaction(reaction.copy(syncStatus = SyncStatus.SYNC_NEEDED))
688+
repos.write {
689+
repos.selectReactionById(id)
690+
?.let { repos.insertReaction(it.copy(syncStatus = SyncStatus.SYNC_NEEDED)) }
691+
}
683692
}
684693
}
685694
}
@@ -997,7 +1006,7 @@ internal class SyncManager(
9971006
?.updateDataForChannel(channel, channel.messages.size, fromServer = true)
9981007
}
9991008
mutableGlobalState.updateChannelDrafts(foundChannels)
1000-
repos.storeStateForChannels(foundChannels)
1009+
repos.write { repos.storeStateForChannels(foundChannels) }
10011010
val foundCids = foundChannels.mapTo(mutableSetOf(), Channel::cid)
10021011
val stillMissingChannelIds = requestedIds.filterNot { it.cid in foundCids }
10031012
logger.v { "[updateActiveChannels] stillMissingCids.size: ${stillMissingChannelIds.size}" }
@@ -1081,7 +1090,7 @@ internal class SyncManager(
10811090
?.updateDataForChannel(channel, channel.messages.size, fromServer = true)
10821091
}
10831092
mutableGlobalState.updateChannelDrafts(foundChannels)
1084-
repos.storeStateForChannels(foundChannels)
1093+
repos.write { repos.storeStateForChannels(foundChannels) }
10851094
foundChannels.mapTo(refreshedCids, Channel::cid)
10861095
}
10871096
// Stop at the first failure: the remaining requests would be spent on a refresh the
@@ -1118,7 +1127,7 @@ internal class SyncManager(
11181127
val channel = repos.selectChannel(cid) ?: return@forEach
11191128
val result = if (channel.createdAt.exceedsSyncThreshold()) {
11201129
logger.w { "[retryChannels] outdated channel($cid)" }
1121-
repos.deleteChannel(cid)
1130+
repos.write { repos.deleteChannel(cid) }
11221131
uncreatedCids += cid
11231132
discardedCids += cid
11241133
Result.Success(Unit)
@@ -1139,8 +1148,10 @@ internal class SyncManager(
11391148
if (retriedCid != cid) {
11401149
// The create stores and replaces the placeholder regenerated from the members, so one stored with
11411150
// another member order is renamed first, or it would be left behind next to the regenerated one
1142-
repos.insertChannel(channel.copy(id = retriedCid.substringAfter(':')))
1143-
repos.replacePlaceholderChannel(cid, retriedCid)
1151+
repos.write {
1152+
repos.insertChannel(channel.copy(id = retriedCid.substringAfter(':')))
1153+
repos.replacePlaceholderChannel(cid, retriedCid)
1154+
}
11441155
}
11451156
// The server rejects the placeholder id, so it resolves the distinct channel from the members
11461157
val channelId = if (isPlaceholder) "" else channel.id
@@ -1308,7 +1319,7 @@ internal class SyncManager(
13081319

13091320
private suspend fun markMessageAsFailed(message: Message): Result<Unit> = try {
13101321
val failed = message.copy(syncStatus = SyncStatus.FAILED_PERMANENTLY, updatedLocallyAt = Date(now()))
1311-
repos.insertMessage(failed)
1322+
repos.write { repos.insertMessage(failed) }
13121323
logicRegistry.channelFromMessage(failed)?.upsertMessage(failed)
13131324
logicRegistry.getActiveQueryThreadsLogic().forEach { it.upsertMessage(failed) }
13141325
logicRegistry.threadFromMessage(failed)?.upsertMessage(failed)
@@ -1398,12 +1409,16 @@ internal class SyncManager(
13981409
try {
13991410
logger.d { "[removeReaction] reaction.id: ${reaction.id}" }
14001411
// A dropped deletion leaves its message alone: the reaction is still on the server.
1401-
if (reaction.deletedAt == null) {
1402-
removeReactionFromState(reaction)
1403-
repos.selectMessage(reaction.messageId)?.let { repos.insertMessage(it.removeMyReaction(reaction)) }
1412+
val onMessage = reaction.deletedAt == null
1413+
if (onMessage) removeReactionFromState(reaction)
1414+
// One write, so a failure leaves the row for the next sync to drop again.
1415+
repos.write {
1416+
if (onMessage) {
1417+
repos.selectMessage(reaction.messageId)
1418+
?.let { repos.insertMessage(it.removeMyReaction(reaction)) }
1419+
}
1420+
repos.deleteReaction(reaction)
14041421
}
1405-
// Deleted last, so a failure above leaves the row for the next sync to drop again.
1406-
repos.deleteReaction(reaction)
14071422
logger.v { "[removeReaction] completed: ${reaction.id}" }
14081423
Result.Success(Unit)
14091424
} catch (e: Throwable) {
@@ -1430,7 +1445,7 @@ internal class SyncManager(
14301445
return CoroutineCall(syncScope) {
14311446
try {
14321447
logger.d { "[removeMessage] message.id: ${message.id}" }
1433-
repos.deleteChannelMessage(message)
1448+
repos.write { repos.deleteChannelMessage(message) }
14341449
logicRegistry.channelFromMessage(message)?.deleteMessage(message)
14351450
logicRegistry.getActiveQueryThreadsLogic().forEach { it.deleteMessage(message) }
14361451
logicRegistry.threadFromMessage(message)?.deleteMessage(message)

0 commit comments

Comments
 (0)