feat(events): EventStore + AllEvent unified stream + replay endpoints
ci / JVM build + tests (push) Has been cancelled
release / Publish KMP libraries → caffeine Nexus (release) Successful in 32s

EventStore (persistent event log) и AllEvent (sealed wrapper для
третьего типа подписки — ВСЕ events в одном потоке). Touches 7 modules.

Архитектура:
  Producer (ChatAgent + ConversationEvents) → EventStore + SharedFlow
  ↓                                            ↓
  Live SSE (cold, no replay)         Replay endpoints (cursor-based)

(1) :storage-core — EventStore interface
  - append(record): idempotent по record.id (INSERT OR IGNORE)
  - query(conversationId?, afterId?, limit): пагинированный catchup
  - pruneOlderThan(instant): TTL cleanup
  - count(): maintenance метрика
  - @Serializable EventRecord(id, conversationId?, createdAt, type, payload)
  - enum EventType: AGENT_*/CONVERSATION_* (forward-compat fallback)
  - StorageBundle дополнен eventStore: EventStore? = null (backward-compat)

(2) :storage-inmemory — InMemoryEventStore
  - Thread-safe (Mutex), binarySearch для упорядоченной вставки
  - Записи сортируются по createdAt ASC, ties по id ASC (стабильно)
  - Idempotency по id (повторный append no-op)

(3) :storage-sqlite — SqliteEventStore
  - sqldelight schema: agent_event (id PK, conversation_id?, created_at,
    type, payload BLOB) + 2 индекса (conversation_id+created_at,
    created_at)
  - Миграция v3: CREATE TABLE IF NOT EXISTS (additive)
  - 5 запросов: insert, queryGlobal, queryByConv, pruneOlderThan, count
  - Forward-compat: неизвестный EventType в БД → fallback AGENT_CREATED
    (чтобы старые клиенты не падали на новых enum values)
  - Добавлен в SqliteStores (open/inMemory + asBundle())

(4) :standalone — Producer wiring
  - ChatAgent.persistAgentEvent() — fire-and-forget append при каждом
    AgentEvent (Created/Deleted/Renamed)
  - ConversationEvents — персистит в EventStore при каждом tryEmit/emit
    (концертный случай от connect disconnect)
  - ChatAgent.allEvents() — merge agent-events + snapshot всех живых
    диалогов в единый Flow<AllEvent>

(5) :proto — AllEvent sealed interface
  - AllEvent.Agent(date, event: AgentEvent)
  - AllEvent.Conversation(date, conversationId, event: Event)
  - Agent.allEvents(after): Flow<AllEvent> — третий тип подписки
    (в дополнение к events() и Conversation.events)

(6) :server — Endpoints
  - GET /events/all — SSE поток AllEvent (cold)
  - GET /events/replay?after_id=&limit= — пагинированный catchup
    (503 если EventStore не сконфигурирован)
  - GET /conversations/{id}/events/replay?after_id=&limit= — то же per-conv
  - Module.kt принимает eventStore: EventStore? параметром

(7) :client — Client API
  - AgentClient.allEvents(after) — подписка на /events/all SSE
  - AgentClient.replayAllEvents(afterId, limit) — catchup /events/replay
  - AgentClient.replayConversationEvents(convId, afterId, limit)
  - EventRecordDto — wire-зеркало EventRecord (клиент не зависит
    от :storage-core, определяет DTO локально; формат совместим с
    серверным JSON)

Тесты: 22 новых теста (12 InMemory + 10 Sqlite), все зелёные.
Все три слоя синхронизированы: proto contract + standalone impl +
server endpoint + client API.
This commit is contained in:
2026-09-20 02:51:58 +03:00
parent c140d0b758
commit 4ad59d5f5d
18 changed files with 1065 additions and 19 deletions
@@ -17,6 +17,7 @@ import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.runBlocking
import pw.binom.agentik.proto.Agent
import pw.binom.agentik.proto.AgentEvent
import pw.binom.agentik.proto.AllEvent
import pw.binom.agentik.proto.Conversation
import kotlin.time.Instant
@@ -78,4 +79,74 @@ internal class AgentClient(
}
}
}
/**
* Подписка на ВСЕ события: agent lifecycle + все conversation events.
* Использует SSE endpoint /events/all.
*/
override fun allEvents(after: Instant): Flow<AllEvent> = flow {
httpClient.prepareGet("$agentUrl/events/all?after=$after") { noSseReadTimeout() }
.execute { response ->
check(response.status == HttpStatusCode.OK) {
"allEvents: server returned ${response.status}"
}
readSse(response.bodyAsChannel())
.collect { payload ->
emit(agentikJson.decodeFromString(AllEvent.serializer(), payload))
}
}
}
/**
* Catchup для /events/replay — пагинированно читает events после [afterId].
* Caller делает несколько вызовов пока `result.size < limit` (= конец).
*
* @param afterId exclusive cursor. `null` = с начала.
* @param limit max per-request (default 100, max 1000 на сервере).
*/
internal suspend fun replayAllEvents(
afterId: String? = null,
limit: Int = 100,
): List<EventRecordDto> {
val response = httpClient.get("$agentUrl/events/replay") {
afterId?.let { parameter("after_id", it) }
parameter("limit", limit)
}
return response.body()
}
/**
* Catchup для /conversations/{id}/events/replay — пагинированно.
*/
internal suspend fun replayConversationEvents(
conversationId: String,
afterId: String? = null,
limit: Int = 100,
): List<EventRecordDto> {
val response = httpClient.get("$agentUrl/conversations/$conversationId/events/replay") {
afterId?.let { parameter("after_id", it) }
parameter("limit", limit)
}
return response.body()
}
}
/**
* Запись event'а, которую возвращает /events/replay endpoint.
*
* Это **мини-зеркало** `pw.binom.agentik.storage.events.EventRecord` — клиент
* не зависит от `:storage-core`, поэтому определяет свою модель (wire-only).
*
* Формат полностью совместим с сервером — `agentikJson.encodeToString(...)` там
* и `agentikJson.decodeFromString(...)` здесь.
*/
@kotlinx.serialization.Serializable
internal data class EventRecordDto(
val id: String,
val conversationId: String? = null,
val createdAt: kotlin.time.Instant,
val type: String,
val payload: String,
)