Repository Public BSD-3-Clause
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Maps9// File : Infrastructure/package-builder/Sources/PackageBuilderKit/CatalogGenerator.swift10// Module : PackageBuilderKit11// 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 ORIXMapPackage9192/// Generates the static distribution documents (`catalog.json`, `regions/<id>.json`, `regions/<id>/versions.json`)93/// from the packages present under `files/` of a distribution directory. Every package is fully verified first.94public enum CatalogGenerator {95 public static let pinsFileName = "pins.json"9697 public enum BuildError: Error, Sendable, Equatable, CustomStringConvertible {98 case noFilesDirectory(String)99 case unexpectedEntry(String)100 case invalidPackage(path: String, error: PackageError)101 /// The package is valid but sits in the directory of another region or version.102 case misplaced(path: String, regionId: String, dataVersion: String)103 /// `--latest` names a version that is not published.104 case unknownVersion(regionId: String, dataVersion: String)105 case io(String)106107 public var description: String {108 switch self {109 case .noFilesDirectory(let p): "no files/ directory in \(p)"110 case .unexpectedEntry(let p): "unexpected entry in the distribution: \(p)"111 case .invalidPackage(let p, let e): "invalid package \(p): \(e)"112 case .misplaced(let p, let r, let v): "\(p) contains region \(r) version \(v): wrong directory or file name"113 case .unknownVersion(let r, let v): "region \(r) has no published version \(v)"114 case .io(let m): m115 }116 }117 }118119 public struct RegionReport: Sendable, Equatable {120 public var id: String121 public var latest: DataVersion122 public var versions: [DataVersion]123 public var pinned: Bool124 }125126 public struct Report: Sendable, Equatable {127 public var regions: [RegionReport]128 public var packagesVerified: Int129 public var written: [String]130 public var removed: [String]131 }132133 private struct Published {134 var manifest: PackageManifest135 var release: CatalogRelease136 }137138 /// Regenerates every document. Publication is atomic per file (temporary file + rename) and ordered so that a139 /// reader never sees a reference to something that is not there yet: `versions.json` and `<id>.json` of every140 /// region first, `catalog.json` last, documents of regions that disappeared removed after it.141 ///142 /// - Parameters:143 /// - setLatest: regions whose "latest" must point to a given published version (publisher rollback). The choice144 /// is stored in `pins.json` and stays in force until `unpin` names the region.145 public static func generate(distribution: URL, trust: TrustStore, generatedAt: Date = Date(), setLatest: [String: DataVersion] = [:],146 unpin: [String] = [], limits: PackageLimits = .standard) throws(BuildError) -> Report {147 let fm = FileManager.default148 let files = distribution.appendingPathComponent("files")149 var isDirectory: ObjCBool = false150 guard fm.fileExists(atPath: files.path, isDirectory: &isDirectory), isDirectory.boolValue else { throw .noFilesDirectory(distribution.path) }151 let verifier = PackageVerifier(trustStore: trust, limits: limits)152153 func list(_ url: URL) throws(BuildError) -> [String] {154 do { return try fm.contentsOfDirectory(atPath: url.path).filter { !$0.hasPrefix(".") }.sorted() } catch { throw .io(error.localizedDescription) }155 }156157 var published: [String: [Published]] = [:]158 var verified = 0159 for regionId in try list(files) {160 for version in try list(files.appendingPathComponent(regionId)) {161 let directory = files.appendingPathComponent(regionId).appendingPathComponent(version)162 for name in try list(directory) {163 let url = directory.appendingPathComponent(name)164 let relative = "files/\(regionId)/\(version)/\(name)"165 guard name == "\(regionId)-\(version).\(PackageFormat.fileExtension)" else { throw .unexpectedEntry(relative) }166 let package: VerifiedPackage167 do throws(PackageError) { package = try verifier.verify(at: url) } catch { throw .invalidPackage(path: relative, error: error) }168 let m = package.manifest169 guard m.regionId == regionId, m.dataVersion.rawValue == version else {170 throw .misplaced(path: relative, regionId: m.regionId, dataVersion: m.dataVersion.rawValue)171 }172 let digest: String173 do { digest = try sha256(of: url) } catch { throw .io(error.localizedDescription) }174 published[regionId, default: []].append(Published(175 manifest: m, release: CatalogRelease(manifest: m, preambleLength: package.preamble.header.preambleLength, fileSHA256: digest)))176 verified += 1177 }178 }179 }180181 // Pins.182 let pinsURL = distribution.appendingPathComponent(pinsFileName)183 var pins: [String: String] = [:]184 if let data = try? Data(contentsOf: pinsURL) { pins = (try? JSONDecoder().decode([String: String].self, from: data)) ?? [:] }185 for id in unpin { pins[id] = nil }186 for (id, version) in setLatest {187 guard published[id]?.contains(where: { $0.manifest.dataVersion == version }) == true else {188 throw .unknownVersion(regionId: id, dataVersion: version.rawValue)189 }190 pins[id] = version.rawValue191 }192 pins = pins.filter { id, version in published[id]?.contains { $0.manifest.dataVersion.rawValue == version } == true }193194 let stamp = Timestamp.format(generatedAt)195 var written: [String] = []196 var reports: [RegionReport] = []197 var catalogRegions: [CatalogRegion] = []198199 func write(_ data: Data, _ relative: String) throws(BuildError) {200 let url = distribution.appendingPathComponent(relative)201 do {202 try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)203 try data.write(to: url, options: .atomic)204 } catch { throw .io("cannot write \(relative): \(error.localizedDescription)") }205 written.append(relative)206 }207208 for id in published.keys.sorted() {209 let versions = (published[id] ?? []).sorted { $0.manifest.dataVersion > $1.manifest.dataVersion }210 guard let newest = versions.first else { continue }211 let latest = versions.first { $0.manifest.dataVersion.rawValue == pins[id] } ?? newest212 let detail = CatalogRegionDetail(manifest: latest.manifest, release: latest.release, generatedAt: stamp)213 let list = CatalogRegionVersions(generatedAt: stamp, id: id, latest: latest.manifest.dataVersion, versions: versions.map(\.release))214 do {215 try write(try list.encoded(), "regions/\(id)/versions.json")216 try write(try detail.encoded(), "regions/\(id).json")217 } catch let error as BuildError { throw error } catch { throw .io(error.localizedDescription) }218 catalogRegions.append(detail.region)219 reports.append(RegionReport(id: id, latest: latest.manifest.dataVersion, versions: versions.map(\.manifest.dataVersion), pinned: pins[id] != nil))220 }221222 do {223 if pins.isEmpty { try? fm.removeItem(at: pinsURL) } else {224 let encoder = JSONEncoder(); encoder.outputFormatting = [.prettyPrinted, .sortedKeys]225 try encoder.encode(pins).write(to: pinsURL, options: .atomic)226 }227 try write(try Catalog(generatedAt: stamp, regions: catalogRegions).encoded(), "catalog.json")228 } catch let error as BuildError { throw error } catch { throw .io(error.localizedDescription) }229230 // Documents of regions that have no package any more.231 var removed: [String] = []232 let regionsDirectory = distribution.appendingPathComponent("regions")233 for name in (try? fm.contentsOfDirectory(atPath: regionsDirectory.path)) ?? [] {234 let id = name.hasSuffix(".json") ? String(name.dropLast(5)) : name235 if published[id] == nil, !name.hasPrefix(".") {236 try? fm.removeItem(at: regionsDirectory.appendingPathComponent(name))237 removed.append("regions/\(name)")238 }239 }240 return Report(regions: reports, packagesVerified: verified, written: written, removed: removed.sorted())241 }242243 /// Verifies a package and copies it to its canonical place under `files/` (temporary file + rename).244 /// The catalog is not touched: call ``generate(distribution:trust:generatedAt:setLatest:unpin:limits:)`` afterwards.245 public static func addPackage(_ package: URL, to distribution: URL, trust: TrustStore) throws(BuildError) -> String {246 let verified: VerifiedPackage247 do throws(PackageError) { verified = try PackageVerifier(trustStore: trust).verify(at: package) } catch {248 throw .invalidPackage(path: package.path, error: error)249 }250 let relative = CatalogRelease.canonicalPath(regionId: verified.manifest.regionId, dataVersion: verified.manifest.dataVersion)251 let destination = distribution.appendingPathComponent(relative)252 let fm = FileManager.default253 do {254 try fm.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)255 let temp = destination.deletingLastPathComponent().appendingPathComponent(".incoming-\(UUID().uuidString.prefix(8))")256 try fm.copyItem(at: package, to: temp)257 guard rename(temp.path, destination.path) == 0 else {258 try? fm.removeItem(at: temp)259 throw BuildError.io("cannot move the package into place: errno \(errno)")260 }261 } catch let error as BuildError { throw error } catch { throw .io(error.localizedDescription) }262 return relative263 }264265 static func sha256(of url: URL) throws -> String {266 let handle = try FileHandle(forReadingFrom: url)267 defer { try? handle.close() }268 var hasher = SHA256()269 while let chunk = try handle.read(upToCount: 4 << 20), !chunk.isEmpty { hasher.update(data: chunk) }270 return hasher.finalize().map { String(format: "%02x", $0) }.joined()271 }272}273