~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0
109 lines · 4.5 KB Raw History
import Foundation
import Testing
import UIKit

@testable import HUDKit

// Pictures fetched once however many ask: a picture loaded ahead (the next
// story) and then drawn waits for the one fetch, as two drawing it at once
// do; one kept is fetched no more; and one let go by all who asked stops,
// asked again after, fetched afresh. Each is asked for as AVIF first.

/// Answers each request with a small picture a while later, counting them by URL and keeping what each asked for as.
private final class SlowPictures: URLProtocol, @unchecked Sendable {
	nonisolated(unsafe) static var asked: [URL: Int] = [:]
	nonisolated(unsafe) static var accepts: [URL: String] = [:]
	static let lock = NSLock()
	static let png = UIGraphicsImageRenderer(size: CGSize(width: 4, height: 4)).pngData { context in
		UIColor.red.setFill()
		context.fill(CGRect(x: 0, y: 0, width: 4, height: 4))
	}

	static func count(_ url: URL) -> Int { lock.withLock { asked[url] ?? 0 } }
	static func accept(_ url: URL) -> String? { lock.withLock { accepts[url] } }

	override class func canInit(with request: URLRequest) -> Bool { true }
	override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }

	override func startLoading() {
		let url = request.url!
		Self.lock.withLock {
			Self.asked[url, default: 0] += 1
			Self.accepts[url] = request.value(forHTTPHeaderField: "Accept")
		}
		DispatchQueue.global().asyncAfter(deadline: .now() + 0.3) { [self] in
			let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: nil, headerFields: ["Content-Type": "image/png"])!
			client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
			client?.urlProtocol(self, didLoad: Self.png)
			client?.urlProtocolDidFinishLoading(self)
		}
	}

	override func stopLoading() {}
}

private func pictures() -> Pictures {
	let configuration = URLSessionConfiguration.ephemeral
	configuration.protocolClasses = [SlowPictures.self]
	return Pictures(configuration: configuration, urlCache: nil)
}

@Suite struct PicturesLoad {
	@Test func twoAskingAtOnceFetchItOnce() async throws {
		let shared = pictures()
		let url = try #require(URL(string: "https://cdn.test/\(UUID().uuidString).png"))
		async let first = shared.load(url, side: 100)
		async let second = shared.load(url, side: 100)
		let (a, b) = try await (first, second)
		#expect(a === b)
		#expect(SlowPictures.count(url) == 1)
		// Kept, it is fetched no more.
		_ = try await shared.load(url, side: 100)
		#expect(SlowPictures.count(url) == 1)
	}

	@Test func oneLoadedAheadIsWaitedForWhenDrawn() async throws {
		let shared = pictures()
		let url = try #require(URL(string: "https://cdn.test/\(UUID().uuidString).png"))
		shared.preload(Source(src: url.absoluteString, fallback: nil), side: 100, scale: 3)
		try await Task.sleep(for: .milliseconds(100))
		_ = try await shared.load(url, side: 100)
		#expect(SlowPictures.count(url) == 1)
		#expect(shared.cached(url) != nil)
		// Loaded already, or with no source, nothing more is fetched.
		shared.preload(Source(src: url.absoluteString, fallback: nil), side: 100, scale: 3)
		shared.preload(nil, side: 100, scale: 3)
		try await Task.sleep(for: .milliseconds(100))
		#expect(SlowPictures.count(url) == 1)
	}

	@Test func oneWithSizesIsLoadedAheadAtTheOneThatFillsItsSideAtItsScale() async throws {
		let shared = pictures()
		let at = "https://cdn.test/\(UUID().uuidString)"
		let (small, large) = try (#require(URL(string: "\(at)-640.png")), #require(URL(string: "\(at)-1440.png")))
		let sized = Source(src: "\(at).png", fallback: nil, sizes: Source.sizes("\(large) 1440w, \(small) 640w"))
		shared.preload(sized, side: 400, scale: 3)
		shared.preload(sized, side: 200, scale: 3)
		try await Task.sleep(for: .milliseconds(500))
		#expect(SlowPictures.count(large) == 1)
		#expect(SlowPictures.count(small) == 1)
	}

	@Test func oneLetGoByAllStopsAndIsFetchedAfreshAfter() async throws {
		let shared = pictures()
		let url = try #require(URL(string: "https://cdn.test/\(UUID().uuidString).png"))
		let gone = Task { try await shared.load(url, side: 100) }
		try await Task.sleep(for: .milliseconds(50))
		gone.cancel()
		await #expect(throws: (any Error).self) { try await gone.value }
		#expect(shared.cached(url) == nil)
		_ = try await shared.load(url, side: 100)
		#expect(SlowPictures.count(url) == 2)
	}

	@Test func itIsAskedForAsAvifFirstThenJpeg() async throws {
		let url = try #require(URL(string: "https://cdn.test/\(UUID().uuidString).png"))
		_ = try await pictures().load(url, side: 100)
		#expect(SlowPictures.accept(url) == "image/avif,image/jpeg;q=0.9,*/*;q=0.8")
	}
}