Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class SseChangeParser @Inject constructor() {
fun parse(event: SseEvent): ParsedSseChange? {
val name = event.name
// Nothing to act on: the long connection's keep-alive, the task queue counter and the session expiry
// (RootViewModel logs out on that one).
// (RootViewModel logs out on that one). The queue counter is not dropped, it is read by [parseTaskQueue].
if (name.startsWith("Task") || name == "SessionExpired") return null
if (CONTENT_EVENT_PREFIXES.none { name.startsWith(it) }) return null

Expand Down Expand Up @@ -197,6 +197,19 @@ class SseChangeParser @Inject constructor() {
}
}

/**
* The `TaskQueueStatus` frame: the server's whole queue (`count` plus per-type counts), re-sent every 10 s while
* tasks run. It is not a content delta — no row changed — so it does not travel through [parse], and its
* consumer is [TaskQueueStore] rather than the change bus.
*/
fun parseTaskQueue(data: String): TaskQueueStore.Snapshot? =
runCatching { json.decodeFromString<TaskQueuePayload>(data) }.getOrNull()?.let { payload ->
TaskQueueStore.Snapshot(
count = payload.count.coerceAtLeast(0),
countByType = payload.countByType.filterValues { it > 0 },
)
}

/** Decode [data], or fall back to "reload everything" when the payload is not what we expect. */
private inline fun <reified T> decodable(data: String, consume: (T) -> ParsedSseChange?): ParsedSseChange =
runCatching { json.decodeFromString<T>(data) }.getOrNull()?.let(consume)
Expand Down Expand Up @@ -244,3 +257,13 @@ private data class ReadListPayload(
private data class SmartListPayload(
val smartListId: String? = null,
)

/**
* `TaskQueueStatus` payload (Komga `TaskQueueStatus`): the queued total and its split by task class. Both fields
* default so a future server that adds keys keeps working; unknown keys are ignored by the parser's `Json`.
*/
@Serializable
private data class TaskQueuePayload(
val count: Int = 0,
val countByType: Map<String, Int> = emptyMap(),
)
11 changes: 11 additions & 0 deletions app/src/main/java/com/kmworks/kmreader/core/sse/SseContentSync.kt
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ class SseContentSync @Inject constructor(
private val parser: SseChangeParser,
private val contentChangeBus: ContentChangeBus,
private val thumbnailCache: ThumbnailCache,
private val taskQueueStore: TaskQueueStore,
private val scope: CoroutineScope,
) {

Expand Down Expand Up @@ -111,6 +112,16 @@ class SseContentSync @Inject constructor(

private suspend fun collectEvents() {
sseService.events.collect { event ->
// The queue snapshot is not a content change: no row it names can be patched, and the ids it carries are
// task classes, not entities. It is the only live "the server is working" signal, so it goes to the
// store the server screens read. Being the first frame of every connection, it also refills the badge
// after a reconnect without an extra request.
if (event.name == SseService.TASK_QUEUE_STATUS) {
parser.parseTaskQueue(event.data)?.let { queue ->
taskQueueStore.update(queue.count, queue.countByType)
}
return@collect
}
val parsed = runCatching { parser.parse(event) }.getOrNull() ?: return@collect
if (parsed.coverDtoIds.isNotEmpty()) refreshCovers(event, parsed)
val change = parsed.change ?: return@collect
Expand Down
14 changes: 11 additions & 3 deletions app/src/main/java/com/kmworks/kmreader/core/sse/SseService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import okhttp3.sse.EventSourceListener
@Singleton
class SseService @Inject constructor(
private val scope: CoroutineScope,
private val taskQueueStore: TaskQueueStore,
) {

private val _connectionState = MutableStateFlow<SseConnectionState>(SseConnectionState.Disconnected)
Expand Down Expand Up @@ -140,6 +141,8 @@ class SseService @Inject constructor(
lastEventId = null
cursorInstance = null
}
// The queue belonged to this socket; see TaskQueueStore.clear() (iOS does the same in `disconnect`).
taskQueueStore.clear()
_connectionState.value = SseConnectionState.Disconnected
}

Expand Down Expand Up @@ -223,6 +226,7 @@ class SseService @Inject constructor(
// Keep-alives stay out of the log (the server ticks its task counter every 10 s, which would be pure
// noise); the per-connection summary below still reports how many frames the stream carried, so
// "silent socket" and "healthy stream" remain distinguishable. Content events are rare enough to log.
// The task counter is still delivered to [events]: SseContentSync turns it into the queue badge.
if (name != TASK_QUEUE_STATUS) {
contentCount++
_lastContentAt.value = now
Expand Down Expand Up @@ -289,13 +293,17 @@ class SseService @Inject constructor(
it.className.startsWith("com.kmworks") && !it.className.endsWith("SseService")
}?.let { "${it.className.substringAfterLast('.')}.${it.methodName}" } ?: "unknown"

private companion object {
internal companion object {
const val TAG = "SseService"
const val INITIAL_BACKOFF_MS = 2_000L
const val MAX_BACKOFF_MS = 60_000L

/** The server's 10 s admin-only task counter: proves the stream is alive but is not content. */
const val TASK_QUEUE_STATUS = "TaskQueueStatus"
/**
* The server's admin-only task counter, re-sent every 10 s while the queue is non-empty: it is both the
* cheapest keep-alive the stream has and the queue snapshot [TaskQueueStore] publishes. It carries no content
* delta, so it stays out of the content-frame accounting and out of the event log.
*/
internal const val TASK_QUEUE_STATUS = "TaskQueueStatus"

/** Quiet period between two gap announcements, so a flapping stream cannot turn into a re-read storm. */
const val GAP_SIGNAL_MIN_INTERVAL_MS = 20_000L
Expand Down
60 changes: 60 additions & 0 deletions app/src/main/java/com/kmworks/kmreader/core/sse/TaskQueueStore.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package com.kmworks.kmreader.core.sse

import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow

/**
* The server's task queue as the SSE stream last announced it (iOS `TaskQueueSSEDto` kept in `AppConfig`).
*
* The stream opens with this snapshot and the server re-sends it every 10 s while work is queued, so the count is
* the one live "something is happening on the server" signal the app gets for free — no polling, no extra request.
* Scroll-scanning a library is the usual reason a grid looks stale, and until this store existed the app had no way
* to say so: the count only ever appeared after opening Server → Tasks and letting that page fetch `/stats/server` once.
*
* Komga sends the frame to administrators only, so a non-admin session simply never sees a non-zero
* [Snapshot.count] — absent, not wrong, the same way iOS gates its task surfaces behind `current.isAdmin`.
*
* [Snapshot.countByType] keys are the server's task class names (`ScanLibraryTask`, …), the strings the server
* screens humanize; they are carried as-is so no screen has to keep its own task-type table.
*/
@Singleton
class TaskQueueStore @Inject constructor() {

/**
* [updatedAt] is null until the stream announces a queue: it separates "the server says zero tasks" from
* "nothing has been announced yet", which is what lets a screen fall back to a fetched value instead of
* painting a zero it has no evidence for.
*/
data class Snapshot(
val count: Int = 0,
val countByType: Map<String, Int> = emptyMap(),
val updatedAt: Long? = null,
)

private val _snapshot = MutableStateFlow(Snapshot())
val snapshot = _snapshot.asStateFlow()

/**
* Replace the state with a newly announced queue. The frame carries the whole queue, not a delta, so a stale
* entry must never survive: a task that finished is simply absent from the next frame.
*/
fun update(count: Int, countByType: Map<String, Int>, atMillis: Long = System.currentTimeMillis()) {
_snapshot.value = Snapshot(
count = count.coerceAtLeast(0),
countByType = countByType.filterValues { it > 0 },
updatedAt = atMillis,
)
}

/**
* Forget the last announcement. The queue belongs to a stream: once the socket is stopped, or replaced by
* another server instance, the old count speaks for a server the app is no longer talking to (iOS clears
* `AppConfig.taskQueueStatus` in `disconnect` for the same reason). The next connection re-announces its
* snapshot as its very first frame, so nothing stays empty for long.
*/
fun clear() {
_snapshot.value = Snapshot()
}
}
8 changes: 8 additions & 0 deletions app/src/main/java/com/kmworks/kmreader/ui/RootViewModel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import com.kmworks.kmreader.core.sse.SseConnectionState
import com.kmworks.kmreader.core.sse.SseContentSync
import com.kmworks.kmreader.core.sse.SseEventKind
import com.kmworks.kmreader.core.sse.SseService
import com.kmworks.kmreader.core.sse.TaskQueueStore
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.Dispatchers
Expand Down Expand Up @@ -46,6 +47,7 @@ class RootViewModel @Inject constructor(
private val appSettings: AppSettingsStore,
private val sseService: SseService,
private val sseContentSync: SseContentSync,
private val taskQueueStore: TaskQueueStore,
private val sessionManager: SessionManager,
private val detailRepository: DetailRepository,
private val downloadRepository: DownloadRepository,
Expand All @@ -65,6 +67,12 @@ class RootViewModel @Inject constructor(
/** Server reachability (fed by the shared OkHttp client): drives the global offline indicator. */
val serverOffline: StateFlow<Boolean> = serverReachability.offline

/**
* The server's task queue as the live stream last announced it (empty once disconnected). Read by the settings
* entry and the server screens, so "the server is scanning" is visible without opening a page that polls for it.
*/
val taskQueue: StateFlow<TaskQueueStore.Snapshot> = taskQueueStore.snapshot

/** True while a tap on the offline indicator has a probe request in flight. */
val probingServer: StateFlow<Boolean> get() = _probingServer
private val _probingServer = MutableStateFlow(false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ import com.kmworks.kmreader.core.api.model.HistoricalEventDto
import com.kmworks.kmreader.core.server.SessionEntry
import com.kmworks.kmreader.core.server.SessionScope
import com.kmworks.kmreader.core.server.TaskTypeStatsDto
import com.kmworks.kmreader.core.sse.TaskQueueStore
import com.kmworks.kmreader.ui.components.relativeTimeLabel
import com.kmworks.kmreader.ui.settings.settingsBackIcon
import com.kmworks.kmreader.ui.settings.SettingsDangerRow
Expand Down Expand Up @@ -125,6 +126,8 @@ fun ServerAdminScreen(
viewModel: ServerAdminViewModel = hiltViewModel(),
) {
val state by viewModel.state.collectAsStateWithLifecycle()
// The queue as the live stream announces it, next to the snapshot the page fetched once.
val taskQueue by viewModel.taskQueue.collectAsStateWithLifecycle()
val snackbarHostState = remember { SnackbarHostState() }
var confirmShutdown by remember { mutableStateOf(false) }
var confirmCancelAll by remember { mutableStateOf(false) }
Expand Down Expand Up @@ -205,7 +208,10 @@ fun ServerAdminScreen(
when {
!state.isAdmin -> CenteredMessage(R.string.server_admin_admin_required)
state.page == ServerAdminPage.Info -> InfoPage(
taskQueueCount = state.tasks.queueSize,
// Live count first — it is the stream's own snapshot, and it moves without a refresh. Until
// the stream has announced one (SSE off, an older server, a non-admin session) the value this
// page fetched from `/stats/server` stands in.
taskQueueCount = if (taskQueue.updatedAt != null) taskQueue.count.toLong() else state.tasks.queueSize,
onOpen = viewModel::open,
onDownloadLog = { viewModel.open(ServerAdminPage.Log) },
onShutdown = { confirmShutdown = true },
Expand All @@ -214,6 +220,7 @@ fun ServerAdminScreen(
state.page == ServerAdminPage.Libraries -> LibrariesPage(state)
state.page == ServerAdminPage.Tasks -> TasksPage(
state = state,
live = taskQueue,
onCancelAll = { confirmCancelAll = true },
)
state.page == ServerAdminPage.Sessions -> SessionsPage(
Expand Down Expand Up @@ -682,15 +689,26 @@ private fun LibrariesPage(state: ServerAdminUiState) {
// region tasks page

@Composable
private fun TasksPage(state: ServerAdminUiState, onCancelAll: () -> Unit) {
private fun TasksPage(state: ServerAdminUiState, live: TaskQueueStore.Snapshot, onCancelAll: () -> Unit) {
val tasks = state.tasks
if (tasks.loading && tasks.types.isEmpty() && tasks.queueSize == null) {
Loading()
return
}
val queuedTypes = tasks.types
.filter { (it.queued ?: 0L) > 0L }
.sortedWith(compareByDescending<TaskTypeStatsDto> { it.queued ?: 0L }.thenBy { it.type })
// Once the stream has announced a queue, it is the authority: same queue, but it moves on its own, and on stock
// Komga it is the only per-type source the app has (the stats endpoint there carries no `queued`).
val announced = live.updatedAt != null
val queueTotal: Long? = if (announced) live.count.toLong() else tasks.queueSize
val queuedTypes: List<Pair<String, Long>> = if (announced) {
live.countByType.entries
.sortedWith(compareByDescending<Map.Entry<String, Int>> { it.value }.thenBy { it.key })
.map { it.key to it.value.toLong() }
} else {
tasks.types
.filter { (it.queued ?: 0L) > 0L }
.sortedWith(compareByDescending<TaskTypeStatsDto> { it.queued ?: 0L }.thenBy { it.type })
.map { it.type to (it.queued ?: 0L) }
}
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(horizontal = 16.dp, vertical = 16.dp),
Expand Down Expand Up @@ -718,17 +736,17 @@ private fun TasksPage(state: ServerAdminUiState, onCancelAll: () -> Unit) {
modifier = Modifier.weight(1f),
)
Text(
text = (tasks.queueSize ?: 0L).toString(),
text = (queueTotal ?: 0L).toString(),
style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.SemiBold,
color = if ((tasks.queueSize ?: 0L) > 0L) {
color = if ((queueTotal ?: 0L) > 0L) {
MaterialTheme.colorScheme.onSurface
} else {
MaterialTheme.colorScheme.onSurfaceVariant
},
)
}
queuedTypes.forEach { type ->
queuedTypes.forEach { (type, queuedCount) ->
SettingsRowDivider()
Row(
modifier = Modifier
Expand All @@ -744,14 +762,14 @@ private fun TasksPage(state: ServerAdminUiState, onCancelAll: () -> Unit) {
)
Spacer(Modifier.width(12.dp))
Text(
text = humanizeTaskType(type.type),
text = humanizeTaskType(type),
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.weight(1f),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(
text = (type.queued ?: 0L).toString(),
text = queuedCount.toString(),
style = MaterialTheme.typography.bodyMedium,
fontWeight = FontWeight.SemiBold,
)
Expand All @@ -761,7 +779,7 @@ private fun TasksPage(state: ServerAdminUiState, onCancelAll: () -> Unit) {
SettingsDangerRow(
text = stringResource(R.string.server_admin_tasks_cancel_all),
icon = Icons.Outlined.Cancel,
enabled = tasks.queueSize != 0L && !tasks.busy,
enabled = queueTotal != 0L && !tasks.busy,
onClick = onCancelAll,
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import com.kmworks.kmreader.core.server.SessionScope
import com.kmworks.kmreader.core.server.StatsLibrariesDto
import com.kmworks.kmreader.core.server.TaskTypeStatsDto
import com.kmworks.kmreader.core.server.UpdateCheckDto
import com.kmworks.kmreader.core.sse.TaskQueueStore
import dagger.hilt.android.lifecycle.HiltViewModel
import java.time.Instant
import java.time.OffsetDateTime
Expand Down Expand Up @@ -131,11 +132,18 @@ data class ServerAdminUiState(
@HiltViewModel
class ServerAdminViewModel @Inject constructor(
private val repository: ServerAdminRepository,
private val taskQueueStore: TaskQueueStore,
) : ViewModel() {

private val _state = MutableStateFlow(ServerAdminUiState())
val state: StateFlow<ServerAdminUiState> = _state.asStateFlow()

/**
* The queue as the SSE stream announces it. The stats endpoint has the same number, but only at the moment it was
* fetched; this one moves on its own, so a scan started from the web UI shows up here without a refresh.
*/
val taskQueue: StateFlow<TaskQueueStore.Snapshot> = taskQueueStore.snapshot

init {
viewModelScope.launch {
val isAdmin = repository.isAdmin()
Expand Down Expand Up @@ -291,6 +299,9 @@ class ServerAdminViewModel @Inject constructor(
_state.update { it.copy(tasks = it.tasks.copy(busy = true)) }
viewModelScope.launch {
val ok = repository.emptyTaskQueue()
// The stream will announce an empty queue within its 10 s tick; clearing it here keeps the badge from
// claiming work that the user just cancelled. Nothing else is lost: the next frame replaces the snapshot.
if (ok) taskQueueStore.update(0, emptyMap())
_state.update {
it.copy(
tasks = it.tasks.copy(busy = false, queueSize = if (ok) 0L else it.tasks.queueSize),
Expand Down
Loading