SPB Git

Repository Public

FaviconStore.swift 9.6 KB 209 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Search iOS9// File             : Core/Sources/SPSearchKit/FaviconStore.swift10// Description      : Site icons relayed by the engine's own server: memory and11//                    disk cache, misses remembered, one request per icon.12// Module           : SPSearchKit13// Repository       : https://git.spboucher.ai/sp-search-ios14// Project Website  : https://search.spboucher.ai15// Created          : 2026-12-0116// Last Modified    : 2026-12-0117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import CryptoKit91import Foundation9293/// Icons come from `/v2/favicon` on the engine's server only; the third-party site is never contacted. A 404 is a94/// normal answer (the interface then draws a monogram) and is remembered for a day so it is not asked again.95public actor FaviconStore {96    public typealias Loader = @Sendable (URL) async -> (data: Data, status: Int, contentType: String?)?9798    static let allowedTypes: Set<String> = ["image/png", "image/x-icon", "image/vnd.microsoft.icon", "image/jpeg", "image/gif"]99    static let maxBytes = 512 << 10100    static let hitAge: TimeInterval = 7 * 86_400101    static let missAge: TimeInterval = 86_400102103    private let base: URL104    private let directory: URL?105    private let loader: Loader106    private let now: @Sendable () -> Date107    private let memoryLimit: Int108    private let diskLimit: Int109    private var memory: [String: Data?] = [:]110    private var order: [String] = []111    private var inFlight: [String: Task<Data?, Never>] = [:]112113    public init(base: URL = Endpoint.production, directory: URL? = FaviconStore.defaultDirectory(), memoryLimit: Int = 200,114                diskLimit: Int = 6 << 20, now: @escaping @Sendable () -> Date = { Date() }, loader: @escaping Loader) {115        self.base = base; self.directory = directory; self.loader = loader; self.now = now116        self.memoryLimit = memoryLimit; self.diskLimit = diskLimit117    }118119    public static func defaultDirectory() -> URL? {120        FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first?.appendingPathComponent("SPSearch/favicons", isDirectory: true)121    }122123    /// Loader on a URLSession (the app passes the same cookieless session as the API client).124    public static func loader(session: URLSession, userAgent: String) -> Loader {125        { url in126            var req = URLRequest(url: url)127            req.setValue(userAgent, forHTTPHeaderField: "User-Agent")128            req.setValue("image/png,image/x-icon,image/jpeg,image/gif", forHTTPHeaderField: "Accept")129            guard let (data, response) = try? await session.data(for: req), let http = response as? HTTPURLResponse else { return nil }130            return (data, http.statusCode, http.value(forHTTPHeaderField: "Content-Type"))131        }132    }133134    /// Image bytes for a result's `favicon` path, or nil when there is none (or the path is not on our server).135    public func data(path: String?) async -> Data? {136        guard let path, let url = Endpoint.favicon(path: path, base: base) else { return nil }137        let key = url.absoluteString138        if let known = memory[key] { return known }139        if let disk = readDisk(key) { remember(key, disk.data); return disk.data }140        if let running = inFlight[key] { return await running.value }141        let task = Task { [loader] () -> Data? in142            guard let r = await loader(url) else { return nil }           // transport failure: not remembered143            return Self.accept(r.data, status: r.status, contentType: r.contentType) ?? Data()144        }145        inFlight[key] = task146        let got = await task.value147        inFlight[key] = nil148        guard let got else { return nil }149        let image: Data? = got.isEmpty ? nil : got150        remember(key, image)151        writeDisk(key, image)152        return image153    }154155    /// Only a 200 with a raster image type of reasonable size is an icon. SVG is refused, as the contract promises none.156    static func accept(_ data: Data, status: Int, contentType: String?) -> Data? {157        guard status == 200, !data.isEmpty, data.count <= maxBytes else { return nil }158        let type = (contentType ?? "").split(separator: ";").first.map { $0.trimmingCharacters(in: .whitespaces).lowercased() } ?? ""159        return allowedTypes.contains(type) ? data : nil160    }161162    public func removeAll() {163        memory = [:]; order = []164        if let directory { try? FileManager.default.removeItem(at: directory) }165    }166167    private func remember(_ key: String, _ data: Data?) {168        memory[key] = .some(data)169        order.removeAll { $0 == key }170        order.append(key)171        while order.count > memoryLimit { memory[order.removeFirst()] = nil }172    }173174    private func file(_ key: String) -> URL? {175        directory?.appendingPathComponent(SHA256.hash(data: Data(key.utf8)).map { String(format: "%02x", $0) }.joined())176    }177178    /// An empty file is a remembered miss.179    private func readDisk(_ key: String) -> (data: Data?, Void)? {180        guard let f = file(key), let v = try? f.resourceValues(forKeys: [.contentModificationDateKey, .fileSizeKey]),181              let date = v.contentModificationDate else { return nil }182        let miss = (v.fileSize ?? 0) == 0183        guard now().timeIntervalSince(date) <= (miss ? Self.missAge : Self.hitAge) else {184            try? FileManager.default.removeItem(at: f)185            return nil186        }187        if miss { return (nil, ()) }188        guard let d = try? Data(contentsOf: f) else { return nil }189        return (d, ())190    }191192    private func writeDisk(_ key: String, _ data: Data?) {193        guard let f = file(key), let directory else { return }194        try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)195        try? (data ?? Data()).write(to: f, options: .atomic)196        guard let list = try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: [.fileSizeKey, .contentModificationDateKey]) else { return }197        var files = list.compactMap { u -> (URL, Int, Date)? in198            guard let v = try? u.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey]) else { return nil }199            return (u, v.fileSize ?? 0, v.contentModificationDate ?? .distantPast)200        }.sorted { $0.2 < $1.2 }201        var total = files.reduce(0) { $0 + $1.1 }202        while total > diskLimit || files.count > 2_000, !files.isEmpty {203            let old = files.removeFirst()204            try? FileManager.default.removeItem(at: old.0)205            total -= old.1206        }207    }208}209
Files main
Menu

Theme