Skip to content

fix(sse): keep the long connection alive and re-read after every gap - #95

Merged
dyphire merged 1 commit into
mainfrom
fix/sse-stream-resilience
Nov 28, 2026
Merged

dyphire merged 1 commit into
mainfrom
fix/sse-stream-resilience

Conversation

@dyphire

@dyphire dyphire commented Nov 28, 2026

Copy link
Copy Markdown
Member

Problem

SSE never delivered content events. Reading progress and read/unread changes made on another device — or in another app while this one was away — never refreshed anything. Two distinct faults were stacked:

  1. The socket was re-dialed constantly. SessionManager rebuilt ApiClients on every write to either preferences DataStore (theme toggle, lastUsedAt, an unrelated preference), and SseService.start() told a rebuild apart from an instance switch by object identity. Every emission therefore cancelled the in-flight call and dialed again — connections measured in tens of milliseconds.
  2. Every gap was permanent. The resume point (Last-Event-ID) is never filled: the first frame of every connection is the task-queue snapshot, which carries no id, and keep-alives are protocol comments. So after the socket went down (background trip, instance switch, network change, the churn above) nothing could be replayed. iOS does not depend on the cursor either — scenePhase == .active reconnects and refreshes the dashboard sections — and that second half was missing here.

Changes

Transport (core/network/ApiClients.kt, core/network/NetworkModule.kt)

  • Deduplicate both SessionManager.clients inputs by value, so settings writes stop producing new clients.
  • SseService.start() compares base URL + credentials rather than object identity (isAdmin and the timeout are deliberately ignored — the SSE client overrides the timeout, and the capability probe flips isAdmin after login).
  • readTimeout(0) → 45 s. It is a heartbeat watchdog, not a data timeout: the server writes a comment every 15 s, and with no timeout a socket killed by Wi-Fi power save or a NAT drop stayed half-open and reported nothing — forever.
  • Every request now carries User-Agent: KMReader-Android; okhttp's default is what reverse proxies and WAFs refuse.
  • Expose config so the connection comparison can be made.

Lifecycle (core/sse/SseService.kt, ui/RootViewModel.kt, ui/AppRoot.kt)

  • stop(preserveCursor) / restart(): the cursor survives a plain disconnect and is reset only on logout or an instance switch, mirroring iOS disconnect(resettingCursor:).
  • Drop the socket on ON_STOP, reopen on ON_START (the scenePhase counterpart).
  • The connection belongs to the application scope and is no longer torn down when the activity's ViewModel is cleared.
  • A 401/403 stops the loop instead of hammering an endpoint that always refuses.

Catch-up (core/sse/SseService.kt, core/sse/SseContentSync.kt)

  • streamGaps: every reopened stream announces that it starts with a hole (rate limited at 20 s; an explicit stop/start always counts). Screens receive it as an unclassifiable change — each re-reads its own query once, debounced, and the dashboard takes it as a full refresh.
  • A watchdog covers the stream that stays open yet never hands over a content frame: while connected and no content frame has ever arrived, screens re-read every 45 s until one does, then it stops firing. A healthy stream never pays for it.

Settings (core/settings/ClientSettingsSync.kt)

  • Stop writing the SSE switch back down to the device: a stale "false" from another client turned the feature off at every start. iOS keeps that switch purely local too.

Verification

  • ./gradlew :app:compileDebugKotlin, :app:lintDebug (only the four pre-existing warnings) and :app:assembleDebug pass.
  • On device: cross-device read-progress and read/unread changes now refresh without touching the app; logs show one connection per server with content frames arriving, and the gap signal fires on each reopen.
  • Logs were kept quiet: keep-alive frames are not logged; one summary line per connection (SSE connection ended: N frames, M content), the caller of every teardown (SSE loop stopped from …), and content events only.

No generated API sources were touched.

The app never received content events: the socket was re-dialed for reasons
unrelated to the stream, and whenever it was down the changes it missed were
lost for good.

Three separate mechanisms fed that:

- SessionManager rebuilt ApiClients on *every* write to the two preference
  DataStores (a theme toggle, an instance's lastUsedAt, an unrelated
  preference), and SseService.start() compared client objects by identity, so
  each emission cancelled the in-flight call and dialed again. The connection
  lived for tens of milliseconds and reached nobody. Both inputs are now
  deduplicated by value, and start() compares the base URL and credentials
  instead, ignoring the admin flag and the timeout the SSE client overrides.

- readTimeout(0) left a silently dead socket indistinguishable from an idle
  stream: after a background trip or a network switch the state stayed
  "connected" while nothing arrived. The SSE client now uses a 45 s read
  timeout as a heartbeat watchdog (the server writes a comment every 15 s),
  and every request carries an app User-Agent, since reverse proxies refuse
  okhttp's default.

- The socket is dropped on ON_STOP and reopened on ON_START with the cursor
  kept, the iOS scenePhase behavior; only logout or an instance switch resets
  it, and the connection itself belongs to the application scope, so it no
  longer dies with the activity's ViewModel.

What made the gaps permanent is that the resume point is never filled: the
first frame of every connection is the task-queue snapshot, which carries no
id, and keep-alives are protocol comments, so Last-Event-ID stays empty and
the server has nothing to replay. iOS does not rely on it either —
scenePhase == .active reconnects *and* refreshes the dashboard — and that half
was missing here. Every reopened stream now announces a gap (rate limited;
a stop/start always counts), which reaches the screens as an unclassifiable
change: they re-read their own query once, and the dashboard takes it as a
full refresh. A watchdog covers the stream that stays open but never delivers
a content frame at all: screens re-read every 45 s until one arrives, then it
stops firing.

Also: the client settings sync no longer writes the SSE switch back down,
where a stale "false" turned the feature off at every start.
@dyphire
dyphire merged commit 9510aff into main Nov 28, 2026
1 check passed
@dyphire
dyphire deleted the fix/sse-stream-resilience branch November 28, 2026 13:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant