12.9 · Single-flight token refresh, streaming lines, multipart bodies and request signing

The harder client features: refreshing a token once for many concurrent calls, reading a response as it arrives, building an upload body by hand, and proving a request was not tampered with.

Mental model. Concurrency makes auth and streaming subtle: one refresh for everyone, bytes arrive in arbitrary pieces, and a signature must cover exactly what the server will see.

Auth under concurrency

Coalescing token refreshes so five 401s cause one refresh.

  1. Five requests fail with 401 at the same moment. How do you refresh the token once, retry each request once, and avoid a loop? 12.9.1 · L5
    If every failing request refreshes the token itself you send five refresh calls, and with a rotating refresh token the second one invalidates the first and the…

Bytes and bodies

Line streams and server-sent events, multipart bodies, and HMAC request signing.

  1. How do you read a response as a stream with URLSession.bytes, and why does lines skip blank lines when you are parsing server-sent events? 12.9.2 · L3
    session.bytes(for:) returns an AsyncBytes sequence and the response as soon as the headers arrive, so you can process a body incrementally instead of waiting…
  2. What does a multipart/form-data body look like on the wire, and what are the boundary, CRLF and Content-Type rules you must get right? 12.9.3 · L3
    A multipart body is a sequence of parts separated by a boundary string that must not appear in the data. Each part is --boundary, then headers…
  3. How does HMAC request signing work, what must a canonical string include, and how do you verify a signature safely? 12.9.4 · L5
    When an API must know a request was not altered and came from a client holding a shared secret, the client sends a signature: an HMAC (here HMAC-SHA256) over a…

More in Networking