Refreshing an access token without a race
`api_get(client, path, tokens)` calls the API with an access token and refreshes
it on `401`.
Client: `get(path, headers=...)` → a response with `status_code` and `json()`.
`TokenProvider(refresher, token=None)` holds the current token:
- `get()` — return the current token; if there is none, call `refresher()` once;
- `refresh(stale)` — refresh the token if the current one is still equal to
`stale`. If another thread has already refreshed it, return the fresh token
and **do not** call `refresher()` again. That is single-flight.
Rules for `api_get`:
- the request carries `Authorization: Bearer <token>`;
- `200` — return `json()`;
- `401` — refresh the token once and retry exactly once;
- a second `401` — `AuthError`;
- other `4xx` and `5xx` — `ApiError`, no refresh and no retry;
- concurrent `401`s from several threads result in one `refresher()` call, and
both retries go out with the new token.
Write tests: success, `401` → success, a second `401` after the refresh, `403`
without a refresh, `5xx` without a refresh, and parallel requests with a single
refresh.
The AI mentor is available after you log in: it sees your attempt history and does not spend resources on anonymous requests.
Log in and askHint 1
How do you tell "the token expired" from "no permission", and get through it
without a refresh storm?