git.iko.soy/opencode-android
on 066cded help sign in
opencode-android/app/src/main/java/soy/iko/opencode/di/OpencodeConnection.kt
47 lines 2.0 kB history raw
1package soy.iko.opencode.di
3import soy.iko.opencode.data.model.ServerProfile
4import soy.iko.opencode.data.network.EventStreamClient
5import soy.iko.opencode.data.network.HttpClientFactory
6import soy.iko.opencode.data.network.OpencodeApiClient
7import soy.iko.opencode.data.repo.MessageCacheStore
8import soy.iko.opencode.data.repo.SessionRepository
9import kotlinx.coroutines.CoroutineScope
10import kotlinx.coroutines.Dispatchers
11import kotlinx.coroutines.SupervisorJob
12import kotlinx.coroutines.cancel
14/**
15 * An active connection to one opencode server. Bundles the Ktor client, REST API,
16 * SSE event stream, and the reducing repository, all sharing a connection-scoped
17 * coroutine scope that is cancelled on [close].
18 */
19open class OpencodeConnection(
20 val profile: ServerProfile,
21 // Optional on-disk message cache, supplied by AppContainer, so conversations render
22 // instantly and stay readable offline. Null in the test constructor.
23 private val messageCache: MessageCacheStore? = null,
24) {
26 protected constructor() : this(ServerProfile(id = "", label = "", baseUrl = "http://localhost"), null)
28 private val scopeJob = SupervisorJob()
29 private val scope by lazy { CoroutineScope(scopeJob + Dispatchers.IO) }
30 private val client by lazy { HttpClientFactory.create(profile) }
32 open val api: OpencodeApiClient by lazy { OpencodeApiClient(client) }
33 open val events: EventStreamClient by lazy { EventStreamClient(client, scope) }
34 open val repository: SessionRepository by lazy { SessionRepository(api, events, messageCache, profile.id) }
36 /**
37 * Cancel the coroutine scope and wait for in-flight work (including the SSE reader)
38 * to wind down before closing the HTTP client. Calling client.close() while the SSE
39 * coroutine is still mid-request produces a spurious "stream error, will retry"
40 * warning during normal teardown.
41 */
42 open suspend fun close() {
43 scope.cancel()
44 scopeJob.join()
45 runCatching { client.close() }
46 }