SPB Git

Repository Public

RegistryTestSupport.swift 11.0 KB 196 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Tests/AstraLocalTests/RegistryTestSupport.swift10// Module           : AstraLocalTests11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2213// Last Modified    : 2026-11-2214//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 AstraCore89import Foundation90@testable import AstraLocal9192/// Files recorded from real services, kept outside the test target's folder (`Tests/AstraLocalFixtures`) and read from the source tree.93enum RecordedFixture {94    static let directory = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("AstraLocalFixtures")95    static func data(_ name: String) throws -> Data { try Data(contentsOf: directory.appendingPathComponent(name)) }96    /// The catalogue shipped inside TestFlight build 2 (`git show v1.0.0-build2:docs/catalog/catalog.json`).97    static func build2Catalog() throws -> Data { try data("catalog-build2.json") }98    static func build2Cards() throws -> [LocalModelCard] { try ModelCatalog.decode(try build2Catalog()).models }99    static func card(_ id: String) throws -> LocalModelCard {100        guard let card = try build2Cards().first(where: { $0.id == id }) else { throw AstraError.local("no \(id) in the build 2 catalogue") }101        return card102    }103}104105/// Devices that do not exist on this desk, described by the numbers the system would report.106enum FakeDevice {107    /// An iPhone sold as `gb` GB: the kernel reports a little less than the nominal size.108    static func iPhone(_ gb: Double, availableGB: Double? = nil, model: String = "iPhone18,2", os: String = "27.0") -> (device: DeviceFacts, memory: MemoryReading) {109        let physical = Int64(gb * 0.97 * 1_073_741_824)110        return (DeviceFacts(platform: .iOS, modelIdentifier: model, osVersion: os, physicalMemoryBytes: physical),111                MemoryReading(physicalBytes: physical, availableBytes: availableGB.map { Int64($0 * 1_073_741_824) }))112    }113    static let sizes: [Double] = [4, 6, 8, 12, 16]114}115116extension LocalModelCard {117    func with(_ change: (inout LocalModelCard) -> Void) -> LocalModelCard { var copy = self; change(&copy); return copy }118}119120/// The exact shape TestFlight build 2 decodes one catalogue entry with (its `LocalModelCard` had a synthesized `Decodable`):121/// the same required and optional fields, the same strict `Capability` enum. Kept here, frozen, to prove old builds accept new catalogues.122struct Build2Card: Decodable, Equatable {123    struct File: Decodable, Equatable { var path: String; var size: Int64; var sha256: String }124    struct Verified: Decodable, Equatable {125        var date: String; var machine: String; var platform: String; var osVersion: String; var tokensPerSecond: Double; var timeToFirstToken: Double126        var peakMemoryBytes: Int64?; var runtime: String?127    }128    var id: String; var displayName: String; var family: String; var publisher: String; var repo: String; var revision: String; var architecture: String129    var quantization: String; var parameterCount: Int64?; var licenseID: String; var licenseURL: String; var redistributable: Bool; var totalBytes: Int64130    var files: [File]; var contextLength: Int; var capabilities: [Capability]; var minimumDeviceMemoryGB: Double; var estimatedRuntimeMemoryBytes: Int64131    var supportedTasks: [String]; var verified: Verified?; var notes: String?; var baseURL: String?; var fallbackBaseURL: String?132}133struct Build2Catalog: Decodable { var schema: Int; var generatedAt: String; var models: [Build2Card] }134135/// Canned Hugging Face API: answers by URL from recorded files, records every request, can fail on demand.136final class HubStub: HTTPTransport, @unchecked Sendable {137    struct Answer { var status: Int; var data: Data; var headers: [String: String] }138    private let lock = NSLock()139    private var answers: [String: Answer] = [:]140    private var failure: Error?141    private var log: [URLRequest] = []142143    var requests: [URLRequest] { lock.withLock { log } }144    var urls: [String] { requests.map { $0.url!.absoluteString } }145    func respond(_ url: String, status: Int = 200, _ data: Data = Data("{}".utf8), headers: [String: String] = [:]) {146        lock.withLock { answers[url] = Answer(status: status, data: data, headers: headers) }147    }148    func fail(with error: Error?) { lock.withLock { failure = error } }149150    /// Registers the recorded info, tree and config of one repository under the URLs `HubDiscovery` asks for.151    func publish(repo: String, revision: String, tree: Bool = true, config: Bool = true) throws {152        let name = repo.replacingOccurrences(of: "/", with: "_")153        respond("https://huggingface.co/api/models/\(repo)", try RecordedFixture.data("hub/info_\(name).json"))154        if tree { respond("https://huggingface.co/api/models/\(repo)/tree/\(revision)?recursive=true&limit=1000", try RecordedFixture.data("hub/tree_\(name).json")) }155        if config { respond("https://huggingface.co/\(repo)/resolve/\(revision)/config.json", try RecordedFixture.data("hub/config_\(name).json")) }156    }157158    func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {159        let url = request.url!.absoluteString160        let (answer, failure) = lock.withLock { () -> (Answer?, Error?) in log.append(request); return (answers[url], self.failure) }161        if let failure { throw failure }162        guard let answer else { return (Data(#"{"error":"Repository not found"}"#.utf8), HTTPURLResponse(url: request.url!, statusCode: 401, httpVersion: "HTTP/1.1", headerFields: [:])!) }163        return (answer.data, HTTPURLResponse(url: request.url!, statusCode: answer.status, httpVersion: "HTTP/1.1", headerFields: answer.headers)!)164    }165    func stream(_ request: URLRequest) async throws -> (HTTPURLResponse, AsyncThrowingStream<String, Error>) { throw AstraError.unsupported("not used") }166}167168/// A `FileDownloadTransport` backed by the fake server: stands for the system's background session. Each piece is written to a169/// temporary file and handed over through `LandedPiece.land`, exactly as the real transport's delegate does.170final class FakePieceTransport: FileDownloadTransport, @unchecked Sendable {171    enum Mode { case pieces, unavailable, ignoreRange }172    let server: FakeServer173    private let lock = NSLock()174    private var _mode: Mode175    private var _pieceRequests: [FileDownloadRequest] = []176    init(server: FakeServer, mode: Mode = .pieces) { self.server = server; _mode = mode }177    var mode: Mode { get { lock.withLock { _mode } } set { lock.withLock { _mode = newValue } } }178    var pieceRequests: [FileDownloadRequest] { lock.withLock { _pieceRequests } }179180    func open(_ request: URLRequest) async throws -> DownloadResponse { try await server.open(request) }181182    func download(_ request: FileDownloadRequest, progress: @escaping @Sendable (Int64) -> Void) async throws {183        let mode = lock.withLock { () -> Mode in _pieceRequests.append(request); return _mode }184        if mode == .unavailable { throw FileDownloadUnavailable("no background session in this test") }185        var r = URLRequest(url: request.url)186        if request.offset > 0, mode != .ignoreRange { r.setValue("bytes=\(request.offset)-", forHTTPHeaderField: "Range") }187        let response = try await server.open(r)188        guard response.status == 200 || response.status == 206 else { throw FileDownloadHTTPError(status: response.status) }189        var body = Data()190        for try await chunk in response.body { body.append(chunk); progress(Int64(body.count)) }191        let temporary = FileManager.default.temporaryDirectory.appendingPathComponent("piece-" + UUID().uuidString)192        try body.write(to: temporary)193        try LandedPiece.land(temporary, as: LandedPiece(path: request.path, offset: response.status == 206 ? request.offset : 0, status: response.status), in: request.landedDirectory)194    }195}196
Files main
Menu

Theme