sinew_network library
SinewHttp (Dio), the auth layer, processApiCall, retry, polling and NetworkChecker.
Classes
- DeadlineExceeded
-
Why SinewTimeoutInterceptor cancelled a request: its deadline passed.
The guard turns a cancellation with this reason into a
RequestTimeOutException, never aCancelException. - ErrorBody
- What a backend's error body says: a message to show, and per-field validation messages.
- ErrorBodyReader
-
Reads a backend's error body. Each client runs its own reader on every
failed response, and the guard turns a readable ErrorBody.message into a
server message, and ErrorBody.fieldErrors into a
ValidationException. - FaultDecision
- What a fault does to a request, inside the auth layer: wait delay, then fail as a dropped connection (drop), answer status with body without reaching the network, or, with neither, send the request after the delay.
- HttpExchange
- One request and its response, as sent: after the auth layer and the host override. Values are not redacted; only devtools receives this, and it redacts before storing anything.
- NetworkChecker
- The device's connectivity, for the UI: an offline banner, a disabled submit button. It never decides a request's error type, which comes from the request's own failure: "connected to Wi-Fi" doesn't mean "the backend is reachable".
- Refreshed
- New tokens are stored: replay the waiting requests once.
- RefreshOutcome
- What a refresh attempt concluded.
- RefreshRejected
- The backend refused the refresh token: the session is over.
- RefreshResult
- What the backend answered to a refresh.
- RefreshTokens
- A new pair. With rotating refresh tokens, refresh replaces the stored one.
- RefreshTokenStore
- Where SessionTokenSource keeps the refresh token: the app adapts its secure store in a few lines.
- The refresh couldn't be completed (offline, a timeout, a 5xx): the session is kept.
- Rejected
-
The backend refused the refresh token, or the session ended while
refreshing. Waiting requests fail with
UnauthorizedException. - SessionTokenSource
- Sinew's ready TokenSource: the access token in memory, the refresh token in a RefreshTokenStore, and a refresh through a RefreshCall.
- SinewAuthInterceptor
-
The auth layer. For a request to the client's own host and port (from
options.baseUrl, or baseUrl), outside anonymousPaths, it attaches the current access token and handles a 401: - SinewConfig
- What an app configures for one backend. Build one client per backend from it, not one per endpoint.
- SinewErrorBodyInterceptor
-
Reads a failed response's body with reader and attaches it, with the
Retry-Afterwait, to theDioExceptionas anHttpStatusError, forprocessApiCallto classify. Any install order works: it only adds to the error, so an auth interceptor still sees the 401. - SinewHeadersInterceptor
-
Accept: application/json,Accept-Languagefrom locale and the defaults, read on every request so a language switch applies to the next one. A header the request set itself wins. - SinewHooksInterceptor
-
Applies hooks' faults and host override, and
SinewHttp.debugExpireToken. Installed after the auth interceptor, so a forced 401 runs the real refresh and a token is attached by the client's own host. - SinewHttp
-
The optional preset: a
Diowith every Sinew interceptor from one SinewConfig. Skip it to add only the interceptors an app needs to its ownDio: SinewTimeoutInterceptor, SinewHeadersInterceptor, SinewAuthInterceptor, SinewErrorBodyInterceptor and SinewLogInterceptor. - SinewHttpHooks
- Devtools' way into a client: fault injection, a host override and recording. Only devtools implements it. Every member has a default that leaves the request alone, and none is what a client gets without devtools, so production code paths never change.
- SinewLogInterceptor
- One line per exchange: method, host, path, status and duration, or the failure's type. Headers, bodies, query strings and error messages are never read, so no token or credential can reach the log. Install it last, so each replay after a refresh is its own line. Debug builds only.
- SinewRecorderInterceptor
- Hands every exchange to hooks once, with the URL the caller asked for. Installed before the auth interceptor: it sees a 401 before the auth layer replays it, and each replay is recorded on its own.
- SinewTimeoutInterceptor
-
A total deadline on every request: read for
GETandHEAD, write for the rest. Dio's ownreceiveTimeoutonly limits the gap between data chunks, so a response that trickles in never trips it; this cancels the request when the whole exchange runs past its deadline. A request's own sinewDeadline wins, for a slow endpoint. - TokenSource
-
Where a client's tokens live and how they refresh. Sinew's
SessionTokenSourceis the ready implementation; an app that writes its own must keep the clear contract. - The refresh couldn't be completed: offline, a timeout, a 5xx. The session is kept, and waiting requests fail with cause, so the page shows a retryable error instead of signing the user out.
Enums
- NetworkStatus
- Whether the device has a usable network.
Constants
- expiredToken → const String
-
An invalid token, sent once after
SinewHttp.debugExpireToken. - sinewDeadline → const String
-
The
extrakey for one request's own deadline, which wins over SinewTimeoutInterceptor's:Options(extra: {sinewDeadline: Duration(minutes: 2)}).
Functions
-
apiHandlers(
String module, String function) → List< ExceptionHandler> -
The HTTP handler table over Dio's errors, first match wins. Public, so an
app can guard a call Sinew doesn't wrap with
processCalland these handlers. -
defaultHttpLogger(
String line) → void -
Writes to the
dart:developerlog, under the nameSinewHttp. -
pinCertificateAuthorities(
Dio dio, Iterable< String> authorities) → void - Does nothing in the browser: the browser owns TLS and can't be told to trust only some authorities. See the IO version for what it does on Android, iOS and the desktop.
-
poll<
T> (String module, String function, Future< Result< block(), {required bool until(T data), Duration interval = const Duration(seconds: 2), Duration maxInterval = const Duration(seconds: 10), Duration timeout = const Duration(seconds: 60)}) → Future<T> >Result< T> > -
Calls
blockuntiluntilaccepts its data, for a backend process that finishes later (a payment, an export). The wait between calls starts atintervaland grows by 1.5× up tomaxInterval, with jitter so many clients don't call in step. -
processApiCall<
R> (String module, String function, Future< Envelope< call()) → Future<R> >Result< R> > -
The source guard for an HTTP call:
callreturns the response's envelope, and the result is aResultwith a classifiedSinewExceptionon failure. It never throws. -
processOptionalApiCall<
R> (String module, String function, Future< Envelope< call()) → Future<R> >Result< R?> > -
processApiCall for a lookup that may not exist: a 404 is
Success(null), every other failure is unchanged. -
retryWithBackoff<
T> (Future< Result< block(), {int maxAttempts = 3, Duration initialDelay = const Duration(milliseconds: 500), Duration maxDelay = const Duration(seconds: 5), bool retryIf(SinewException error)?}) → Future<T> >Result< T> > -
Runs
blockagain after a retryable failure, with exponential backoff and full jitter: before attemptn + 1it waits a random time up toinitialDelay × 2ⁿ, capped atmaxDelay. A 429 waits at least itsretryAfter; one asking for longer thanmaxDelayis returned at once, so the page shows the wait instead of a spinner.
Typedefs
- HttpLogger = void Function(String line)
- Where SinewLogInterceptor's lines go: pass the app's logger.
-
RefreshCall
= Future<
RefreshResult> Function(String refreshToken) -
The app's backend call that trades a refresh token for a new pair. It
must use a
Diowithout the auth interceptor, so a refresh never refreshes itself. A thrown failure counts as RefreshUnavailable.
Exceptions / Errors
- InjectedConnectionDrop
- A connection dropped by a devtools fault. Raised as a connection error, so the guard treats it as no connection, like a real one.