Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions docs/internal/development/guide/02-packages/06-network.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,7 @@ public class SessionTokenSource(
|---|---|
| `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 |
| `SinewFaults` / `SinewRecorder` | Call `hooks`. `SinewHttpHooks.None` makes them do nothing. |
| `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 {#kotlin-the-guard-and-the-error-body}

Expand Down Expand Up @@ -516,7 +516,8 @@ Sinew offers **no option** to accept invalid certificates. A local-development s
|---|---|
| `SinewHttp.client` | as above, returns `HttpClient` |
| `SinewHttp.resetAuth` | `public suspend fun resetAuth(client: HttpClient)` |
| `SinewHttpHooks` | `public interface SinewHttpHooks { public suspend fun fault(request: HttpRequestData): FaultDecision?; public fun record(exchange: HttpExchange) }`, `None` |
| `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>` |
Expand Down Expand Up @@ -579,7 +580,8 @@ Sinew offers **no option** to accept invalid certificates. A local-development s
- **The request's own settings win**: a `timeout { }` on the call is kept, and a header it sets isn't overwritten. An own `Accept` also excludes JSON from `ContentNegotiation`, which would otherwise add it beside.
- **`SinewRedirect` is Sinew's own**, because Ktor's `HttpRedirect` has no hop limit. It follows Ktor's rules (GET/HEAD only, no `https` → `http`), adds the 5-hop limit, drops `Cookie` as well as `Authorization` across hosts, counts another port as another host, and reuses the caller's request builder so a hop stays tied to the caller's cancellation.
- **`SinewLog` replaces Ktor's `Logging`**: 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 an `HttpLogger`.
- **`tokenSource` and devtools `hooks` arrive later**: `tokenSource` with `SinewAuth` (#19), `hooks` with DevTools (S6).
- **`tokenSource` and devtools `hooks` arrive later**: `tokenSource` with `SinewAuth` (#19), `hooks` with DevTools (S6, `SinewHttp.client(…, hooks = …)`).
- **One hooks plugin, not two.** Faults, the host override, token expiry and recording share one `SinewHooks` plugin inside `SinewAuth`: 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 internal `InjectedConnectionDrop` that `isNoConnectionFailure` recognizes, so it maps to `NoInternetConnectionException` on every engine.
- **`SinewAuth` is an `on(Send)` client plugin**, installed inside `SinewRedirect`. The `SingleFlightRefresher` lives in the client's attributes, so `resetAuth(client)` finds it; `onClose` cancels its scope. Refreshes run in a `SupervisorJob` scope on `Dispatchers.Default`, injectable internally so tests run every interleaving on the test dispatcher.
- **`resetAuth` cancels the running refresh and completes its waiters as `Rejected`** at once, rather than leaving them to wait for a backend that no longer matters.
- **`FakeTokenSource` is in `sinew-testing`**: counts refreshes and clears, rotates `token-1` → `token-2`, and takes an `onRefresh` lambda to gate a refresh on a `CompletableDeferred`. Like a real source, a `Rejected` refresh ends its session.
Expand Down Expand Up @@ -621,8 +623,6 @@ abstract final class SinewHttp {
final common = [
SinewTimeoutInterceptor(config), // a total deadline per request, by method
SinewHeadersInterceptor(config), // Accept, Accept-Language, default headers
SinewFaultInterceptor(hooks), // devtools; no-op by default
SinewRecorderInterceptor(hooks), // devtools; no-op by default
if (config.logHttp) SinewLogInterceptor(), // redacted
...extraInterceptors,
];
Expand All @@ -640,6 +640,15 @@ abstract final class SinewHttp {
}
```

#### Devtools hooks {#dart-devtools-hooks}

| Interceptor | Where | Does |
|---|---|---|
| `SinewRecorderInterceptor(dio, hooks:, defaults:)` | **before** `SinewAuthInterceptor` | Stamps the request, then hands each exchange to `hooks.record` from `onResponse` and `onError`. Dio runs every phase in list order, and the auth interceptor resolves a refreshed request from its `onError`, which skips every error interceptor after it; before it, the original 401 is recorded, and the replay is recorded on its own. |
| `SinewHooksInterceptor(hooks:)` | **after** `SinewAuthInterceptor` | Applies `debugExpireToken`, the host override and a `FaultDecision`. A forced status is rejected with `callFollowingErrorInterceptor`, so the auth interceptor sees a forced 401 like a real one. A drop is a `connectionError`, so `NoInternetConnectionException`. |

`SinewHttp.dio(…, hooks:)` installs both; with `SinewHttpHooks.none` they do nothing but `debugExpireToken`. Dio has no close callback, so devtools can't tell a closed `Dio` apart: replaying through one fails, and the failure is in the replay's record.

#### The auth interceptor {#dart-the-auth-interceptor}

`SinewAuthInterceptor` is a plain `Interceptor`, **not** a `QueuedInterceptor`. A queued interceptor that awaits a replay on the same `Dio` deadlocks when the replay itself fails: the replay's error queues behind the handler that's waiting for it. Single-flight comes from a shared `Completer` instead; Dart runs one event at a time, so no lock is needed around it.
Expand Down
14 changes: 10 additions & 4 deletions docs/internal/development/guide/02-packages/11-dev-tools.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ SinewDevTools(
| **Local DB** | Group | `InspectableStore`s the app registers (one per DAO it wants visible) | Read-only. |
| **Expire Access Token** | Action | the auth layer | The next request goes out with an invalid token, so the real 401 → refresh path runs. Non-production only. |
| **Fault Injection** | Page | fault rules applied in the network stack | Rules live in memory only and are gone after a restart. See below. |
| **API Host** | Page | the hosts listed in the app's config | Never compiled into a production flavor. The active host shows in the ribbon. |
| **API Host** | Page | the hosts listed in the app's config | Never compiled into a production flavor. The active host shows in the ribbon. Only a listed host can be chosen; a remembered host the app no longer lists is forgotten. Requests for the client's own host move to the chosen base, keeping the path below the base path, after the auth layer attached the token. |
| **Changelog** | Page | text the app supplies | |

#### Redaction, when recording
Expand Down Expand Up @@ -166,7 +166,10 @@ FaultRule(method: String? = null, pathPattern: String, status: Int? = null, dela

| Rule | Why |
|---|---|
| Rules apply **inside** the auth layer | A forced 401 runs the real refresh path. A forced 503 on the refresh call previews the "backend down, session kept" screen. |
| Rules apply **inside** the auth layer | A forced 401 runs the real refresh path. A forced 503 on the refresh call previews the "backend down, session kept" screen; the refresh client needs the same hooks for that. |
| A path pattern matches the **end** of the path, at a `/`, and `*` matches any run of characters | `/orders` catches `/v1/orders` without knowing the base path, and not `/v1/myorders` |
| When several rules match, the most recently added wins | A tester narrows a broad rule by adding a specific one |
| A dropped connection is classified as no connection, like a real one | The app shows its offline state, which is what a tester is checking |
| Rules are in memory only, gone after a restart | A rule forgotten on a test device can't break the next day's session |
| The ribbon shows "faults on" while any rule is active | A tester always knows the app is being lied to |

Expand Down Expand Up @@ -390,7 +393,9 @@ As the base note. Kotlin specifics:
| `NetworkRecorder` | `NetworkRecorder(capacity = 200, redaction = Redaction.Default)`, `records: StateFlow<List<NetworkRecord>>` (newest first), `record(NetworkExchange): NetworkRecord`, `recordCacheServe(key, source, body, contentType, at)`, `clear()` |
| `NetworkExchange` | the raw exchange the hooks hand over: method, URL, headers and bodies before redaction, status, `startedAt`, `duration`, `error`, `clientHeaders` (the client's `defaultHeaders` names), `isReplay` |
| `ExceptionRecorder` | `ExceptionRecorder(capacity = 50, dedupeWindow = 2.seconds, redaction, clock: kotlin.time.Clock)`, `records: StateFlow<List<ExceptionRecord>>`, `record(error: Throwable, source = Reported)`, `clear()` |
| `DevTools` | `object DevTools { network; exceptions; coroutineHandler; captureUncaughtErrors(); clearUserData() }`; `open()`/`close()`/`replay` arrive with the UI and hooks |
| `DevTools` | `object DevTools { network; exceptions; faults; hosts; httpHooks; coroutineHandler; captureUncaughtErrors(); clearUserData(); canReplay(record); suspend replay(record); expireAccessToken() }`; `open()`/`close()` arrive with the UI |
| `FaultRule`, `FaultRules` | `FaultRule(method, pathPattern, status, delay, drop, body)` (validated), `matches(method, path)`; `FaultRules.active: StateFlow`, `add`, `remove`, `clear`, `match` |
| `HostOverride` | `hosts`, `current: StateFlow<String?>`, `suspend configure(hosts, store: KeyValueStore?)`, `suspend select(host?)` |
| `DevTools.replay` | `public suspend fun replay(record: NetworkRecord)`, through the `HttpClient` the hooks were installed in; the no-op returns at once |

### 4. Build steps {#kotlin-4-build-steps}
Expand Down Expand Up @@ -501,7 +506,8 @@ EXIF, camera and map playgrounds are separate packages. Flutter links every plug
| `RecordedBody` | `sealed`: `NoBody`, `TextBody(text, size:, truncated:, masked:)`, `BinaryBody(contentType, size)` |
| `NetworkRecorder` | `NetworkRecorder({int capacity = 200, Redaction? redaction})`, `ValueListenable<List<NetworkRecord>> records` (newest first, unmodifiable), `record(NetworkExchange)`, `recordCacheServe(key, source, {body, contentType, at})`, `clear()` |
| `ExceptionRecorder` | `ExceptionRecorder({capacity = 50, dedupeWindow = Duration(seconds: 2), redaction, DateTime Function()? clock})`, `records`, `record(Object error, StackTrace? stack, {source})`, `clear()` |
| `DevTools` | `abstract final class` with `static network`, `exceptions`, `captureUncaughtErrors()`, `clearUserData()` |
| `DevTools` | `abstract final class` with `static network`, `exceptions`, `faults`, `hosts`, `httpHooks`, `captureUncaughtErrors()`, `clearUserData()`, `canReplay(record)`, `replay(record)`, `expireAccessToken()` |
| `FaultRule`, `FaultRules`, `HostOverride` | as Kotlin, with `ValueListenable`s and `configure(hosts, {KeyValueStore? store})` |
| Dependencies | `sinew_devtools` imports `sinew_exception` (`CrashReporter`) and `sinew_models` (`SinewException`) directly, so both are declared and in the graph: Dart needs a direct dependency for every import, where Kotlin reaches them through `sinew-network`'s `api` |
| `DevTools.replay` | `static Future<void> replay(NetworkRecord record)`, through the `Dio` the hooks were installed in |

Expand Down
Loading