SPB Git

Repository Public MIT

RegistrySource.swift 10.7 KB 221 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/GlassCLICore/RegistrySource.swift8// Module           : Glass CLICore9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import SPGlassRegistry4344/// Somewhere registry files can be read from, by path relative to the registry root.45public protocol RegistrySource: Sendable {46    /// A stable description of the origin, used to key the cache and recorded in the lock file.47    var identity: String { get }48    /// Reads one file. Fails rather than returning more than `limit` bytes.49    func fetch(_ relativePath: String, limit: Int) async throws -> Data50}5152/// A registry in a local directory: the repository checkout, an unpacked release or a test fixture.53public struct LocalDirectorySource: RegistrySource {54    public let root: URL5556    public init(root: URL) {57        self.root = root.standardizedFileURL.resolvingSymlinksInPath()58    }5960    public var identity: String { "file://" + root.path }6162    public func fetch(_ relativePath: String, limit: Int) async throws -> Data {63        try RegistryPath.validate(relativePath)64        let url = root.appendingPathComponent(relativePath)65        // A link inside the registry may not lead outside of it.66        let resolved = url.resolvingSymlinksInPath().standardizedFileURL.path67        guard resolved == root.path || resolved.hasPrefix(root.path + "/") else {68            throw CLIError(RegistryError.unsafePath(relativePath, reason: "it leaves the registry directory through a symbolic link"))69        }70        var isDirectory: ObjCBool = false71        guard FileManager.default.fileExists(atPath: resolved, isDirectory: &isDirectory), !isDirectory.boolValue else {72            throw CLIError(code: "not_found", message: "The registry has no file \"\(RegistryText.clip(relativePath))\".", exitCode: .notFound)73        }74        let size = (try? FileManager.default.attributesOfItem(atPath: resolved)[.size] as? Int) ?? 075        guard size <= limit else { throw CLIError(RegistryError.tooLarge(what: relativePath, bytes: size, limit: limit)) }76        do {77            return try Data(contentsOf: URL(fileURLWithPath: resolved))78        } catch {79            throw CLIError(code: "unreadable", message: "\"\(RegistryText.clip(relativePath))\" could not be read from the registry.")80        }81    }82}8384/// A registry served over HTTPS. Plain HTTP is refused, as are redirects that leave HTTPS.85public struct HTTPRegistrySource: RegistrySource {86    public let baseURL: URL87    public let timeout: TimeInterval8889    public init(baseURL: URL, timeout: TimeInterval = 20) throws {90        guard baseURL.scheme?.lowercased() == "https", let host = baseURL.host, !host.isEmpty, baseURL.user == nil, baseURL.password == nil else {91            throw CLIError(code: "insecure_registry", message: "The registry must be an https:// URL without credentials, or a local directory.", exitCode: .usage)92        }93        self.baseURL = baseURL94        self.timeout = timeout95    }9697    public var identity: String {98        var text = baseURL.absoluteString99        while text.hasSuffix("/") { text.removeLast() }100        return text101    }102103    public func fetch(_ relativePath: String, limit: Int) async throws -> Data {104        try RegistryPath.validate(relativePath)105        var url = baseURL106        for component in relativePath.split(separator: "/") {107            url.appendPathComponent(String(component))108        }109        let configuration = URLSessionConfiguration.ephemeral110        configuration.timeoutIntervalForRequest = timeout111        configuration.timeoutIntervalForResource = timeout * 3112        configuration.httpCookieStorage = nil113        configuration.urlCache = nil114        configuration.httpAdditionalHeaders = ["User-Agent": "spglass/\(CLIVersion.current)", "Accept": "*/*"]115        let session = URLSession(configuration: configuration, delegate: HTTPSOnlyRedirects(), delegateQueue: nil)116        defer { session.finishTasksAndInvalidate() }117118        do {119            let (bytes, response) = try await session.bytes(from: url)120            guard let http = response as? HTTPURLResponse else {121                throw CLIError(code: "network", message: "Unexpected response from the registry.", exitCode: .network)122            }123            if http.statusCode == 404 {124                throw CLIError(code: "not_found", message: "The registry has no file \"\(RegistryText.clip(relativePath))\".", exitCode: .notFound)125            }126            guard http.statusCode == 200 else {127                throw CLIError(code: "network", message: "The registry answered HTTP \(http.statusCode) for \"\(RegistryText.clip(relativePath))\".", exitCode: .network)128            }129            if http.expectedContentLength > Int64(limit) {130                throw CLIError(RegistryError.tooLarge(what: relativePath, bytes: Int(http.expectedContentLength), limit: limit))131            }132            var data = Data()133            data.reserveCapacity(max(0, min(Int(http.expectedContentLength), limit)))134            for try await byte in bytes {135                data.append(byte)136                if data.count > limit {137                    throw CLIError(RegistryError.tooLarge(what: relativePath, bytes: data.count, limit: limit))138                }139            }140            return data141        } catch let error as CLIError {142            throw error143        } catch is CancellationError {144            throw CancellationError()145        } catch let error as URLError {146            if error.code == .cancelled { throw CancellationError() }147            let reason = error.code == .timedOut ? "the request timed out after \(Int(timeout)) seconds" : "the registry is unreachable (\(error.code.rawValue))"148            throw CLIError(code: "network", message: "Network error: \(reason).", hint: "Check the connection, or use --offline to work from the cache.", exitCode: .network)149        } catch {150            throw CLIError(code: "network", message: "Network error while reading the registry.", exitCode: .network)151        }152    }153}154155private final class HTTPSOnlyRedirects: NSObject, URLSessionTaskDelegate, Sendable {156    func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest) async -> URLRequest? {157        request.url?.scheme?.lowercased() == "https" ? request : nil158    }159}160161/// Adds an on-disk cache in front of a source, and serves from the cache alone when offline.162///163/// Versioned files never change, so a cached copy is used without contacting the registry. The index and its164/// signature are refreshed whenever the registry answers. Callers verify every file against its checksum, so165/// a damaged or tampered cache entry is detected, discarded with ``invalidate(_:)`` and fetched again.166public struct CachingRegistrySource: RegistrySource {167    public let upstream: any RegistrySource168    public let directory: URL169    public let offline: Bool170171    public init(upstream: any RegistrySource, cacheRoot: URL, offline: Bool) {172        self.upstream = upstream173        self.offline = offline174        let key = RegistryHash.sha256(Data(upstream.identity.utf8)).prefix(16)175        self.directory = cacheRoot.appendingPathComponent(String(key))176    }177178    public var identity: String { upstream.identity }179180    public static func defaultCacheRoot(environment: [String: String]) -> URL {181        if let custom = environment["SPGLASS_CACHE_DIR"], !custom.isEmpty { return URL(fileURLWithPath: custom) }182        let base = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first ?? FileManager.default.temporaryDirectory183        return base.appendingPathComponent("spglass")184    }185186    private static let mutablePaths: Set<String> = [RegistrySchema.indexFileName, RegistrySchema.signatureFileName]187188    public func fetch(_ relativePath: String, limit: Int) async throws -> Data {189        try RegistryPath.validate(relativePath)190        let cached = directory.appendingPathComponent(relativePath)191        let isMutable = Self.mutablePaths.contains(relativePath)192193        if !isMutable || offline, let data = readCache(cached, limit: limit) {194            return data195        }196        if offline {197            throw CLIError(code: "offline_cache_miss", message: "\"\(RegistryText.clip(relativePath))\" is not in the local cache.", hint: "Run the command once without --offline.", exitCode: .network)198        }199        do {200            let data = try await upstream.fetch(relativePath, limit: limit)201            try? FileManager.default.createDirectory(at: cached.deletingLastPathComponent(), withIntermediateDirectories: true)202            try? data.write(to: cached, options: .atomic)203            return data204        } catch let error as CLIError where error.exitCode == .network && isMutable {205            // The registry is unreachable: fall back to the last index seen.206            if let data = readCache(cached, limit: limit) { return data }207            throw error208        }209    }210211    public func invalidate(_ relativePath: String) {212        guard (try? RegistryPath.validate(relativePath)) != nil else { return }213        try? FileManager.default.removeItem(at: directory.appendingPathComponent(relativePath))214    }215216    private func readCache(_ url: URL, limit: Int) -> Data? {217        guard let size = try? FileManager.default.attributesOfItem(atPath: url.path)[.size] as? Int, size <= limit else { return nil }218        return try? Data(contentsOf: url)219    }220}221
Files main
Menu

Theme