krz/moonrise

Night-sky companion for iPhone, Apple Watch and Vision Pro: what's up tonight, the Moon, planets, launches and missions, and a Library of the solar system. SwiftUI app with a Cloudflare Workers backend. astronomy cloudflare-workers ios night-sky space swiftui visionos watchos

Commit 4234268fe5

4234268fe5b8984dc41138e5c4a4b751f81e2afb

parent: a0928c6710

Unsigned

cmc <hello@cleberg.net> · 2026-10-21 05:17 UTC

Remote images: large bodies to a file, two decodes at a time, 150 MB cache (!75)

## Cause

Scrolling News pushed the footprint to 531–533 MB. That was not a full-size decode. The feed currently carries a 208 MB PNG (11958×11156, nasa.gov `55572978759-545472774e-o.png`). `URLSession.data(from:)` holds the body in memory while it downloads and then a second copy while it finishes (macOS: 453 MB peak footprint for that one download, no decoding). `CGImageSourceCreateThumbnailAtIndex` already decodes it as a stream: the footprint stayed flat during its 1.3 s decode in the simulator, and on macOS the thumbnail adds 16 MB. So a pixel-size check would not lower the peak, and none was added.

Library thumbnails decoded again after a cleared search because the cache evicted them. The front page alone decodes to about 89 MB at 780 px, and the limit was 60 MB. There were 113–142 evictions per run. Cache keys match.

## Changes (`App/Sources/RemoteImage.swift`)

- If a data task's response announces a body over 20 MB, the task is cancelled after the headers. The image is then downloaded to a file and mapped, so ImageIO reads it from disk. URLCache never stores bodies that size (5% of its 400 MB disk), so nothing that was cached before goes uncached now. Smaller images use the same data-task path as before.
- Decodes run on an `OperationQueue` limited to 2. Before, `Task.detached` started one decode per image.
- `NSCache` `totalCostLimit`: 60 MB → 150 MB. That holds the front page, News and the two searches in the tour (137 MB in total). NSCache releases memory under pressure.
- Thumbnail size and options are unchanged, so images at display size are the same as before.

## Measurements

Release build-for-testing, iPhone 18 Pro simulator (iOS 27), M2 Pro. Fresh install per run with live network. Method: a temporary probe (not committed) samples `phys_footprint` every 54 ms and logs each decode's thread CPU time, cache misses and NSCache evictions. A UI test opens Launches, switches to News, scrolls, then opens Library, scrolls, searches "andromeda galaxy", clears, searches "orion", clears and goes back to News. Two runs each, against the same feed.

| | main (2 runs) | this branch (2 runs) |
|-|-:|-:|
| Peak footprint, News switch and scroll | 531 / 533 MB | 147 / 142 MB |
| Peak footprint, whole tour | 531 / 533 MB | 186 / 183 MB |
| Time over 250 MB | 2.9 / 2.7 s | 0 |
| Footprint at end of tour | 178 / 177 MB | 178 / 176 MB |
| Decodes, whole tour | 141 / 171 | 102 / 105 |
| Decode CPU, whole tour | 3,471 / 4,073 ms | 2,875 / 2,819 ms |
| Decodes after the two search clears | 40 / 53 (628 / 938 ms) | 0 / 0 |
| NSCache evictions | 113 / 142 | 5 / 3 |
| Decode CPU, News | 1,896 / 1,872 ms | 1,949 / 1,871 ms |

The 3–5 evictions left happen when the same URL loads twice at once and the second result replaces the first: a URL repeated in the news feed, and Library of Congress plates shared by several constellation results. Decode CPU for News did not change. 1.28–1.33 s of it is the 208 MB PNG, because ImageIO has to inflate all of its data whatever the thumbnail size.

Load (`uptime`) during the runs: main 71.7 → 19.6 and 6.7 → 5.6; this branch 10.9 → 9.0 and 5.3 → 4.2. Other work was running on the host during the first main run.

## Tests

- `swift test` (MoonriseKit): pass.
- `npm test` (server): 55 pass.
- `xcodebuild test` (iPhone 18 Pro): pass. The accessibility audit found 66 issues: Sky 4, Settings 2, System 7, Sun 3, News & launches 23, Library 14, Library page: Saturn 13. main's run in the same session found 67 (News & launches 24, the rest the same). The difference is launch-list content.

## Not verified

- On a device. Neither the memory warnings that make NSCache evict nor the URLSession copy behaviour has been checked on a phone.
- The large-body path when the server sends no `Content-Length`. Those responses go through the data task as before.

Layout: unified · split

App/Sources/RemoteImage.swift +41 −4
@@ -5,21 +5,44 @@ import UIKit
5/// Images from the network, decoded at the size they are shown rather than full size, and kept in memory. 5/// Images from the network, decoded at the size they are shown rather than full size, and kept in memory.
6/// Downloads go through URLSession.shared, so the disk cache set up in `configureURLCache` applies. 6/// Downloads go through URLSession.shared, so the disk cache set up in `configureURLCache` applies.
7enum ImageLoader { 7enum ImageLoader {
8 // NSCache is thread-safe. 8 // NSCache is thread-safe. The Library front page alone is about 90 MB of thumbnails, so the limit holds it,
9 // the news list and a few searches; NSCache gives memory back under pressure.
9 nonisolated(unsafe) private static let cache: NSCache<NSString, UIImage> = { 10 nonisolated(unsafe) private static let cache: NSCache<NSString, UIImage> = {
10 let c = NSCache<NSString, UIImage>() 11 let c = NSCache<NSString, UIImage>()
11 c.totalCostLimit = 60 * 1024 * 1024 12 c.totalCostLimit = 150 * 1024 * 1024
12 return c 13 return c
13 }() 14 }()
14 15
16 // Two decodes at a time; a list otherwise starts one per row at once.
17 nonisolated(unsafe) private static let decodes: OperationQueue = {
18 let q = OperationQueue()
19 q.maxConcurrentOperationCount = 2
20 q.qualityOfService = .userInitiated
21 return q
22 }()
23
24 /// Bodies over this size are never stored by URLCache (5% of its disk size).
25 private static let largeBody: Int64 = 20 * 1024 * 1024
26
15 static func cached(_ url: URL, maxPixels: Int) -> UIImage? { 27 static func cached(_ url: URL, maxPixels: Int) -> UIImage? {
16 cache.object(forKey: key(url, maxPixels)) 28 cache.object(forKey: key(url, maxPixels))
17 } 29 }
18 30
19 static func load(_ url: URL, maxPixels: Int) async throws -> UIImage { 31 static func load(_ url: URL, maxPixels: Int) async throws -> UIImage {
20 if let hit = cached(url, maxPixels: maxPixels) { return hit } 32 if let hit = cached(url, maxPixels: maxPixels) { return hit }
21 let (data, _) = try await URLSession.shared.data(from: url) 33 let data: Data
22 let image = try await Task.detached(priority: .userInitiated) { try downsample(data, maxPixels: maxPixels) }.value 34 do {
35 data = try await URLSession.shared.data(for: URLRequest(url: url), delegate: CancelLargeBody(limit: largeBody)).0
36 } catch let error as URLError where error.code == .cancelled && !Task.isCancelled {
37 // A data task holds the whole body in memory, twice while it finishes. Download to a file instead
38 // and map it, so ImageIO reads it from disk.
39 let (file, _) = try await URLSession.shared.download(from: url)
40 data = try Data(contentsOf: file, options: .alwaysMapped)
41 try? FileManager.default.removeItem(at: file)
42 }
43 let image = try await withCheckedThrowingContinuation { c in
44 decodes.addOperation { c.resume(with: Result { try downsample(data, maxPixels: maxPixels) }) }
45 }
23 let cost = Int(image.size.width * image.size.height * image.scale * image.scale * 4) 46 let cost = Int(image.size.width * image.size.height * image.scale * image.scale * 4)
24 cache.setObject(image, forKey: key(url, maxPixels), cost: cost) 47 cache.setObject(image, forKey: key(url, maxPixels), cost: cost)
25 return image 48 return image
@@ -47,6 +70,20 @@ enum ImageLoader {
47 } 70 }
48} 71}
49 72
73/// Cancels a data task as soon as its response announces a body over `limit` bytes.
74private final class CancelLargeBody: NSObject, URLSessionTaskDelegate, @unchecked Sendable {
75 let limit: Int64
76 private var observation: NSKeyValueObservation?
77
78 init(limit: Int64) { self.limit = limit }
79
80 func urlSession(_ session: URLSession, didCreateTask task: URLSessionTask) {
81 observation = task.observe(\.countOfBytesExpectedToReceive) { [limit] task, _ in
82 if task.countOfBytesExpectedToReceive > limit { task.cancel() }
83 }
84 }
85}
86
50/// A remote image decoded for `points` (the longer side it is drawn at), with a placeholder while loading. 87/// A remote image decoded for `points` (the longer side it is drawn at), with a placeholder while loading.
51struct RemoteImage<Placeholder: View>: View { 88struct RemoteImage<Placeholder: View>: View {
52 var url: URL? 89 var url: URL?