fix backend stuff

This commit is contained in:
2026-07-29 17:05:44 +03:00
parent 6485f4ec26
commit 725c78aa2d
4 changed files with 43 additions and 21 deletions
@@ -18,7 +18,7 @@ class BackendChatRepository(
) : ChatRepository {
override suspend fun query(afterId: Long?): List<Message> {
val history = storage.query(userId, afterId, limit = 10)
val history = storage.query(userId, afterId, limit = 30)
return history.sortedBy { it.timestamp }
}
@@ -6,6 +6,9 @@ import ru.shadowsparky.chat.backend.domain.MessageStorage
import ru.shadowsparky.chat.domain.Message
import ru.shadowsparky.domain.DispatcherProvider
import ru.shadowsparky.vbox.backend.AppDatabase
import ru.shadowsparky.vbox.server.GetInitialChatContext
import ru.shadowsparky.vbox.server.GetNewMessages
import java.time.OffsetDateTime
@Factory
class SqlMessageStorage(
@@ -16,21 +19,32 @@ class SqlMessageStorage(
override suspend fun query(userId: Long, afterId: Long?, limit: Int): List<Message> = withContext(dispatcherProvider.io) {
val chatId = queries.getChatIdByUserId(userId).executeAsOneOrNull() ?: return@withContext emptyList()
val dbMessages = queries.getChatContext(
chatId = chatId,
afterId = afterId,
limit = limit.toLong()
).executeAsList()
dbMessages.map { dbMsg ->
Message(
id = dbMsg.id,
role = dbMsg.role,
content = dbMsg.content,
timestamp = checkNotNull(dbMsg.created_at?.toInstant()?.toEpochMilli()) { "created_at required" }
)
if (afterId == null) {
queries.getInitialChatContext(
chatId = chatId,
limit = limit.toLong()
).executeAsList().reversed().map { it.toMessage() }
} else {
queries.getNewMessages(
chatId = chatId,
afterId = afterId,
limit = limit.toLong()
).executeAsList().map { it.toMessage() }
}
}
private fun GetNewMessages.toMessage(): Message {
return Message(id, role, content, created_at.asMillis())
}
private fun GetInitialChatContext.toMessage(): Message {
return Message(id, role, content, created_at.asMillis())
}
private fun OffsetDateTime?.asMillis(): Long {
return checkNotNull(this?.toInstant()?.toEpochMilli()) { "created_at required" }
}
override suspend fun insert(userId: Long, message: Message): Long = withContext(dispatcherProvider.io) {
val chatId = queries.getChatIdByUserId(userId).executeAsOneOrNull()
?: queries.createChat(userId = userId).executeAsOne()
@@ -14,10 +14,19 @@ INSERT INTO messages (chat_id, role, content)
VALUES (:chatId, :role, :content)
RETURNING id;
getChatContext:
-- Просто берем последние N сообщений (прилетят в порядке: новые -> старые)
getInitialChatContext:
SELECT id, role, content, created_at
FROM messages
WHERE chat_id = :chatId
AND (:afterId IS NULL OR id > :afterId)
ORDER BY id DESC
LIMIT :limit;
-- Сюда новые сообщения всё так же дописываются по порядку (старые -> новые)
getNewMessages:
SELECT id, role, content, created_at
FROM messages
WHERE chat_id = :chatId
AND id > :afterId
ORDER BY id ASC
LIMIT :limit;