Cache responses per identity and read cached, then fresh

Draft
JE
1d ago
+22927-3926

Stacked on request-options (per-call request options, no PR yet) and drafted until it and #1139 (single-page reads) merge. When they do, this rebases onto main and adds the page-at-a-time observe example and tests.

Why

Apps with their own runtime (stale-while-revalidate caches, several signed-in identities) and agents re-reading the same resources both want the same things from the SDK: a store for responses, conditional revalidation against it, and a read that shows what was stored and then what is fresh. Until now each app has built that itself. This PR is the SDK's own version, behind seams an app can swap out.

What

SPEC §17 used to be "ETag Caching". It is now "Response Cache and Reactive Reads". It keeps the old contract: opt-in, GET only, a 304 answered from the store as a 200. On top of that it adds:

  • ResponseCache store seam: get/set/remove take (partition, url), plus clear(partition) and clearAll(). InMemoryCache is bounded FIFO at 1000 entries. FileCache(directory) (Swift, Kotlin JVM/Android) keeps one directory per partition and writes atomically. A store that fails or holds a corrupt entry is treated as a miss, and a store never fails a call.
  • Wire responses only: the store holds the body and an allowlist of headers (Content-Type, ETag, Last-Modified, Link, X-Total-Count, Cache-Control, Date), never decoded models. Link and X-Total-Count come back on a 304, so a walk whose pages all 304 still follows every page.
  • Partitions: entries are keyed per identity. The partition is cacheIdentity if set, otherwise credential: plus a SHA-256 prefix of the Authorization value. Two identities never share an entry, and clear(A) can't touch B's entries. A persistent store without cacheIdentity is a usage error, because a token refresh would otherwise orphan it. client.clearCache() clears the client's own partition.
  • Revalidation: If-None-Match and If-Modified-Since. A 304 refreshes the stored headers. A 2xx without validators removes the entry, as do 401 (once refresh has failed), 403, 404 and 410. 429, 5xx and network errors leave it in place.
  • Cache policy: a request option under the SDK's own typed key (Swift CachePolicy.Key, Kotlin CachePolicy.Key, TS CACHE_POLICY). The values are default, cacheOnly and networkOnly, defined as Cache-Control's only-if-cached and no-cache. A cacheOnly miss raises the new cache_miss error (§6, exit 11, not retryable) without sending anything. With no SDK store, the SDK sets the equivalent Cache-Control header before caller headers, so URLCache, OkHttp or a service worker under a custom transport honours the policy with no glue.
  • observe: one generic combinator per SDK, not a generated method per operation. It runs any read once with cacheOnly and once with default, and yields Observed{value, source, notModified}. That gives two emissions when something is stored and one when nothing is. The network emission always comes, with notModified set on a 304. If revalidation fails, the stream ends with the mapped error after the cached emission. It works for every read that passes the options it is handed to every call it makes, including page siblings once #1139 lands. A composite that takes no request options yet (recordings.summarize) can't be observed: its cache pass would go to the wire. The forms are Swift AsyncThrowingStream, Kotlin cold Flow and TS AsyncIterable.
  • Offline and rotation: with a cacheIdentity, a cacheOnly read and clearCache() never run the auth strategy, so an offline app with an expired token still reads its store. Each retry attempt is keyed by the credential it was signed with. A caller's own If-None-Match or If-Modified-Since makes the store step aside, except under cacheOnly.
  • Hooks: a cache-only answer fires operation hooks only. A store-answered 304 reports status 200 with fromCache: true, as the ETag cache already did. observe adds no hooks of its own.

Implementations: Swift evolves ETagCache into the store, and enableCache keeps working as InMemoryCache. Kotlin had an enableCache flag and no cache, and now has the full section. TypeScript replaces its ETag middleware. Every page of a walk goes through the cache in all three.

Conformance: conformance/tests/response_cache.json (11 cases), with a cacheCalls case field in conformance/schema.json that runs a sequence of calls over one store. The TypeScript, Swift and Kotlin runners run it. Go, Python, Ruby and Rust skip it by name until their SDK implements §17, as recorded in spec/zero-skip-roster.yml.

Departures, with reasons

  • Store interface vs hey-sdk: hey-sdk's ResponseCache takes one hashed key. Here the partition is a separate argument, so one identity can be cleared without touching another. hey-sdk and fizzy-sdk should converge on this shape: same names (ResponseCache, InMemoryCache, CachedResponse, FileCache), with the partition split out.
  • No credential, no partition: Swift and TS bypass the store when the auth strategy sets no Authorization header. Kotlin hashes every header its strategy sets. Both are safe, and §17 records both.
  • Swift traps on a persistent store without an identity, because its client initializers don't throw (same as a malformed base URL).
  • Kotlin replays stored answers through a private no-network Ktor client, so generated code reads a real HttpResponse. That needs one @OptIn(InternalAPI::class) for callContext(), which a Ktor upgrade could break.
  • Opt-in, not on by default: turning a store on by default would change wire behaviour (conditional requests, memory use) for every existing caller.

Follow-ups

  • Go: move CacheEnabled onto the store seam, then add the policy and observe. Ruby, Python, Rust: implement §17.
  • A TypeScript persistent store (Node file store).
  • Thread request options through recordings.summarize in every SDK, so it can be observed.
  • After #1139: a page-at-a-time observe example and tests, per page with listPage(continuation).

Tests

  • TypeScript: 2259 unit tests pass. TS conformance: 431 pass, 6 skipped, including all 11 cache cases.
  • Swift: 717 pass. Swift conformance: 373 pass, 0 fail, 5 skipped.
  • Kotlin: make kt-check passes, 857 jvmTests. Kotlin conformance: 371 pass, 0 fail, 7 skipped.
  • In all three, the new tests cover: two emissions, 304 reuse including a fully revalidated two-page walk, identity isolation and per-identity clear, stale-on-error (503 keeps the entry, 404 removes it), cacheOnly hit and miss including offline with a throwing auth strategy, networkOnly, retries re-keyed after a token rotation, a corrupt entry treated as a miss, the no-store Cache-Control header with the caller's header winning, and a persistent store without an identity.

CI

cargo deny, Rust stable, Conformance Tests (via test-rust), npm Audit, Bundler Audit and Trivy fail on yanked crates (sha2, pin-project-lite) and new advisories in lockfiles this PR doesn't touch; #1141 owns the lockfile fix. cubic reached its monthly line limit, so it did not review the latest heads.