06 - Network
Concept
1. Why
Every app rebuilds the same HTTP setup. The hard parts are also the easiest to get wrong:
- Token refresh. Ten requests hit 401 at once, two refreshes race, and a rotating refresh token gets invalidated.
- Translating HTTP errors into something a page can act on.
- Timeouts on every request.
- Logging that never leaks a token.
- Never sending a token to a host it doesn't belong to.
sinew_network provides those parts as separate pieces the app installs on its own client when it needs them (Dio interceptors on Flutter, Ktor plugins on Kotlin), plus an optional preset that installs them all from one config, and the source guard processApiCall. The app keeps writing its API clients directly on Dio or Ktor. Sinew doesn't hide the HTTP library.
2. Shape
What the app supplies
SinewConfig(
baseUrl: String,
connectTimeout = 15s,
readTimeout = 30s, // reads
writeTimeout = 60s, // writes: repeating them is costly, so they get longer
logHttp = false, // debug builds only
anonymousPaths: Set<String> = {}, // never get a token, never trigger a refresh (sign-in, register, OTP, password reset, refresh).
// Matched relative to baseUrl's path: with baseUrl ".../v1", "/auth/login" matches "/v1/auth/login".
locale: () -> String, // read per request, sent as Accept-Language
defaultHeaders: () -> Map<String, String> = {}, // app version, API key, device id: read per request. Every name here is redacted by devtools.
errorBodyReader: ErrorBodyReader = ErrorBodyReader.default,
)
interface TokenSource {
accessToken(): String? // in memory
refresh(): RefreshOutcome // gets a new pair from the backend and stores it
clear() // the session ended: drop tokens, void any refresh still running, tell the app's session service
}
RefreshOutcome = Refreshed | Rejected | Unavailable(cause: SinewException)
// Rejected: the backend refused the refresh token, or the session ended while refreshing → the session is over;
// the source ends it itself, unless another session started meanwhile
// Unavailable: the refresh couldn't be completed (offline, timeout, 5xx) → the session is kept
// Sinew's ready implementation: the app supplies only the backend call and where the refresh token is kept
class SessionTokenSource(store: RefreshTokenStore, call: RefreshCall) : TokenSource
interface RefreshTokenStore { read(): String?, write(token: String), delete() } // the app adapts its SecureStore in one line
interface RefreshCall { refresh(refreshToken: String): RefreshResult } // the app's backend call, on a client without the auth layer
RefreshResult = Tokens(access: String, refresh: String) | Rejected | Unavailable(cause: SinewException)
interface ErrorBodyReader { read(status: Int, body: String?): ErrorBody? }
ErrorBody(message: String?, fieldErrors: Map<String, List<String>>?)
// default: reads JSON "message" and "errors" ({ field: [messages] }), returns null for anything unreadable
The app builds one client per backend (SinewHttp.dio(config, tokenSource) / SinewHttp.client(config, tokenSource)) and registers each under a name in its DI.
The layers, in order
Each request passes through these layers, outermost first. They're Dio interceptors on Flutter and Ktor plugins on Kotlin.
| # | Layer | Does |
|---|---|---|
| 1 | Timeout | Sets the deadline by method: reads use readTimeout, writes (POST, PUT, PATCH, DELETE) use writeTimeout. Every request has one. |
| 2 | Headers | Adds Accept: application/json, Accept-Language from locale(), and defaultHeaders(). |
| 3 | Auth | Adds Authorization: Bearer … for requests to its own host, except anonymous paths. Refreshes on 401 (rules below). |
| 4 | Fault injection | Devtools hook: forces a status, a delay or a dropped connection on a matching path. Does nothing without devtools. |
| 5 | Recorder | Devtools hook: records the request and response, redacted when recorded. Does nothing without devtools. |
| 6 | Redacting log | Logs method, path, status and duration when logHttp is on. Redacts Authorization, cookies and the bodies of auth endpoints. |
Fault injection sits inside auth, so a forced 401 exercises the real refresh path.
The auth layer
| Rule | Why |
|---|---|
| Single-flight: while a refresh runs, other 401s wait for its outcome instead of starting their own | Parallel refreshes race, and with rotating refresh tokens the second invalidates the first |
| A 401 for a request sent with an older token than the current one replays at once, without refreshing | A refresh already finished while that request was in flight. Refreshing again would break "exactly one refresh". |
| The refresh runs in a scope owned by the client, not by the first caller | If the first caller is cancelled (its page closed), the other waiters still get the outcome |
| A replay goes out through the auth layer's own path, and its errors are handed back to the caller like any other error | A failing replay can never wait on the auth layer that is waiting on it |
| A replayed request is marked. A second 401 on it fails instead of refreshing again. | Otherwise a replay waits on a refresh that waits on the replay: a deadlock |
| Anonymous paths never get a token and never trigger a refresh | A 401 there means "wrong credentials", not "expired token" |
| The refresh call itself bypasses the auth layer | A failing refresh must not refresh itself |
Rejected: every queued request fails with UnauthorizedException. The token source ends the session, only if it's still the session the refresh started in; the auth layer never calls clear() | The app's session service routes to sign-in. A refresh voided by another user's sign-in must not sign them out |
Unavailable keeps the session: queued requests fail with the cause (NoInternetConnectionException, RequestTimeOutException, ServiceUnavailableException) | A refresh that fails because the network or the backend is down must not sign the user out. The page shows a retryable error; the next request tries again. |
A token is attached only to requests whose host is the client's baseUrl host | An absolute URL to a CDN or a storage bucket never receives the user's token |
reset() on sign-out clears the queue and the refreshing flag, and clear() voids a running refresh through the session epoch | Nothing leaks into the next user's session, and a late refresh result is never stored |
A redirect to another host is followed without the Authorization header | A redirect can't carry the user's token off the backend's host |
Sign-out during a refresh: the session epoch
A refresh is a network call, so it can finish after the user signed out. If it then stored its new tokens, the user (or the next user on the device) would be silently signed back in. SessionTokenSource prevents that with a session epoch, a counter that clear() increments:
refresh():
epoch = currentEpoch // remember which session started this refresh
result = call.refresh(store.read())
lock:
if currentEpoch != epoch: return Rejected // signed out meanwhile: discard the result, store nothing
if result is Tokens: store.write(result.refresh), access = result.access, return Refreshed
…
clear():
lock: currentEpoch += 1, access = null, store.delete()
The check and the write happen under one lock, so no ordering of clear() and a finishing refresh can store tokens after sign-out. An app that writes its own TokenSource must give clear() the same guarantee; the rule is part of the interface's contract.
The source guard
processApiCall(module, function, call: () -> Envelope<R>): Result<R> =
message = ""
processCall(module, function, Repository, apiHandlers(module, function)) {
envelope = call() // a non-2xx status already threw, with the error body read by ErrorBodyReader
failure = envelope.failure() // null unless the app's envelope maps a failure inside a 2xx body
if failure != null:
throw failure.fieldErrors != null
? ValidationException(module, Repository, function, fieldErrors = failure.fieldErrors, message = serverOrLocal(failure.message, "sinew.error.validation"))
: ApiErrorException(module, Repository, function, message = serverOrLocal(failure.message, "sinew.error.generic"))
message = envelope.message() ?: ""
envelope.toDomain() // inside the guard: a mapping bug becomes ParseException
}.withMessage(message) // a success becomes Success(data, message); a failure is unchanged
processOptionalApiCall(module, function, call): Result<R?> // the same, except a 404 is success(null)
serverOrLocal(text, key) = text is not blank ? Server(text) : Local(key, fallback = English for key)
apiHandlers turns HTTP library errors into the Exception types, first match wins:
| # | Matches | Produces |
|---|---|---|
| 1 | a cancelled request (Flutter) | CancelException. On Kotlin, cancellation is rethrown before handlers run. |
| 2 | a connect, send or receive timeout | RequestTimeOutException |
| 3 | no connection, DNS failure, connection refused or reset | NoInternetConnectionException |
| 4 | a response with status 400 or 422 whose body has field errors | ValidationException |
| 5 | status 401 (after the auth layer gave up) | UnauthorizedException |
| 6 | 403, 404, 409 | ForbiddenException, NotFoundException, ConflictException |
| 7 | 429 | RateLimitedException, with retryAfter from the Retry-After header (seconds or an HTTP date) |
| 8 | 503, 504 / any other 5xx (500, 501, 502, 505…) | ServiceUnavailableException / ServerException |
| 9 | any other non-2xx status with a readable message | ApiErrorException |
| 10 | any other non-2xx status | UndefinedErrorResponseException |
| 11 | JSON that doesn't fit the DTO, including an enum value the DTO can't fall back from | ParseException |
| 12 | EnvelopeDataMissing (shared) | ParseException |
For rows 4–10, the client has already read the error body: when a response fails, its error layer runs the client's own errorBodyReader.read(status, body) and attaches the result to the error as an HttpStatusError(status, errorBody, retryAfter). The reader belongs to each client's SinewConfig, so the handlers never need it; they classify HttpStatusError by status. A readable message becomes Server(text); otherwise the type's local key is used.
Retry and polling
| Helper | Does | Rules |
|---|---|---|
retryWithBackoff(module, function, maxAttempts = 3, initialDelay = 500 ms, maxDelay = 5 s, retryIf = { it.retryable }, block) | Runs block (which returns a Result) again after a retryable failure, with exponential backoff and full jitter. A 429 waits at least retryAfter. When it gives up, it returns the last failure unchanged, so the user sees the real reason. | Idempotent requests only (reads, and writes carrying an Idempotency-Key). Retry in one layer only: never around a call that's already retried. |
poll(module, function, interval = 2 s, maxInterval = 10 s, timeout = 60 s, until: (T) -> Boolean, block) | Calls block until until(data) is true, growing the interval by 1.5× with jitter | Retryable failures keep polling until the timeout. A non-retryable failure stops at once and is returned. The timeout gives PollingTimeOutException. |
There's no automatic retry in the client. A failed request shows its error with a retry action, and the user decides.
Network checker
NetworkChecker { isOnline(): Boolean, changes: stream of NetworkStatus } NetworkStatus { Online, Offline }
It's for the UI (an offline banner, disabling a submit button). It never decides a request's error type. That comes from the request's own failure, because "connected to Wi-Fi" doesn't mean "the backend is reachable".
Environment rules
| Rule | Why |
|---|---|
The base URL and keys come from the app's build configuration, passed in SinewConfig | One source per environment. Nothing hard-coded in API clients. |
| Accepting invalid certificates is possible only through a debug-only option that release builds can't set | A leftover "accept any certificate" disables TLS checks in production |
| Certificate pinning, when an app wants it, is configured on the client's engine (each platform note says how) | One place, next to the rest of the client setup |
logHttp is off by default and must never be on in release builds | Logs end up in device logs and bug reports |
3. API
| Name | Signature (pseudocode) | For |
|---|---|---|
SinewConfig | as above | per-client configuration |
TokenSource | accessToken(): String?, refresh(): RefreshOutcome, clear() (voids a running refresh) | where tokens live, how they refresh |
SessionTokenSource | SessionTokenSource(store: RefreshTokenStore, call: RefreshCall) | the ready, epoch-guarded implementation |
RefreshTokenStore, RefreshCall, RefreshResult | as above | what the app supplies to SessionTokenSource |
RefreshOutcome | Refreshed | Rejected | Unavailable(cause) | what a refresh attempt concluded |
ErrorBodyReader, ErrorBody | read(status, body): ErrorBody?, ErrorBodyReader.default | reading the backend's error messages |
SinewHttp | Flutter SinewHttp.dio(config, tokenSource, extraInterceptors = []): Dio. Kotlin SinewHttp.client(config, tokenSource, engine = platform default, configure = {}): HttpClient. | building one client |
resetAuth | SinewHttp.resetAuth(client) | sign-out: clear the auth layer's queue and flag |
processApiCall | processApiCall(module, function, call: () -> Envelope<R>): Result<R> | the source guard for HTTP calls |
processOptionalApiCall | processOptionalApiCall(module, function, call): Result<R?> | 404 → null |
retryWithBackoff | as above, → Result<T> | explicit retries |
poll | as above, → Result<T> | bounded waiting for a backend process |
NetworkChecker | isOnline(), changes | connectivity for the UI |
| devtools hooks | RecorderLayer, FaultInjectionLayer, no-ops until devtools install them | see DevTools |
4. Build steps
SinewConfig,TokenSource,RefreshOutcome,ErrorBodyReaderwith its default, and tests that the default reader:- reads
messageanderrorsfrom an error body; - returns null for HTML, empty or non-JSON bodies.
- reads
- The timeout and headers layers, tested against a mock server:
- read and write deadlines;
Accept-Languagefollows a locale change between two requests;- default headers are read per request.
- The auth layer, test first, against a mock server that counts refresh calls. Tests:
- ten parallel 401s cause exactly one refresh, and all ten replay once;
Rejectedclears the session and fails all ten withUnauthorizedException;Unavailablekeeps the session and fails them with the cause;- a replayed request that gets 401 again fails without a second refresh;
- anonymous paths never get a token, including with a
baseUrlpath prefix (/v1); - sign-out while a refresh is running: the refresh's tokens are not stored, and waiters fail with
UnauthorizedException; - a 401 for a request sent with an older token replays without a second refresh;
- the first caller cancelled mid-refresh: the other waiters still get the outcome;
- a replay that returns 401, and one that returns 500, fail the caller without blocking later requests;
- a cross-host redirect drops
Authorization; - a request to another host never gets a token;
- sign-out during a refresh fails the queue and leaves no state behind.
processApiCallandprocessOptionalApiCall, with one test per handler row. That includes a 400/422 error body with and without field errors, an envelope whosefailure()is set (with and withoutfieldErrors),Success.messagefrommessage(), a 404 on the optional variant, a 429 withRetry-Afterin seconds and as a date, and an HTML 502 page.retryWithBackoffandpollwith a virtual clock. Tests:- attempts and delays;
- a non-retryable failure stops at once;
- a 429 waits at least
retryAfter; - the polling timeout.
NetworkCheckerper platform.- The redacting log, with a test that no logged line contains a bearer token or an auth endpoint's body.
Platforms
| Platform | Notes |
|---|---|
| Flutter web | Dio's browser adapter can't set a send timeout or pin certificates. Those settings are ignored there, as documented in the Flutter note. |
| Kotlin wasmJs | Ktor's JS engine follows the browser's own TLS and redirect handling. Pinning isn't available. |
Done when
- Every test in step 3 passes against a real HTTP mock on every target.
- Every handler row has a test that produces its exception type and code.
- No log line, in any test, contains a bearer token.
- A refresh failing because the backend is down never signs the user out.
5. Edge cases
| Case | Decided behavior |
|---|---|
| Ten requests get 401 at once | One refresh. The others wait and replay once with the new token, or all fail together. |
| The refresh token was rejected | Rejected: the session ends and every waiting request fails with UnauthorizedException. |
| The refresh call times out or gets a 503 | Unavailable: the session is kept, waiting requests fail with the cause, and the page shows a retryable error. |
| The user signs out while a refresh runs | The app calls resetAuth and tokenSource.clear(), which bumps the session epoch. When the refresh finishes, its tokens are not stored (the epoch moved), and waiting requests fail with UnauthorizedException. |
| A 401 arrives for a request sent before a refresh that has since finished | It replays with the new token. No second refresh. |
| The first request that triggered a refresh is cancelled | The refresh keeps running in the client's scope, and the other waiters get its outcome. |
| The replay itself fails (a second 401, a 500, offline) | The caller gets that failure. The auth layer is never blocked by its own replay. |
| A replayed request gets 401 again | It fails with UnauthorizedException. No second refresh. |
A timeout on a non-idempotent write (POST) | Returned as RequestTimeOutException, never retried automatically. The app decides; an Idempotency-Key makes a retry safe. |
| Offline at app start | Requests fail with NoInternetConnectionException. The network checker shows offline, and pages offer retry. |
A 429 with Retry-After | RateLimitedException.retryAfter is set, and the message names the wait. retryWithBackoff waits at least that long. |
| A redirect | GET redirects are followed within the same host. A redirect to another host is followed without the Authorization header. |
| A 5xx the table doesn't name (501, 505, 507…) | ServerException, with the backend's text if readable. Every 5xx is the backend's side, never ApiErrorException or UndefinedErrorResponseException. |
| A 408 status | Not a timeout: rows 2 and 3 cover the client's own deadlines and connection failures. The server answered, so it falls to row 9 or 10 (ApiErrorException with readable text, UndefinedErrorResponseException otherwise). |
| A TLS or certificate failure, including a pinning mismatch | UnexpectedException, reported. It's a security event, not "offline": showing the offline message would hide a misconfigured server or an interception. |
| A 502 whose body is an HTML page from a proxy | The error-body reader returns null, so the message is the local sinew.error.server. |
An error body with an empty message | Treated as unreadable: the local message for the status is shown. |
An envelope failure() with an empty message | The same: the local generic (or validation) message is shown. |
| The app's language changes mid-request | That request carries the old Accept-Language. The next one uses the new locale. |
| An absolute URL to another host (a CDN image, a pre-signed upload) | No Authorization header is attached. |
- Every 5xx except 503 and 504 is
ServerException, not only 500 and 502. A 408 status and TLS or certificate failures keep their catch-all rows: a 408 is a server answer (row 9 or 10), and a certificate failure isUnexpectedException, reported, on both platforms.
SinewConfigfails fast: a blankbaseUrl, a timeout that isn't positive, or an anonymous path without a leading/throws when the config is built, not on the first request.- The default
ErrorBodyReaderreads a JSON object only. A blankmessage, blank or non-string field messages and empty field lists are dropped; a field may hold one string instead of a list. An object with neither a message nor field errors,{}included, is unreadable (null). HttpStatusErroris internal. It only travels from the client toprocessApiCall, which turns it into aSinewException; apps never see it, and it can open up later if an app needs it. Its own message names only the status (HTTP 422), because an error body may hold personal data and exception messages reach logs and crash reports.- One
SinewConfigper backend, not per endpoint. Per-endpoint needs stay on the request:anonymousPathsfor sign-in and refresh, a header on the call, and a per-request timeout for a slow endpoint, which the timeout layer must leave alone. Retry-Afteraccepts delay-seconds and the IMF-fixdate form (Wed, 21 Oct 2015 07:28:00 GMT). A date in the past is a zero wait. The obsolete RFC 850 and asctime forms, a negative or fractional number, or anything else is treated as no header.- The log reads nothing secret: one line per exchange with the method, host, path, status and duration (or the failure's type). No header, body, query string or exception message, so a token can't reach it.
- Redirects: at most 5 hops, never from
httpstohttp, and a hop to another host or port dropsCookieas well asAuthorization. - A request's own timeout and headers win over the client's defaults, so a slow endpoint sets its deadline on that call.
- A rejected refresh is ended by the token source, not the auth layer. If the auth layer called
clear()onRejected, a refresh voided because another user signed in meanwhile would sign that user out.SessionTokenSourceends the session under its lock only when the epoch is still the one the refresh started in. Rejectedand a replayed 401 return the 401 response to the validator, which throwsHttpStatusError(401); the guard maps it toUnauthorizedException. There's no separate rejection type.SessionTokenSourceaddsstart(access, refresh)for sign-in (it voids any refresh from the previous session) andonSessionEnded, called onclear()and when the backend rejects the refresh token or none is stored: the only way the app learns the backend ended the session.- A refresh call that throws is
Unavailable, guarded asAUTH-R-REFRESH-…(an unexpected failure is reported), so a bug or a raw network error never signs the user out. - A 401 for a request whose token was cleared since it was sent (the user signed out mid-flight) returns as is, with no refresh: refreshing could bring the session back.
- A request with no token yet (a cold start with only a refresh token) still refreshes on 401 and replays. A request with its own
Authorizationis left alone: no token, no refresh. A one-shot streamed body still triggers the refresh but isn't replayed, so the app's retry carries the new token. - Anonymous paths match exactly, relative to
baseUrl's path (/auth/logindoesn't cover/auth/login/history), and another port is another host. - Installable pieces first, the preset second. Each layer (auth, headers, timeouts, the error-body reader, redirects, the log) is a public plugin or interceptor an app installs on its own client, alone or together, in any order the HTTP library allows.
SinewHttp.client(config, tokens)stays as an optional preset that installs them all from oneSinewConfig. An app that only wants the refresh logic installs only the auth layer. - The backend's base URL is declared once per client (
sinewBackend(url)on Kotlin), and the pieces that need it (request URLs, the token's host, anonymous paths) read it from there. - The guard walks a failure's causes. Engines wrap their failures, so a timeout or a lost connection anywhere in the chain classifies the failure, but a TLS or certificate failure anywhere in it means it's never "offline": a handshake cut by a reset is still a reported
UnexpectedException. - A plain client works too. Without the error-body reader, the HTTP library's own status errors (Ktor's
ResponseException, Dio'sbadResponse) are classified by status, with the local message, since the body can't be read there. - An envelope
failure()with an empty field map is anApiErrorException, not aValidationExceptionwith no fields. RefreshResult.from(result)turns a guarded refresh call into its answer, so aRefreshCallis only the HTTP call. A refusal (401, 403, 400 or 422 for OAuth'sinvalid_grant, a readable refusal, any other 4xx except 408 and 429) isRejected; everything else, a bug included, keeps the session asUnavailable.retryWithBackoffhas no module or function: its block already returns a guardedResult, so it never creates an exception.pollkeeps them, for itsPollingTimeOutException.- A 429 asking for longer than
maxDelayis returned at once, not waited out, so the page shows "Try again in 120 seconds" instead of a long spinner. WithinmaxDelay, the retry waits at leastretryAfter. polluses equal jitter (half the interval fixed, half random), so the interval still grows by 1.5× while clients spread out;retryWithBackoffkeeps full jitter. A slow call still running at the timeout is cut, and thePollingTimeOutExceptioncarries the last retryable failure as its cause.NetworkCheckerstartsOnlineuntil the platform first reports, so an app doesn't flash an offline banner at launch, and it has aclose(): monitoring runs from creation until then, one checker per app. A captive portal counts as offline where the platform can tell (Android's validation).- Auth is opt-out, through
anonymousPathsonly (decided 2026-10-12). No per-request "anonymous" flag: anonymous endpoints are few (sign-in, register, OTP, password reset, refresh), so listing them once beats tagging every other endpoint, and a new endpoint gets the token unless someone deliberately lists it. Considered against the opt-in, per-endpoint header markers of an earlier in-house Dio package. - Certificate pinning is part of the network package on both platforms: set once per backend, checked at the TLS handshake before anything is sent, a failure reported as
UnexpectedException, ignored in the browser. Pin an authority's or intermediate's key plus a backup, so a renewal doesn't lock users out. A pinning failure is never "offline", even when the HTTP library reports it behind another route's connection error.
Implementation
1. Why
This note builds the base network design on Ktor 3: one configured HttpClient per backend, the six layers as Ktor plugins, a custom auth plugin for the three-way refresh outcome, and processApiCall.
2. Shape
Building a client
Each layer is a public Ktor plugin, installed alone or together on the app's own HttpClient:
val http = HttpClient(OkHttp) {
expectSuccess = false // needed by sinewErrorBody
sinewBackend("https://api.shop.com/v1") // defaultRequest + the base Sinew's plugins read: written once
install(ContentNegotiation) { json(SinewJson) }
install(SinewHeaders) { locale = { settings.language }; defaults = { mapOf("X-App-Version" to version) } }
install(HttpTimeout); install(SinewTimeouts) { read = 30.seconds; write = 60.seconds }
install(SinewAuth) { tokenSource = tokens; anonymousPaths = setOf("/auth/login") }
HttpResponseValidator { sinewErrorBody() } // HttpStatusError for processApiCall
followRedirects = false; install(SinewRedirect) // optional: a hop limit, cookies dropped across hosts
install(SinewLog) { logger = HttpLogger { Timber.d(it) } } // debug only, installed last
}
| Plugin | Order | Fails fast when |
|---|---|---|
sinewBackend(url) | any: a config function, not a plugin, since it sets defaultRequest | the URL is blank |
SinewAuth | any: Ktor's redirect and validator always wrap it | no tokenSource, or an anonymous path without /; no base URL (from sinewBackend or its own baseUrl) on the first request |
SinewHeaders | any: ContentNegotiation adds Accept later, in the body phase | |
SinewTimeouts | any | a timeout isn't positive; HttpTimeout missing (on the first request) |
sinewErrorBody | any: it's part of Ktor's own validator, outermost | |
SinewRedirect | before SinewAuth, so each hop gets its own token decision | Ktor's HttpRedirect is on (followRedirects not false) |
SinewLog | last, for one line per hop and replay |
The optional preset installs all of them from one SinewConfig:
public object SinewHttp {
public fun client(config: SinewConfig, tokenSource: TokenSource, logger: HttpLogger = HttpLogger.Default, configure: HttpClientConfig<*>.() -> Unit = {}): HttpClient
public fun <T : HttpClientEngineConfig> client(config: SinewConfig, tokenSource: TokenSource, engine: HttpClientEngineFactory<T>, logger: HttpLogger = HttpLogger.Default, configure: HttpClientConfig<T>.() -> Unit = {}): HttpClient
public suspend fun resetAuth(client: HttpClient) // works on any client with SinewAuth installed
}
The auth plugin
Ktor's built-in Auth bearer provider refreshes once for concurrent 401s, but its refresh result is only "new tokens or nothing". Sinew's base contract needs three outcomes (Refreshed, Rejected, Unavailable(cause)), and a failure that carries its cause to every waiting request. So SinewAuth is a small custom plugin on Ktor's HttpSend interceptor:
internal val SinewAuth = createClientPlugin("SinewAuth", ::SinewAuthConfig) {
val cfg = pluginConfig
val refresher = SingleFlightRefresher(cfg.source, scope = CoroutineScope(SupervisorJob())) // owned by the client, not by the first caller
client.plugin(HttpSend).intercept { request ->
val path = request.url.encodedPath.removePrefix(cfg.baseUrl.encodedPath.trimEnd('/')) // anonymous paths are relative to baseUrl's path
val anonymous = path in cfg.anonymousPaths
val ownHost = request.url.host == cfg.baseUrl.host
val sentWith = if (!anonymous && ownHost) cfg.source.accessToken()?.also { request.bearerAuth(it) } else null
val call = execute(request)
if (call.response.status != HttpStatusCode.Unauthorized || sentWith == null || request.attributes.contains(Replayed)) return@intercept call
val outcome = if (cfg.source.accessToken() != sentWith) RefreshOutcome.Refreshed // a refresh already finished meanwhile
else refresher.refresh() // joins the running refresh, or starts one
when (outcome) {
RefreshOutcome.Refreshed -> execute(request.apply {
attributes.put(Replayed, Unit); headers.remove(HttpHeaders.Authorization); cfg.source.accessToken()?.let { bearerAuth(it) } })
RefreshOutcome.Rejected -> call // the 401: the validator throws, the guard maps it
is RefreshOutcome.Unavailable -> throw outcome.cause // already an SinewException: passes through
}
}
}
| Part | Does |
|---|---|
SingleFlightRefresher | holds a Mutex and the in-flight Deferred<RefreshOutcome>, started with scope.async. Waiters await it. Cancelling a waiter cancels only its own wait, never the refresh. resetAuth cancels the scope's children and starts fresh. |
| The sent-token check | a 401 for a request sent with an older token replays at once, so ten requests produce exactly one refresh even when some 401s arrive after it finished |
| The replay | goes through execute like any request. Its failure (a second 401, a 500) is returned to its caller; nothing waits on it, so it can't block the plugin. |
Rejected | returns the 401 response; the source has already ended the session if it was still current |
The refresh call itself is made by the TokenSource. With Sinew's SessionTokenSource, the app's RefreshCall uses a separate HttpClient without SinewAuth, so a refresh can never refresh itself.
SessionTokenSource and the session epoch
public class SessionTokenSource(
private val store: RefreshTokenStore,
private val call: RefreshCall,
private val onSessionEnded: suspend () -> Unit = {}, // on clear(), and when the backend rejects the refresh token
) : TokenSource {
private val mutex = Mutex()
private var epoch = 0L
private val access = AtomicReference<String?>(null)
override fun accessToken(): String? = access.load()
public suspend fun start(accessToken: String, refreshToken: String): Unit = mutex.withLock { epoch++; store.write(refreshToken); access.store(accessToken) }
override suspend fun refresh(): RefreshOutcome {
val (started, refreshToken) = mutex.withLock { epoch to store.read() }
if (refreshToken == null) return endIfStill(started)
val answer = when (val r = processCall("AUTH", "REFRESH", Repository, emptyList()) { call.refresh(refreshToken) }) {
is Result.Failure -> return RefreshOutcome.Unavailable(r.error) // a throw keeps the session
is Result.Success -> r.data
}
return when (answer) {
is RefreshResult.Unavailable -> RefreshOutcome.Unavailable(answer.cause)
RefreshResult.Rejected -> endIfStill(started) // ends the session only if it's still this one
is RefreshResult.Tokens -> mutex.withLock {
if (epoch != started) return@withLock RefreshOutcome.Rejected // signed out or in meanwhile: store nothing
store.write(answer.refresh); access.store(answer.access); RefreshOutcome.Refreshed
}
}
}
override suspend fun clear() { mutex.withLock { epoch++; access.store(null); store.delete() }; onSessionEnded() }
}
Redirects
SinewRedirect follows 301, 302, 303, 307 and 308 for GET and HEAD only, up to 5 hops. Each hop is a new request through HttpSend, so SinewAuth attaches the token only when the hop's host is the client's own. A cross-host hop never carries Authorization.
Timeouts and headers
| Plugin | Does |
|---|---|
SinewTimeout | For GET/HEAD, sets requestTimeoutMillis and socketTimeoutMillis to readTimeout. For other methods, writeTimeout. connectTimeoutMillis is always connectTimeout. |
SinewHeaders | Adds Accept: application/json, Accept-Language: locale(), and defaultHeaders(), read on every request |
SinewHooks | Devtools' hook point, installed inside SinewAuth: it applies a fault (FaultDecision: a delay, a dropped connection, or a status answered without the network through HttpClientCall's @InternalAPI constructor), the host override, and debugExpireToken, then hands the raw exchange to hooks.record. With SinewHttpHooks.None it only serves debugExpireToken. |
The guard and the error body
Reading a response body is a suspend call, but handlers are plain functions. So the client's response validator reads a failed response's body with its own errorBodyReader and throws a plain HttpStatusError(status, errorBody, retryAfter). The guard's handlers only classify it by status:
public suspend fun <R> processApiCall(module: String, function: String, call: suspend () -> Envelope<R>): Result<R> {
var message = ""
return processCall(module, function, ExceptionLayer.Repository, apiHandlers(module, function)) {
val envelope = call() // a failed status already threw HttpStatusError
envelope.failure()?.let { throw it.toSinewException(module, function) } // ValidationException or ApiErrorException
message = envelope.message().orEmpty()
envelope.toDomain()
}.withMessage(message)
}
apiHandlers follows the base table. The connection and timeout predicates are expect functions, because each engine throws its own types:
| Platform | No connection | Timeout |
|---|---|---|
| android, jvm (OkHttp) | UnknownHostException, ConnectException, NoRouteToHostException, SocketException | HttpRequestTimeoutException, SocketTimeoutException, ConnectTimeoutException |
| ios (Darwin) | DarwinHttpRequestException with NSURLErrorNotConnectedToInternet, CannotFindHost, CannotConnectToHost, NetworkConnectionLost | the same with NSURLErrorTimedOut, plus Ktor's timeout types |
| wasmJs (Js) | a fetch TypeError while navigator.onLine is false | Ktor's timeout types |
Some engines report a timeout as a CancellationException. processCall tells the two apart by checking whether the caller is still active (see Error Model): if it is, the "cancellation" is classified like any other failure, and the timeout predicates above turn it into RequestTimeOutException.
Unknown enum values. SinewJson sets coerceInputValues = true, and DTO enum properties declare a default (val status: OrderStatusDto = OrderStatusDto.Unknown), so an unknown value becomes Unknown instead of failing the whole response. An enum inside a list has no property default; its DTO uses a custom serializer that falls back to Unknown.
Network checker
| Platform | Implementation |
|---|---|
| Android | ConnectivityManager.registerDefaultNetworkCallback, online when the network has NET_CAPABILITY_VALIDATED |
| iOS | NWPathMonitor, online when the path status is satisfied |
| JVM | polls NetworkInterface every 5 seconds for an interface that's up and not loopback |
| wasmJs | navigator.onLine plus the online and offline window events |
Retry and polling
retryWithBackoff and poll use delay, so tests run them on virtual time with runTest. Full jitter uses Random.nextLong(0, backoff).
Certificate pinning and TLS
Pins are SHA-256 public-key hashes (sha256/…) for the base URL's host, set once in the config; the preset applies them on the engine:
SinewConfig(baseUrl = "https://api.shop.com/v1", …, certificatePins = setOf("sha256/…intermediate", "sha256/…backup"))
// a hand-built client: engine { pinCertificates("api.shop.com", pins) } (OkHttpConfig and DarwinClientEngineConfig)
| Engine | How | When the pin is checked |
|---|---|---|
| OkHttp (Android, JVM) | CertificatePinner | during the handshake, before the request is written |
| Darwin (iOS) | Ktor's port of CertificatePinner, through handleChallenge | at URLSession's authentication challenge, before the request is sent |
| Js (wasm) | none: the browser owns TLS | ignored, documented |
any other (MockEngine) | none | building the client throws, so a pinned client never goes unpinned |
A TLS or certificate failure (OkHttp's SSLException family, Darwin's NSURLErrorServerCertificate* and NSURLErrorSecureConnectionFailed) matches neither the no-connection nor the timeout predicate, so it becomes UnexpectedException and is reported, as on Flutter. It's a security event, never shown as "offline".
Sinew offers no option to accept invalid certificates. A local-development setup that needs it configures the engine in the app's debug source set only, so release code can't contain it.
3. API
| Name | Kotlin |
|---|---|
SinewHttp.client | as above, returns HttpClient |
SinewHttp.resetAuth | public suspend fun resetAuth(client: HttpClient) |
SinewHttpHooks | public interface SinewHttpHooks { fun attached(client); fun detached(client); fun hostOverride(): String?; suspend fun fault(method: String, url: Url): FaultDecision?; fun record(exchange: HttpExchange) }, every member defaulted, None |
SinewHttp.debugExpireToken | public fun debugExpireToken(client: HttpClient): the next request that carries a token sends sinew-devtools-expired; SinewAuth itself is unchanged |
processApiCall, processOptionalApiCall | public suspend fun <R> as above |
ErrorBodyReader | public fun interface ErrorBodyReader { public fun read(status: Int, body: String?): ErrorBody? }, Default |
retryWithBackoff, poll | public suspend fun <T> |
NetworkChecker | public interface NetworkChecker { public val status: StateFlow<NetworkStatus> }, NetworkChecker.create(context) |
NetworkChecker exposes a StateFlow, so isOnline() is status.value == Online.
4. Build steps
SinewJson,SinewTimeout,SinewHeaders, tested with Ktor'sMockEngine:- per-method timeouts;
Accept-Languagechanges between two requests;- default headers.
SingleFlightRefresherandSinewAuth, test first withMockEngineandFakeTokenSource. These are the Review Focus 1 tests:- ten parallel 401s cause one refresh;
Rejectedfails all ten withUnauthorizedException;Unavailablefails all ten with its cause and keeps the session;- a replayed 401 fails without a second refresh;
- a replay that returns 500 fails its caller, and the next request still works;
- a 401 for a request sent with an older token replays without refreshing;
- the first caller cancelled mid-refresh: the other nine still get
Refreshed; signOutMidRefresh:clear()while the refresh is suspended; the refresh's tokens are not stored, all waiters fail withUnauthorizedException;- anonymous paths (with a
/v1base path) and other hosts never get a token.
SessionTokenSourcealone: the epoch check under the lock, in every interleaving ofrefreshandclear(driven by a test dispatcher).SinewRedirect: a same-host redirect keeps the token, a cross-host one drops it, aPOSTisn't followed.processApiCallwith one test per handler row (includingdata: null→ParseExceptionreported, and an unknown enum value →Unknown), plus the platform predicate tests on each target, plus an engine-wrapped timeout classified asRequestTimeOutException.- The network checker per platform (instrumented on Android, simulator on iOS, browser test on wasm).
retryWithBackoffandpollon virtual time.
Done when
- Every test in step 2 passes on all four targets.
- No test log contains a bearer token.
5. Edge cases
| Case | Decided behavior |
|---|---|
Ktor's Auth plugin installed by the app as well | Not supported. It would compete with SinewAuth over 401s. |
| A request body that can't be replayed (a one-shot stream upload) | Not replayed after a refresh: it fails with UnauthorizedException, and the app retries the upload. |
| The refresh token call uses the same client | It must not. The TokenSource uses its own client without SinewAuth, documented in the sample. |
A HEAD request | Uses the read timeout. |
- A custom
SinewAuthplugin instead of Ktor'sAuthbearer provider, because the three-wayRefreshOutcomeand the shared failure cause can't be expressed with it. - Sinew validates responses itself (
expectSuccess = falseplus a validator) and follows redirects itself, so the order relative toSinewAuthis known. Verified at S3 (see below). - No insecure-certificate option in Sinew. The base note allowed a debug-only option. On Kotlin, the app's debug source set configures the engine itself, which keeps the option out of Sinew's API entirely.
NetworkChecker.statusas aStateFlow, the Kotlin idiom for "current value plus changes".
SinewConfigis a plain class, not adata class: it holds lambdas (locale,defaultHeaders), whose equality would be meaningless.TokenSource.clear()issuspend, so an implementation can take the sameMutexasrefresh(). Its KDoc states the epoch contract for app-written sources.HttpStatusErrorisinternal, withretryAfteras akotlin.time.Duration, parsed by an internalparseRetryAfter(value, now)with kotlinx-datetime'sRFC_1123format, so the clock is injectable in tests.- The validator wraps every Sinew plugin, verified in Ktor 3.6.0's source.
HttpCallValidatoris a default plugin, installed before any user plugin, andHttpSendmakes the first-registered interceptor the outermost. So it sees only the final response, after redirects and (from #19) afterSinewAuth. The pipeline is engine-independent, and the tests run it onMockEngineon all four targets. - Two
clientoverloads. WithHttpClientConfig<*>,configurecan't callengine { }, so certificate pinning wouldn't compile. The platform-engine overload covers common code; the typed one takesOkHttp,DarwinorJsand reaches its config. - API paths are relative (
get("orders")). The client adds a trailing slash tobaseUrl; a leading/would replace the base path. - The request's own settings win: a
timeout { }on the call is kept, and a header it sets isn't overwritten. An ownAcceptalso excludes JSON fromContentNegotiation, which would otherwise add it beside. SinewRedirectis Sinew's own, because Ktor'sHttpRedirecthas no hop limit. It follows Ktor's rules (GET/HEAD only, nohttps→http), adds the 5-hop limit, dropsCookieas well asAuthorizationacross hosts, counts another port as another host, and reuses the caller's request builder so a hop stays tied to the caller's cancellation.SinewLogreplaces Ktor'sLogging: one line per exchange (GET api.example.com/v1/orders → 200 (84 ms), or the failure's type), never a header, a body, a query string or an exception message. Nothing secret is read, so nothing needs redacting. The app passes anHttpLogger.tokenSourceand devtoolshooksarrive later:tokenSourcewithSinewAuth(#19),hookswith DevTools (S6,SinewHttp.client(…, hooks = …)).- One hooks plugin, not two. Faults, the host override, token expiry and recording share one
SinewHooksplugin insideSinewAuth: recording sits around the fault so a faked answer is recorded too, and both see the token the auth layer attached. A dropped connection is an internalInjectedConnectionDropthatisNoConnectionFailurerecognizes, so it maps toNoInternetConnectionExceptionon every engine. SinewAuthis anon(Send)client plugin, installed insideSinewRedirect. TheSingleFlightRefresherlives in the client's attributes, soresetAuth(client)finds it;onClosecancels its scope. Refreshes run in aSupervisorJobscope onDispatchers.Default, injectable internally so tests run every interleaving on the test dispatcher.resetAuthcancels the running refresh and completes its waiters asRejectedat once, rather than leaving them to wait for a backend that no longer matters.FakeTokenSourceis insinew-testing: counts refreshes and clears, rotatestoken-1→token-2, and takes anonRefreshlambda to gate a refresh on aCompletableDeferred. Like a real source, aRejectedrefresh ends its session.- Testing: every Review Focus 1 case on
MockEnginewith the engine and the refresher on oneStandardTestDispatcher, on all four targets, plus a JVM test with fifty requests on real threads, twenty rounds, one refresh each. - Plugins first, preset second (decided 2026-10-11).
SinewAuth,SinewHeaders,SinewTimeouts,SinewRedirect,SinewLogandsinewErrorBodyare public and installable alone;SinewHttp.clientis an optional preset built from them. Ktor installs its ownHttpRedirectand validator before any user plugin, so with Ktor's redirect each hop already passes throughSinewAuth, and Ktor dropsAuthorizationacross hosts itself.SinewRedirectis opt-in, for the hop limit and dropped cookies. - The base URL is written once, with
sinewBackend(url). Ktor keepsdefaultRequest's URL in a lambda no plugin can read back, so a hand-built client would otherwise repeat it forSinewAuth.sinewBackendsetsdefaultRequest(with the trailing slash) and records the URL in the client's attributes.SinewAuthreads it on the first request, so the two may be declared in any order; its ownbaseUrloverrides it for a client that setsdefaultRequestitself.SinewConfigfeeds only the preset. - The "token already changed" check runs inside the refresher's lock (
refresh(sentWith)), the same lock that clears a finished refresh. Checked outside it, a 401 that read the old token just before a refresh stored the new one could reach the refresher just after it cleared, and start a second refresh. CI's real-thread test caught that once; the test now refreshes with no delay over 200 rounds and fails without the fix. apiHandlers(module, function)is public, for an app guarding a callprocessApiCalldoesn't wrap.processOptionalApiCallshares one implementation with a 404-is-null switch; a 404 is caught before the handlers run.- Three
expectpredicates per platform:isEngineTimeout(OkHttp's whole-callInterruptedIOException("timeout"), Darwin'sNSURLErrorTimedOut; Ktor's own timeout types are common),isNoConnection(OkHttp'sUnknownHostException,ConnectException,NoRouteToHostException,SocketException; Darwin's not-connected, host and lost-connection codes; on wasm, any non-HTTP failure whilenavigator.onLineis false) andisSecurityFailure(SSLException,CertificateException; Darwin codes -1206 to -1200; nothing on wasm, where the browser reports TLS like anyfetchfailure). Each target has its own predicate tests (jvmTest,androidHostTest,iosTest,wasmJsTest). - Ktor's
ResponseException(expectSuccess = truewithoutsinewErrorBody) becomes anHttpStatusErrorwith no body, so it's classified by status andRetry-After. pollruns insidewithTimeoutOrNull, so its timeout follows virtual time in tests and cancels a call still in flight. Both helpers take an internalRandom, so tests assert every delay exactly with "always longest" and "always shortest" stand-ins.NetworkChecker : AutoCloseable, made withNetworkChecker.create(PlatformContext). Android needsACCESS_NETWORK_STATE, declared insinew-network's own manifest so apps get it merged; online isNET_CAPABILITY_INTERNETandNET_CAPABILITY_VALIDATEDon the default network. iOS runsNWPathMonitoron its own serial queue. The JVM pollsNetworkInterfaceonDispatchers.IO. wasm talks towindowthroughjs()interop, because Kotlin 2.4 movedkotlinx.browserout of the standard library.sinew-testinggainsFakeNetworkChecker.- Testing per platform: the Android status rule on the host; an instrumented test (
androidDeviceTest, AndroidX Test runner 1.7.0 and ext-junit 1.3.0) that turns Wi-Fi and data off and on withsvcthroughUiAutomation, run on an emulator locally until the CI device job (#30) exists; the real monitor on the iOS simulator; the window's events in the browser; the JVM poller on virtual time. - A poller under test gets its own
TestCoroutineScheduler, advanced by hand, notrunTest's.runTestdrains its clock when it ends, so a poller thatclose()failed to stop keeps scheduling its next tick and the test hangs instead of failing. A mutation check found this by hanging for an hour. - Certificate pinning is a Sinew API (#63, added after S3 for parity with Dart #20):
SinewConfig.certificatePins, validated up front, applied by the preset on OkHttp and Darwin, withpinCertificates(host, pins)for hand-built clients. Kotlin pins public keys (a leaf, an intermediate or a root), finer than Dart, which can only pin whole authorities. - A pinning failure behind a refused connection is still not "offline".
localhost(and any dual-stack host) has two addresses; when one refuses the connection and the other fails the pin, OkHttp throws the first error and attaches the others as suppressed. The security check now walks suppressed exceptions too. A real-server test hit this, classified asNoInternetConnectionExceptionbefore the fix. - Testing: on the JVM, a real HTTPS
MockWebServerwith certificates fromokhttp-tls(test-only, 5.5.0 as Ktor brings): matching root, leaf and backup pins reach it; a wrong pin fails with zero requests at the server. On iOS, Gradle's headless simulator test runner can't verify public certificates (every TLS request fails with-1200), so the tests check that the preset and the helper install Ktor's pinner; a public-site test runs only where verified TLS works and says when it skips. - Tests of a guarded failure return the call's status, not
error("unreachable"): that throw would itself become theUnexpectedExceptionthe test expects, so the test would pass even if the request got through. A mutation (Darwin's pinner removed) exposed it; the same pattern was fixed in Dart's TLS tests.