Repository navigation
feat(playback): open the control socket with a v2 ticket - #378
Conversation
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Advanced Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Quick104 has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Code review summaryReviewed head: Process: an adversarial review of this PR's diff with each candidate finding independently verified before any fix, a simplify pass for medium and larger PRs, and a whole-stack review across contract conformance, authority and failure handling, data integrity, user-visible behavior and cross-PR integration. Verified findings, all fixed on this branch:
Validation: this branch builds on its own for iOS, tvOS and macOS, and its focused tests passed. The completed stack passed the full iOS suite (1981 tests) and tvOS suite (1792 tests) with 0 failures, the macOS build and the v1 path guard. The final stack was also exercised on iOS and tvOS simulators against a v1/v2 bridge server: sign-in (password and QR), restore, browse, search, detail, favorites and watchlist, playback (direct play, transcode, subtitles, stop), audiobooks, downloads with offline playback, settings, requests, profiles, push registration and diagnostics. Server logs showed no Remaining: no open verified findings. Merge in stack order. Mergeability: 8/10 — conditional. The approach holds up and every verified finding is fixed. Conditions: this PR's CI must pass (it was pending at review time), and the owner still plans a physical-device check of the completed stack. Review by Claude Opus 5.5 ( |
5c233a7 to
c425351
Compare
0f3aa8b to
2e3a00b
Compare
c425351 to
6b2151c
Compare
The player's remote-control socket still upgraded
/api/v1/playback/sessions/{id}/control/ws with the account's bearer token
in the Authorization header. A 1.0 server answers every v1 call except
health with 410, so remote control would stop working. The v2 ticket
builder that already existed had no callers. It also refused plain-http
servers other than loopback, so moving to it unchanged would have broken
remote control on plain-http LAN servers.
Every connect and reconnect now checks the control capability, mints a
single-use ticket with POST .../control/ws-ticket for the session's
installation under the owner that started the session, and upgrades
/api/v2/playback/sessions/{id}/control/ws. The ticket travels only as the
second Sec-WebSocket-Protocol entry. No bearer header is sent and no
ticket is reused. Following D11, a plain-http server gets a ws upgrade.
The socket closes and reconnects with a new ticket when
max_connection_seconds runs out. An owner change, a server that does not
serve the handshake, or a v1-only server ends the connection loop at
once instead of burning the reconnect budget. Frames are dropped once the
session's owner is no longer current. The v1 URL builder and its
transport errors are deleted.
Stack-PR: W2-D
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…keep the owner The control loop treated HTTPError.requestIdentityChanged as terminal. The HTTP client throws it whenever any identity transition holds the dispatch gate, including ones that leave the session's owner in place, such as removing another server or a refused sign-out. A reconnect that overlapped one marked realtime control unavailable for the rest of the session. That error now takes the ordinary backoff, and the owner check at the top of each attempt still stops the loop when the owner really changed. The default handshake also waits for the dispatch gate to reopen before minting a ticket, so a running transition does not use up the reconnect budget. Stack-PR: W2-D Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
…fetime The ticket's max_connection_seconds had no upper bound, and the lifetime timer multiplies it into nanoseconds as UInt64. A value of 18_446_744_074 or more trapped on overflow and crashed the app mid-playback. The handshake now refuses a ticket whose lifetime exceeds one day as an invalid response, like its other malformed fields. The server sends four hours. Stack-PR: W2-D Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2e3a00b to
b8e695f
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b8e695fd45
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| UUID(uuidString: sessionID) != nil, | ||
| var url = URLComponents(string: serverURL), | ||
| ["http", "https"].contains(url.scheme), let host = url.host, | ||
| ["http", "https"].contains(url.scheme), url.host != nil, |
There was a problem hiding this comment.
Normalize the server URL scheme before validating it
When a saved server URL uses a valid case variant such as HTTPS://host, URLComponents preserves that spelling, so this case-sensitive check rejects the freshly minted ticket with invalidResponse and remote control exhausts its reconnect budget. This can affect legacy-migrated or paired entries because ServerRegistry.normalize(url:) preserves the original scheme spelling, while the replaced v1 request builder explicitly lowercased the scheme. Compare a lowercased scheme here before selecting ws or wss.
Useful? React with 👍 / 👎.
Problem
The player's remote-control socket (inventory row 85) still upgraded
/api/v1/playback/sessions/{id}/control/wsand sent the account's bearer token in theAuthorizationheader (PlaybackRealtimeClient.makeRequest). A 1.0 server answers every v1 call except health with 410, so SiloRemote and other controllers would lose the player.APIv2Client.playbackControlRequestalready built the v2 handshake, but nothing called it. Its ticket builder also refused plain-http servers other than loopback (controlRequiresTLS), so switching to it as written would have broken remote control on plain-http LAN servers.Solution
APIv2Client.playbackControlHandshake(sessionID:installationID:auth:)inAPIv2Client+Playback.swift. It readsGET /api/v2/playback/sessions/control/capabilities(200), then mints a ticket withPOST /api/v2/playback/sessions/{session_id}/control/ws-ticket(200,{installation_id}). Both requests run throughplaybackRequest, which fences them to the captured owner. The upgrade goes to/api/v2/playback/sessions/{session_id}/control/wsand carriesSec-WebSocket-Protocol: silo.playback-control.v2, silo.ticket.<ticket>. It sends noAuthorizationheader and never reuses a ticket.PlayerViewModelbinds the socket throughPlaybackSessionBridge.committedProtocolV3Authority(sessionId:), so tickets are minted for the owner andinstallation_idthat started the committed session. A late bind for a replaced session binds nothing.PlaybackSequencedError.controlRequiresTLSare gone. Anhttpserver gets awsupgrade and anhttpsserver getswss. Ticket validation stays in place: protocol, positive lifetimes (a connection lifetime above one day is refused), ticket charset, a UUID session id, and a server URL with no credentials, query or fragment.max_connection_secondsruns out, and the loop reconnects with a new ticket.controlUnavailable) or a v1-only server (serverUpdateRequired) marks realtime control unavailable right away. Before this, each of these burned the 8-attempt reconnect budget. Transient failures keep the existing backoff and circuit breaker.HTTPError.requestIdentityChangedcounts as transient: the HTTP client also throws it while an identity transition that keeps the owner (removing another server, a refused sign-out) holds the dispatch gate, and the owner check before the next attempt still stops the loop on a real owner change.HTTPClient.waitForRequestDispatchOpen()before minting, so a running identity transition does not use up the reconnect budget.closeSocket().PlaybackRealtimeTransportError.serverUrlNotConfigured,invalidServerURLandmissingAccessToken, andAPIv2Client.playbackControlRequest, which moved to the playback extension under its new name.Frames are unchanged: the server's v2 handler "changes no frame".
Failure outcomes (
createPlaybackControlSocketTicket,natural_idempotent)requestIdentityChangedrefusal while the owner is unchanged, or the upgrade is refusedValidation
PlaybackRealtimeClientTests,APIv2ContractTests,PlaybackProtocolV3Tests,PlaybackSessionTransportTests) and on tvOS (the same four classes plusSubtitleAIControllerTests).scripts/ci/check-no-api-v1.shpassed.PlaybackRealtimeClient.swiftdrops to 0 v1 literals. Its allowlist entry is left for Z1.StubURLProtocol/APIv2TestStubor injected closures) cover:{"installation_id": …}andX-Profile-Id, under a base-path server URL;http://192.168.1.20:8096/silo:ws://…/silo/api/v2/playback/sessions/{id}/control/ws, with both subprotocols and noAuthorizationheader;controlUnavailablewithout a mint, a 409 on the mint surfacing as a problem, and a non-canonical session id making no request;max_connection_secondsthat would overflow the lifetime timer) and ticket characters;controlUnavailablestopping after one mint, a non-current owner minting nothing, and arequestIdentityChangedrefusal under an unchanged owner minting a second ticket and leaving control available.URLSessionWebSocketTasksends aSec-WebSocket-Protocolheader set on theURLRequestunchanged, sends noOriginheader (which the server's origin check accepts), and completes the handshake over plainws.Risks and follow-ups
84ed9e596(playback_control_socket_v2.go), not against a live server.HTTPClient.shouldAttemptRefreshexcludes the ws-ticket POST from 401 refresh. The capability GET before it does refresh, so an expired access token is normally renewed before the mint. If the token expires between the two requests, that attempt fails and the next reconnect succeeds.PlayerViewModel.swiftandAPIv2PlaybackModels.swift, so expect textual conflicts.AI disclosure
Code and description written by Claude Opus 5.5 (
claude-opus-5-5) agents in Claude Code (T3 Code), orchestrated by a Claude Code workflow.Part 30 of 50 in the Apple API v2 stack. Base:
apiv2-stack/29-playback-sessions-v2. Merge in order from the bottom of the stack. The plan and full index are in PR 01.🤖 Generated with Claude Code