Run imports and deletes on the server, and say so on an event
Leaving the import screen used to cancel the batch it had started: the
request was the work, so the coroutine that owned it died with the screen
and coming back showed no sign anything had happened. A half-imported
session is the expensive kind of missing -- the row is back looking
untouched, and taking it again is the second `--resume` the import path
exists to prevent.
So the work runs on the server now. Delete and a new per-session import both
answer 202 and spawn the work, and `session::pending` is the record of it:
what is running, and how the last attempt failed. The phone reads that two
ways and needs both. Every row of the listing carries `pending` and `error`,
which is what a phone that was asleep, out of range or freshly opened has to
go on; `GET /setups/{id}/importable/events` streams the changes, which is
what makes a screen somebody is watching change by itself.
Neither alone is enough, and that is not theoretical. A broadcast has no
memory, so an operation that started and finished while the stream was still
connecting was one nothing would ever be said about -- with responses held
back far enough to make it visible, one row of a pair of deletes cleared and
the other sat on "waiting" for good. The screen now asks again after a
handover when anything still looks outstanding, and takes its row states
from that answer rather than from what it remembers.
The single tap still waits, because "take me to it" needs the session that
was made and 202 does not carry one. Both paths go through the same `spawn`
so they cannot drift about what importing means.
Resolving one importable session no longer lists every one of them:
`import::find` is the same script with one glob narrower, which takes the
import seed off the 3.7-second full scan that `delete` came off earlier.
The SSE connection and its framing are now `Sse`, shared with the session
transcript stream rather than written a second time.
This commit is contained in:
1 parent
b172c464ea
commit
3c159fa1e1
12 files changed
+992
-176
No files matched your search
@@ -1,9 +1,5 @@
|
||||
package com.example.aiapp
|
||||
|
||||
import java.io.IOException
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
/**
|
||||
* The frame name the server uses to say a cursor was too far behind to continue from. Must match
|
||||
* `send_backlog` in the backend's routes.rs.
|
||||
@@ -14,88 +10,29 @@ private const val RESET_EVENT = "reset"
|
||||
* The SSE half of the API: one long-lived GET per open session screen, replaying the transcript
|
||||
* after a cursor and then following it live.
|
||||
*
|
||||
* Blocking -- run() occupies its thread until the stream ends. [close] (from any thread) is the
|
||||
* cancellation path: it disconnects the socket, which unblocks the read; run() then returns instead
|
||||
* of throwing, so a deliberate close doesn't surface as a connection error. The caller owns
|
||||
* reconnecting (with the last seq it saw as the new cursor) -- see SessionScreen.
|
||||
* The connection and its framing belong to [Sse]; what stays here is what this stream's frames
|
||||
* mean. [close] from any thread ends it, and the caller owns reconnecting -- with the last seq it
|
||||
* saw as the new cursor. See SessionScreen.
|
||||
*/
|
||||
class EventStream(private val settings: ServerSettings, private val sessionId: String) {
|
||||
@Volatile private var connection: HttpURLConnection? = null
|
||||
@Volatile private var closed = false
|
||||
class EventStream(settings: ServerSettings, private val sessionId: String) {
|
||||
private val stream = Sse(settings)
|
||||
|
||||
fun close() {
|
||||
closed = true
|
||||
connection?.disconnect()
|
||||
}
|
||||
fun close() = stream.close()
|
||||
|
||||
/**
|
||||
* Streams events after [after] into [onEvent] until the stream drops.
|
||||
*
|
||||
* [onOpen] fires once the server has accepted the connection. That is the measured moment the
|
||||
* stream is live again, and the only honest thing to clear a previous failure on: an earlier
|
||||
* version cleared on the first event instead, so an idle session went on displaying a
|
||||
* connection error that had already been recovered from, indefinitely.
|
||||
*
|
||||
* [onReset] fires when the server answers that the cursor is too far behind to continue from:
|
||||
* everything already displayed is stale and the events that follow are a fresh window, so the
|
||||
* caller drops what it holds and rebuilds -- the same thing it does when the screen opens. It
|
||||
* arrives before those events, so a caller that clears on it stays in order.
|
||||
*/
|
||||
fun run(after: Long, onOpen: () -> Unit, onReset: () -> Unit, onEvent: (SeqEvent) -> Unit) {
|
||||
val connection =
|
||||
URL("${settings.baseUrl}/sessions/$sessionId/events?after=$after").openConnection()
|
||||
as HttpURLConnection
|
||||
this.connection = connection
|
||||
try {
|
||||
connection.applyPinnedTls()
|
||||
connection.connectTimeout = CONNECT_TIMEOUT_MS
|
||||
// No read timeout: between events there is nothing to read for
|
||||
// as long as the session is idle; the server's keep-alives and
|
||||
// a dead socket erroring out are the liveness story.
|
||||
connection.readTimeout = 0
|
||||
connection.setRequestProperty("Authorization", "Bearer ${settings.token}")
|
||||
connection.setRequestProperty("Accept", "text/event-stream")
|
||||
if (connection.responseCode != 200) {
|
||||
val detail = connection.errorStream?.bufferedReader()?.readText()?.trim()
|
||||
throw ApiException(detail ?: "HTTP ${connection.responseCode} for the event stream")
|
||||
}
|
||||
|
||||
onOpen()
|
||||
val reader = connection.inputStream.bufferedReader()
|
||||
// SSE framing: `data:` and `event:` lines accumulate until a
|
||||
// blank line ends the frame. `id:` (the seq) is also inside the
|
||||
// JSON payload, so it needs no separate handling; comment lines
|
||||
// (keep-alives) start with ':' and are skipped.
|
||||
val data = StringBuilder()
|
||||
var name: String? = null
|
||||
while (true) {
|
||||
val line = reader.readLine() ?: break
|
||||
when {
|
||||
line.isEmpty() -> {
|
||||
// A named frame carries no payload and a data frame
|
||||
// has no name, so this is one or the other.
|
||||
if (name == RESET_EVENT) onReset()
|
||||
else if (data.isNotEmpty()) onEvent(parseSeqEvent(data.toString()))
|
||||
data.clear()
|
||||
name = null
|
||||
}
|
||||
line.startsWith("data:") -> data.append(line.removePrefix("data:").trim())
|
||||
line.startsWith("event:") -> name = line.removePrefix("event:").trim()
|
||||
else -> {} // id:, comments -- nothing to do
|
||||
}
|
||||
}
|
||||
} catch (e: ApiException) {
|
||||
throw e
|
||||
} catch (e: IOException) {
|
||||
if (!closed) {
|
||||
throw ApiException(
|
||||
"Can't reach the server -- retrying. (${e.message ?: e::class.simpleName})",
|
||||
e,
|
||||
)
|
||||
}
|
||||
} finally {
|
||||
connection.disconnect()
|
||||
this.connection = null
|
||||
stream.run("/sessions/$sessionId/events?after=$after", onOpen) { name, data ->
|
||||
// A named frame carries no payload and a data frame has no name, so this is one or
|
||||
// the other.
|
||||
if (name == RESET_EVENT) onReset()
|
||||
else if (data.isNotEmpty()) onEvent(parseSeqEvent(data))
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user