Skip to content

feat(downloads): fetch manifests, assets and files from v2 - #373

Merged
Quick104 merged 1 commit into
mainfrom
apiv2-stack/25-download-assets-v2
Sep 23, 2026
Merged

Quick104 merged 1 commit into
mainfrom
apiv2-stack/25-download-assets-v2

Conversation

@Quick104

Copy link
Copy Markdown
Contributor

Problem

After W3-B, downloads register through the v2 registry, but the pipeline that fills them still used v1 (inventory rows 94-96):

  • The manifest came from GET /api/v1/downloads/{id}/manifest (row 94).
  • Artwork and subtitles went through a generic HTTPClient.getData(path) on whatever path the manifest named (row 95).
  • The background transfer requested /api/v1/downloads/{id}/file (row 96).

Silo 1.0 answers those v1 routes with 410. The transfer failure handler sent a 410 to its default branch, which resent the same resume data up to four times and then failed the download. The v2 manifest also sends media_file_id as a string, and OfflineManifest decoded it as an Int.

Solution

  • Manifest (getDownloadManifest, GET /api/v2/downloads/{id}/manifest). New APIv2Client.downloadManifest(id:auth:) in APIv2Client+Downloads.swift. It goes through the same owner-fenced registry transport as W3-B (gate(), pre-dispatch identity check, withOwnerFence, X-Silo-Device-Id from HTTPClient), expects 200, and throws the new DownloadRegistryError.unusableManifest when the manifest names another entry or has no file or revision. Nothing from a refused manifest is stored.
  • Assets (getDownloadArtwork, getDownloadSubtitle). New APIv2Client.downloadAsset(path:downloadId:auth:). It sends a manifest path only when it is exactly /api/v2/downloads/{that entry}/artwork/{kind} or .../subtitles/{ref}: relative, with no query or fragment and one reference segment that is not . or ... This mirrors the server's own rewrite check in download_manifests.go. Any other path is refused before it is sent. A failed asset is logged and skipped, as before.
  • File (downloadFile). APIv2Client.downloadFileURL(id:serverURL:) builds /api/v2/downloads/{id}/file from the captured owner's server URL, keeping any mount path and percent-encoding the id. DownloadAuthHeaders.authorizedRequest now takes that owner's credentials (the current token for the same owner) instead of reading TokenStore field by field.
  • Scope fencing. The pipeline captures the scope owner once. After each await it applies results only while that scope is still loaded. If no owner can be captured, or the owner changed under a request, the record is parked as queued instead of failed.
  • 410 restarts the download (I16). handleMediaFailure now uses a testable mediaFailureAction. A 410, 412 or 416 on the file transfer restarts the download from a fresh manifest without the old resume data, within the existing maxRetries bound. The other statuses keep their behavior: 409 revokes, 404/403 fail, 401 refreshes and retries, anything else resumes. A 410 on the v2 manifest fails the record instead, because it means the app is too old and a retry cannot fix that.
  • Stale resume data and tasks. W1-D already deleted resume data and cancelled background tasks from before the v2 storage reset. For anything created after that by a build that still used the v1 file URL:
    • DownloadSessionDelegate.resume(data:) returns nil, without sending, when the resume data's request is not a v2 download file route. Callers restart from the manifest.
    • reconnectActiveTasks cancels live tasks on any other route, marking them as intentional cancels, and re-queues their downloads.
    • A task whose request URL is unknown is kept. If it is stale, it still ends in a 410, which restarts it.
  • Model. OfflineManifest.mediaFileId is a required String, with no dual decoder (D1). The stored manifest.json keys and subtitleFilenames (keyed by fetch_url) are unchanged. Offline playback maps the string to the player's integer file id at the boundary. A non-numeric id becomes 0, which the v2 subtitle calls already refuse.
  • Removed. SiloAPI.fetchManifest(downloadId:), fetchDownloadAssetData(path:), downloadFileURL(downloadId:), the now-unused HTTPClient.getData, and DownloadSessionDelegate.activeTaskIdentifiers (replaced by liveTasks).
  • The ownership-fence line count in iosApp/iosApp stays at 63.

Failure outcomes

These are all reads (no x-silo-retry-safety on the operations), so there is no uncertain write.

Call Success Failure
Manifest 200 that describes the entry: stored as manifest.json, display fields applied 409: revoked. 404/403: failed. 429/5xx: bounded retry from the manifest. 410 or other 4xx: failed. Refused manifest: failed with "The server returned download details this app can't use." Owner changed or no session: parked as queued, nothing applied. Transport error: failed (unchanged from before)
Artwork / subtitle 200 with bytes: file written, filename recorded Logged and skipped; the download continues. A path outside the entry's routes is never sent
File transfer 2xx: media moved into place, completed status event queued 410/412/416: restart from the manifest without resume data (bounded). 409: revoked. 404/403: failed. 401: refresh then restart (bounded). Other statuses and transport errors: resume from resume data (bounded)

Validation

  • iOS, tvOS and macOS builds passed on this branch.
  • Focused tests passed on iOS and tvOS: DownloadDeliveryV2Tests, OfflinePlaybackMappingTests, ArtworkURLTests, DownloadRegistryV2Tests, LegacyDownloadStorageTests, DownloadGroupingTests and ProgressSyncV2Tests. The ArtworkURLTests manifest case is iOS-only.
  • New DownloadDeliveryV2Tests (on StubURLProtocol and the vendored download_manifest.json fixture at server 84ed9e596) cover:
    • the manifest request path with its device and profile headers, the string media_file_id and the v2 asset references;
    • a stored manifest round-tripping through the DownloadStore coder with its file id and subtitle fetch_url keys intact;
    • refusal of manifests that name another entry, lack a revision, or carry a numeric or empty file id;
    • 404, 409 and 410 problems keeping their status;
    • an asset fetch sending the manifest route with X-Silo-Device-Id, seven out-of-scope asset paths refused without a request, and an asset 404 thrown;
    • the file URL keeping the server mount and encoding the id, and which URLs count as a v2 file route;
    • the transfer failure decisions: 410/412/416 restart without resume data, the retry bound, network resume, 401 refresh, 409 revoke.
  • OfflinePlaybackMappingTests and ArtworkURLTests now send media_file_id as a string.
  • scripts/ci/check-no-api-v1.sh passed.
  • The final stack passed the full suites (iOS 1981 tests and tvOS 1792 tests, 0 failures), the macOS build and the v1 path guard, and every branch in the stack builds on its own.
  • Not run: the plan's manual checks (upgrade over a paused download with v1 resume data, then a clean restart; offline playback with subtitles) on a signed simulator against a live server.
  • Not verified on a device: that downloadTask(withResumeData:) exposes the resumed request's URL before resume(). If it doesn't, the resume data is kept, and a stale one ends in a 410, which now restarts the download.

Risks and follow-ups

  • Manifests saved by intermediate builds. Builds between W1-D and this PR store manifest.json with an integer mediaFileId. Under D1 there is no dual decoder, so offline playback of a download completed on such a build reports the manifest unavailable. Release upgrades from before W1-D are unaffected, because W1-D removed that storage.
  • Pipeline transport errors still fail the record at once instead of retrying, as the v1 pipeline did. Changing that is outside this PR.
  • Open PR feat(player): support all marker occurrences #343 moves row 94 (the manifest) as well. If it lands first, this PR drops row 94 and keeps rows 95 and 96. Expect conflicts in DownloadAPI.swift, DownloadModels.swift and OfflinePlayback.swift. fix(downloads): retarget store on profile and server switch #181 and feat(apple): detect and label Dolby media formats #72 touch DownloadManager.swift and OfflinePlayback.swift. Whichever lands second rebases.
  • Still on v1: subscriptions (W3-D) and the progress pull (W3-E).

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 25 of 50 in the Apple API v2 stack. Base: apiv2-stack/24-downloads-registry-v2. Merge in order from the bottom of the stack. The plan and full index are in PR 01.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: d7e33990-62ee-449b-8b15-9fe110e1204f

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Quick104 has reached the 50-credit limit for trial accounts. To continue receiving code reviews, upgrade your plan.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-23T13:47:36.364294Z dc6f6ed New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Quick104

Copy link
Copy Markdown
Contributor Author

Code review summary

Reviewed head: 10accf0a (apiv2-stack/25-download-assets-v2).

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: none.
Refuted or unconfirmed after verification: 1 (not acted on).

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 /api/v1 request from the new builds except the retained health probe.

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 (claude-opus-5-5) agents in Claude Code (T3 Code).

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 10accf0a33

ℹ️ 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".

deliveryFormat = try keyed.decodeIfPresent(String.self, forKey: .deliveryFormat)
targetBitrateKbps = try keyed.decodeIfPresent(Int.self, forKey: .targetBitrateKbps)
mediaFileId = try keyed.decodeIfPresent(Int.self, forKey: .mediaFileId) ?? 0
mediaFileId = try keyed.decode(String.self, forKey: .mediaFileId)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve numeric IDs in stored manifests

When upgrading from the parent build, already-downloaded manifest.json files contain mediaFileId as a JSON number because the previous OfflineManifest.encode(to:) encoded an Int. Decoding only String now makes DownloadStore.loadManifest return nil; completed records remain marked playable but OfflinePlaybackBuilder.loadPreparedPlayback fails with manifestUnavailable, even though their media is still present. Decode both the legacy numeric representation and the new opaque string representation, and persist the normalized string.

Useful? React with 👍 / 👎.

@Quick104
Quick104 force-pushed the apiv2-stack/24-downloads-registry-v2 branch from ad27852 to f9ad77a Compare September 23, 2026 13:19
@Quick104
Quick104 force-pushed the apiv2-stack/25-download-assets-v2 branch from 10accf0 to 0b8330c Compare September 23, 2026 13:19

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0b8330ce65

ℹ️ 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".

Comment on lines +230 to +233
guard let path = url?.path, path.hasSuffix("/file"),
let range = path.range(of: "/api/v2/downloads/") else { return false }
let id = path[range.upperBound...].dropLast("/file".count)
return !id.isEmpty && !id.contains("/")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Inspect the percent-encoded path before rejecting transfers

When an opaque download ID contains /, downloadFileURL correctly encodes it as %2F, but URL.path decodes that back to /; the id.contains("/") check therefore rejects a URL created by this same client. DownloadSessionDelegate consequently discards its resume data and cancels its live task after relaunch, repeatedly restarting that download from zero. Parse URLComponents.percentEncodedPath so an encoded delimiter remains within the ID segment.

Useful? React with 👍 / 👎.

@Quick104
Quick104 force-pushed the apiv2-stack/24-downloads-registry-v2 branch from f9ad77a to 02365c3 Compare September 23, 2026 13:39
The download pipeline still read the offline manifest from
/api/v1/downloads/{id}/manifest, fetched artwork and subtitles through a
generic path GET, and pointed the background transfer at
/api/v1/downloads/{id}/file. Silo 1.0 answers those v1 routes with 410, and
the transfer's retry loop resent the same resume data after a 410 until it
gave up.

The manifest now comes from getDownloadManifest, must describe the entry it
was asked for, and carries media_file_id as a string. Artwork and subtitles
use getDownloadArtwork and getDownloadSubtitle, and only paths under the
entry's own /api/v2/downloads/{id}/ asset routes are ever sent. The
background transfer requests /api/v2/downloads/{id}/file with headers taken
from one captured owner, and the whole pipeline applies results only while
the scope that started it is still loaded.

A 410, 412 or 416 on the file transfer now restarts the download from a
fresh manifest without the old resume data, bounded by the existing retry
limit. Resume data or a live background task that targets anything other
than the v2 file route is discarded before it sends a request, and its
download restarts. The v1 manifest, asset and file-URL helpers and the
unused HTTPClient.getData are deleted.

Stack-PR: W3-C
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Base automatically changed from apiv2-stack/24-downloads-registry-v2 to main September 23, 2026 13:39
@Quick104
Quick104 force-pushed the apiv2-stack/25-download-assets-v2 branch from 0b8330c to dc6f6ed Compare September 23, 2026 13:39
@Quick104
Quick104 merged commit 17f3a45 into main Sep 23, 2026
3 of 6 checks passed
@Quick104
Quick104 deleted the apiv2-stack/25-download-assets-v2 branch September 23, 2026 13:39

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: dc6f6ed841

ℹ️ 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".

let fileId = Int(manifest.mediaFileId)
let version = FileVersion(
fileId: manifest.mediaFileId,
fileId: fileId ?? 0,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Treat nonnumeric file IDs as unavailable

When a v2 manifest contains a valid nonnumeric opaque media_file_id, this stores 0 in the nonoptional FileVersion.fileId, which does not turn off server-backed subtitle actions as the comment claims. PlayerViewModel.subtitleSearchVisible only checks that the selected version exists, and SubtitleAIController.submit likewise accepts the resulting zero, so offline playback exposes search/AI controls and sends requests for media file 0. Preserve an optional legacy integer ID or explicitly gate those actions on a positive ID and non-offline playback.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant