Files
LLeMbas-Android/app/src/main/java/eu/llembas/android/api/Identity.kt
T
HomerandClaude Fable 5.2 71b2e847cf Connect as the other LLeMbas clients do: address, identity, refused token, streams, words
- One address rule (api/Address.kt): scheme in any case, host lower-cased, path, query and
  fragment dropped; an http:// address is answered at the address step (this app needs https).
- User-Agent llembas-android/<version> on every request, and the same string as the device
  code's client_id (the server only stores and shows it).
- A 401 of the instance's own (WWW-Authenticate: Bearer realm="lembas") marks the instance
  whose token it was as signed out: nothing more is asked with it, its pages stay underneath a
  page that offers the sign-in in one step, and nothing else is forgotten. A 403 stays the
  server's sentence; a 401 passed on from a provider behind /v1 signs nobody out.
- Streams: 45 s of silence is a broken connection (the server's keepalive is every 15 s on all
  three routes); reconnect 1 s doubling to 60 s, jittered ±20 %, short again only after 30 s of
  health; a 429 waits for Retry-After.
- A sentence for each failure: unreachable, timeout, certificate not trusted, not LLeMbas,
  "the server answered N", too old, too new. Sign-in polls end by their real reason and survive
  a dropped network or a restarting server.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-01 19:22:40 +00:00

92 lines
4.1 KiB
Kotlin

package eu.llembas.android.api
import eu.llembas.android.BuildConfig
import okhttp3.Interceptor
import okhttp3.Response
/** This app's name to a server, with [version]: `llembas-android/1.2.3`. */
fun userAgent(version: String): String = "llembas-android/$version"
/**
* Who is asking: the `User-Agent` of every request this app makes (calls, streams, uploads and
* downloads) and the device code's `client_id` -- one string, so a server's list of devices and
* its logs name the same program.
*/
val USER_AGENT: String = userAgent(BuildConfig.VERSION_NAME)
/**
* The token a response says the instance no longer accepts, or null. Only the instance's own
* refusal counts: a 401 with its `WWW-Authenticate: Bearer realm="lembas"`, to a request that
* carried a token. A 401 passed on from somewhere else -- a speech provider behind `/v1`
* refusing the instance's key -- has no such header and signs nobody out; nor does a 403, which
* is the server's sentence about one thing that is not allowed.
*/
fun refusedToken(status: Int, challenge: String?, authorization: String?): String? {
if (status != 401 || challenge == null || authorization == null) return null
val asked = challenge.trim()
if (!asked.startsWith("Bearer", ignoreCase = true) || !asked.contains("realm=\"lembas\"", ignoreCase = true)) return null
if (!authorization.startsWith("Bearer ")) return null
return authorization.removePrefix("Bearer ").trim().ifEmpty { null }
}
/**
* Where a refused token is said: once for the process, heard by whoever keeps the instances
* (`LembasApp`). It is told the token, not "the instance in use" -- a request of another
* instance, or one that was under way while the person switched, signs out the instance whose
* token it carried and no other. Called on the thread the answer arrived on: the listener only
* hands it on.
*/
object RefusedTokens {
@Volatile
var heard: ((String) -> Unit)? = null
}
/** Names the app on every request, and listens for the instance refusing a token. */
internal class Identity : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request().newBuilder().header("User-Agent", USER_AGENT).build()
val response = chain.proceed(request)
refusedToken(response.code, response.header("WWW-Authenticate"), request.header("Authorization"))?.let { token ->
RefusedTokens.heard?.invoke(token)
}
return response
}
}
/** A `Retry-After` in seconds (the server sends a number), or null: absent, a date, or nonsense. */
fun retryAfterSeconds(header: String?): Long? = header?.trim()?.toLongOrNull()?.takeIf { it >= 0 }
/**
* The one reconnect schedule of every LLeMbas client: a pause of 1 second that doubles to 60,
* each within ±20 % so that the clients of a server that restarted do not all return at the same
* moment, and back to 1 second only after a connection that stayed healthy for 30 seconds -- a
* stream that opens, says one frame and breaks again is not a reason to ask every second.
*
* [jitter] gives a number in 0..1 (0.5 is no jitter).
*/
class Reconnect(private val jitter: () -> Double = { Math.random() }) {
private var step = FIRST_MS
/**
* The pause before the next opening. [healthyMs] is how long the connection that just ended
* had been carrying frames (0 for one that never did); [retryAfterMs] is what the server asked
* for on a 429, honoured when it is the longer of the two (up to [MOST_ASKED_MS]).
*/
fun pause(healthyMs: Long, retryAfterMs: Long = 0): Long {
if (healthyMs >= HEALTHY_MS) step = FIRST_MS
val now = step
step = (step * 2).coerceAtMost(LAST_MS)
val jittered = (now * (0.8 + 0.4 * jitter().coerceIn(0.0, 1.0))).toLong()
return maxOf(jittered, retryAfterMs.coerceIn(0L, MOST_ASKED_MS))
}
companion object {
const val FIRST_MS = 1_000L
const val LAST_MS = 60_000L
const val HEALTHY_MS = 30_000L
/** A server may ask for a long wait; a stream somebody watches is looked at again within five minutes. */
const val MOST_ASKED_MS = 300_000L
}
}