Repository Public BSD-3-Clause
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Maps9// File : Packages/ORIXMapPackage/Tests/ORIXMapPackageTests/LoopbackHTTPTests.swift10// Module : ORIXMapPackageTests11// Repository : https://git.spboucher.ai/orix-maps12// Created : 2026-11-2513// Last Modified : 2026-11-2514//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : Proprietary, all rights reserved (see license file)80// License File : LICENSE81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import CryptoKit89import Foundation90import Testing91@testable import ORIXMapPackage9293/// The same scenarios through a real HTTP/1.1 exchange: `URLSessionTransport` against a server listening on94/// 127.0.0.1 (Network framework). Nothing leaves the machine.95@Suite(.serialized) struct LoopbackHTTPTests {96 let h = DownloadHarness()9798 func setUp(maxAttempts: Int = 4) async throws -> (LoopbackServer, RegionStore, DownloadManager) {99 let server = try await LoopbackServer(logic: h.logic)100 let store = try h.store()101 let (manager, _) = h.manager(store, transport: URLSessionTransport(userAgent: "ORIXMaps/1.0", requestTimeout: 10), base: server.baseURL, maxAttempts: maxAttempts)102 return (server, store, manager)103 }104105 @Test func downloadOverRealHTTP() async throws {106 let published = try h.publish(sizes: [(.map, 5_000_000), (.search, 2_000_000), (.routing, 1_000_000)])107 let (server, store, manager) = try await setUp()108 let region = try await manager.download(published.request)109 #expect(region.dataVersion == DataVersion("2026.11.24"))110 try await store.verifyInstalled(regionId: region.id)111 _ = server112113 // What the server really received: nothing that identifies the user or the device.114 let request = try #require(h.logic.requests.first)115 #expect(request.headers["user-agent"] == "ORIXMaps/1.0")116 #expect(request.headers["accept-language"] == "en")117 #expect(request.headers["accept-encoding"] == "identity")118 #expect(request.headers["cookie"] == nil)119 #expect(request.headers["authorization"] == nil)120 #expect(request.headers["referer"] == nil)121 let expected: Set<String> = ["host", "user-agent", "accept", "accept-language", "accept-encoding", "connection"]122 #expect(Set(request.headers.keys).isSubset(of: expected), "unexpected request headers: \(request.headers.keys.sorted())")123 }124125 @Test func interruptedTransferThenRangeResume() async throws {126 let published = try h.publish(sizes: [(.map, 3_000_000), (.search, 500_000)])127 let path = published.request.path128 h.logic.fail(path, .truncate(afterBytes: 1_200_000), .truncate(afterBytes: 700_000))129 let (server, store, manager) = try await setUp()130 let region = try await manager.download(published.request)131 try await store.verifyInstalled(regionId: region.id)132 _ = server133 let requests = h.logic.requests(for: path)134 #expect(requests.count == 3)135 #expect(requests[0].headers["range"] == nil)136 // URLSession may deliver slightly less than what the server managed to send before the cut.137 let first = try #require(requests[1].headers["range"].flatMap { Int($0.dropFirst(6).dropLast()) })138 #expect(first > 0 && first <= 1_200_000)139 #expect(requests[1].headers["if-range"] == "\"\(sha256Hex(published.data))\"")140 let second = try #require(requests[2].headers["range"].flatMap { Int($0.dropFirst(6).dropLast()) })141 #expect(second > first && second <= first + 700_000)142 }143144 @Test func truncatedBodyIsAnError() async throws {145 let published = try h.publish()146 h.logic.fail(published.request.path, .truncate(afterBytes: 400_000))147 let (server, store, manager) = try await setUp(maxAttempts: 1)148 #expect(await downloadError { try await manager.download(published.request) } == .network(.connectionLost))149 #expect(await store.regions().isEmpty)150 #expect(manager.pendingDownloads().count == 1)151 _ = server152 }153154 @Test func changedETagDuringResume() async throws {155 let published = try h.publish()156 let path = published.request.path157 h.logic.fail(path, .truncate(afterBytes: 600_000))158 let (server, store, manager) = try await setUp(maxAttempts: 1)159 #expect(await downloadError { try await manager.download(published.request) } == .network(.connectionLost))160 var replaced = published.data161 replaced[replaced.count - 1] ^= 0xFF162 h.logic.put(path, replaced)163 #expect(await downloadError { try await manager.download(published.request) } == .serverFileChanged)164 #expect(h.partials().isEmpty)165 #expect(await store.regions().isEmpty)166 _ = server167 }168169 @Test func rateLimitAndWrongChecksum() async throws {170 let published = try h.publish()171 let (server, store, manager) = try await setUp()172 h.logic.fail(published.request.path, .status(429, ["Retry-After": "120"]))173 #expect(await downloadError { try await manager.download(published.request) } == .rateLimited(retryAfter: 120))174 var request = published.request175 request.sha256 = String(repeating: "f", count: 64)176 #expect(await downloadError { try await manager.download(request) } == .checksumMismatch(expected: request.sha256, actual: sha256Hex(published.data)))177 var missing = published.request178 missing.path = "files/none/1/none-1.orixmap"179 #expect(await downloadError { try await manager.download(missing) } == .httpStatus(404))180 #expect(await store.regions().isEmpty)181 try await manager.download(published.request)182 _ = server183 }184185 @Test func catalogWithETagRevalidationOverRealHTTP() async throws {186 let published = try h.publish()187 try h.distribution.publishCatalog([published.region])188 let server = try await LoopbackServer(logic: h.logic)189 let transport = URLSessionTransport(userAgent: "ORIXMaps/1.0", requestTimeout: 10)190 let client = CatalogClient(baseURL: server.baseURL, transport: transport, cacheDirectory: h.tmp.file("cache"))191 let first = try await client.catalog()192 #expect(first.origin == .network)193 #expect(first.document.regions == [published.region])194 #expect(try await client.catalog(refresh: .always).origin == .revalidated)195 #expect(h.logic.requests(for: "catalog.json").last?.headers["if-none-match"] != nil)196 #expect(try await client.regionDetail(id: "ca-qc-montreal").document.region == published.region)197 h.logic.fail("catalog.json", .status(429, ["Retry-After": "9"]))198 #expect(try await client.catalog(refresh: .always).origin == .staleCache(reason: .rateLimited(retryAfter: 9)))199200 // Server gone: the transport reports that it cannot connect, the cached catalog is still usable.201 let dead = CatalogClient(baseURL: URL(string: "http://127.0.0.1:9/maps/v1/")!, transport: transport, cacheDirectory: h.tmp.file("cache-dead"))202 await #expect(throws: CatalogError.network(.cannotConnect)) { try await dead.catalog() }203 }204205 @Test func manifestAloneOverRealHTTP() async throws {206 let published = try h.publish(sizes: [(.map, 4_000_000)])207 let (server, _, manager) = try await setUp()208 let preamble = try await manager.fetchManifest(published.request, preambleSize: published.region.latest.preambleSize)209 #expect(preamble.manifest.regionId == "ca-qc-montreal")210 #expect(h.logic.bodyBytesServed == Int(try #require(published.region.latest.preambleSize)))211 _ = server212 }213}214