|
| 1 | +package com.flipcash.shared.chat.internal |
| 2 | + |
| 3 | +import com.flipcash.app.persistence.sources.UserProfileDataSource |
| 4 | +import com.flipcash.services.controllers.ChatController |
| 5 | +import com.flipcash.services.models.chat.ChatId |
| 6 | +import com.flipcash.services.models.chat.MentionSuggestion |
| 7 | +import com.getcode.opencode.model.core.ID |
| 8 | +import kotlinx.coroutines.CompletableDeferred |
| 9 | +import kotlinx.coroutines.CoroutineScope |
| 10 | +import kotlinx.coroutines.Deferred |
| 11 | +import kotlinx.coroutines.async |
| 12 | +import kotlinx.coroutines.sync.Mutex |
| 13 | +import kotlinx.coroutines.sync.withLock |
| 14 | +import kotlin.time.Instant |
| 15 | +import javax.inject.Inject |
| 16 | +import javax.inject.Singleton |
| 17 | + |
| 18 | +/** |
| 19 | + * The pool of people a group offers for `@` mentions, as `Chat.GetMentionSuggestions` ranked it. |
| 20 | + * |
| 21 | + * Fetched once per composing session: [startSession] replaces whatever is held with a new fetch, |
| 22 | + * and [pool] waits on that fetch, starting one if no session has begun. Held in memory only; the |
| 23 | + * next session fetches again, which is how senders the pool has never seen get in. |
| 24 | + * |
| 25 | + * Between fetches, [onMessages] keeps the order fresh by moving a known sender to the front. |
| 26 | + */ |
| 27 | +@Singleton |
| 28 | +internal class MentionSuggestionPool @Inject constructor( |
| 29 | + private val chatController: ChatController, |
| 30 | + private val profiles: UserProfileDataSource, |
| 31 | +) : MentionPoolUpdates { |
| 32 | + |
| 33 | + private val lock = Mutex() |
| 34 | + private val sessions = mutableMapOf<ChatId, Deferred<Result<List<MentionSuggestion>>>>() |
| 35 | + |
| 36 | + /** Begins a composing session for [chatId] with a fresh fetch, on [scope]. */ |
| 37 | + suspend fun startSession(scope: CoroutineScope, chatId: ChatId) { |
| 38 | + lock.withLock { sessions[chatId] = scope.fetchAsync(chatId) } |
| 39 | + } |
| 40 | + |
| 41 | + /** [chatId]'s pool for the current session, most relevant first, or the failure that ended its fetch. */ |
| 42 | + suspend fun pool(scope: CoroutineScope, chatId: ChatId): Result<List<MentionSuggestion>> = |
| 43 | + lock.withLock { sessions.getOrPut(chatId) { scope.fetchAsync(chatId) } }.await() |
| 44 | + |
| 45 | + override suspend fun onMessages(chatId: ChatId, senders: List<Pair<ID, Instant>>) { |
| 46 | + lock.withLock { |
| 47 | + val session = sessions[chatId] ?: return |
| 48 | + if (!session.isCompleted) return |
| 49 | + val held = session.getCompleted().getOrNull() ?: return |
| 50 | + sessions[chatId] = CompletableDeferred(Result.success(movedToFront(held, senders))) |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + private fun CoroutineScope.fetchAsync(chatId: ChatId): Deferred<Result<List<MentionSuggestion>>> = async { |
| 55 | + chatController.getMentionSuggestions(chatId).onSuccess { pool -> |
| 56 | + pool.forEach { suggestion -> |
| 57 | + val userId = suggestion.userProfile.userId ?: return@forEach |
| 58 | + profiles.store(userId, suggestion.userProfile) |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | +} |
| 64 | + |
| 65 | +/** Told about each message the event stream delivers, so the mention pool's order stays fresh. */ |
| 66 | +interface MentionPoolUpdates { |
| 67 | + suspend fun onMessages(chatId: ChatId, senders: List<Pair<ID, Instant>>) |
| 68 | + |
| 69 | + object None : MentionPoolUpdates { |
| 70 | + override suspend fun onMessages(chatId: ChatId, senders: List<Pair<ID, Instant>>) = Unit |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +/** |
| 75 | + * [pool] with each sender in [senders] that it already holds moved to the front, newest message |
| 76 | + * first, when that message is newer than the sender's last_sent_at. A sender the pool doesn't hold |
| 77 | + * is left out; the next session's fetch brings them in. |
| 78 | + */ |
| 79 | +internal fun movedToFront( |
| 80 | + pool: List<MentionSuggestion>, |
| 81 | + senders: List<Pair<ID, Instant>>, |
| 82 | +): List<MentionSuggestion> { |
| 83 | + val byUser = pool.associateBy { it.userProfile.userId } |
| 84 | + val latest = senders.groupBy({ it.first }, { it.second }).mapValues { (_, times) -> times.max() } |
| 85 | + val moved = latest |
| 86 | + .mapNotNull { (userId, sentAt) -> |
| 87 | + val held = byUser[userId] ?: return@mapNotNull null |
| 88 | + val last = held.lastSentAt |
| 89 | + if (last != null && last >= sentAt) null else held.copy(lastSentAt = sentAt) |
| 90 | + } |
| 91 | + .sortedByDescending { it.lastSentAt } |
| 92 | + if (moved.isEmpty()) return pool |
| 93 | + val movedIds = moved.map { it.userProfile.userId }.toSet() |
| 94 | + return moved + pool.filterNot { it.userProfile.userId in movedIds } |
| 95 | +} |
0 commit comments