Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Search iOS9// File : Core/Sources/SPSearchKit/ResponseCache.swift10// Description : Short-lived cache of API answers: memory first, a bounded11// folder on disk when allowed, dropped when the index moves12// on.13// Module : SPSearchKit14// Repository : https://git.spboucher.ai/sp-search-ios15// Project Website : https://search.spboucher.ai16// Created : 2026-12-0117// Last Modified : 2026-12-0118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author : Simon-Pierre Boucher24// Position : Professor of Finance25// Institution : Université du Québec en Outaouais (UQO)26// Department : Département des sciences administratives27// Organization : SP Boucher28//29// Website : https://spboucher.ai30// Git : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General : info@spboucher.ai37// Professional : contact@spboucher.ai38// Direct : simon@spboucher.ai39// Research : research@spboucher.ai40// Development : dev@spboucher.ai41// Support : support@spboucher.ai42// Security/Admin : admin@spboucher.ai43// Notifications : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification : Public70// Distribution : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License : None specified (no license file in this repository)84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import CryptoKit92import Foundation9394/// Answers of the engine kept for a short while so that going back to a search, or paging back, costs no request.95/// An entry is served only while it is younger than the age the caller accepts, and never once the server has96/// announced a newer index than the one that produced it. The disk copy is optional (the app switches it off97/// with the history: nothing about a search then outlives the process) and bounded in bytes.98public actor ResponseCache {99 struct Entry: Codable {100 var key: String101 var storedAt: Date102 var indexVersion: Int103 var body: Data104 }105106 private var memory: [String: Entry] = [:]107 private var order: [String] = []108 private var knownIndexVersion = 0109 private var persistent: Bool110 private let directory: URL?111 private let memoryLimit: Int112 private let diskLimit: Int113 private let now: @Sendable () -> Date114115 /// - Parameter directory: folder for the disk copy; nil keeps everything in memory.116 public init(directory: URL? = nil, persistent: Bool = true, memoryLimit: Int = 48, diskLimit: Int = 4 << 20,117 now: @escaping @Sendable () -> Date = { Date() }) {118 self.directory = directory; self.persistent = persistent && directory != nil119 self.memoryLimit = max(1, memoryLimit); self.diskLimit = diskLimit; self.now = now120 }121122 /// The app's cache folder for answers (`Library/Caches/SPSearch/responses`): the system may empty it at any time.123 public static func defaultDirectory() -> URL? {124 FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first?.appendingPathComponent("SPSearch/responses", isDirectory: true)125 }126127 public func data(for key: String, maxAge: TimeInterval) -> Data? {128 var entry = memory[key]129 if entry == nil, persistent, let file = file(key), let raw = try? Data(contentsOf: file),130 let e = try? PropertyListDecoder().decode(Entry.self, from: raw), e.key == key {131 entry = e132 }133 guard let e = entry else { return nil }134 let age = now().timeIntervalSince(e.storedAt)135 guard age >= 0, age <= maxAge, e.indexVersion == 0 || e.indexVersion >= knownIndexVersion else {136 remove(key)137 return nil138 }139 remember(e)140 return e.body141 }142143 /// - Parameter indexVersion: version of the index that produced the answer; 0 when the answer does not depend on it.144 public func store(_ body: Data, for key: String, indexVersion: Int = 0, onDisk: Bool = true) {145 let e = Entry(key: key, storedAt: now(), indexVersion: indexVersion, body: body)146 remember(e)147 guard persistent, onDisk, let file = file(key), let directory else { return }148 try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)149 if let raw = try? PropertyListEncoder().encode(e) {150 try? raw.write(to: file, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])151 trimDisk()152 }153 }154155 /// The server announced this index version: answers computed on an older index are forgotten.156 public func noteIndexVersion(_ version: Int) {157 guard version > knownIndexVersion else { return }158 knownIndexVersion = version159 for (k, e) in memory where e.indexVersion != 0 && e.indexVersion < version { memory[k] = nil; order.removeAll { $0 == k } }160 // Disk entries of an older index are refused when read, and trimmed by age.161 }162163 public func setPersistent(_ on: Bool) {164 let wanted = on && directory != nil165 if persistent, !wanted { wipeDisk() }166 persistent = wanted167 }168169 public func removeAll() {170 memory = [:]; order = []171 wipeDisk()172 }173174 public var isPersistent: Bool { persistent }175 public var memoryCount: Int { memory.count }176 public func diskBytes() -> Int { files().reduce(0) { $0 + $1.size } }177178 // MARK: Internals179180 private func remember(_ e: Entry) {181 memory[e.key] = e182 order.removeAll { $0 == e.key }183 order.append(e.key)184 while order.count > memoryLimit { memory[order.removeFirst()] = nil }185 }186187 private func remove(_ key: String) {188 memory[key] = nil189 order.removeAll { $0 == key }190 if let f = file(key) { try? FileManager.default.removeItem(at: f) }191 }192193 /// The file name is a digest: a query never appears in a file name.194 private func file(_ key: String) -> URL? {195 guard let directory else { return nil }196 let digest = SHA256.hash(data: Data(key.utf8)).map { String(format: "%02x", $0) }.joined()197 return directory.appendingPathComponent(digest + ".plist")198 }199200 private func files() -> [(url: URL, size: Int, date: Date)] {201 guard let directory, let list = try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: [.fileSizeKey, .contentModificationDateKey]) else { return [] }202 return list.compactMap { u in203 guard let v = try? u.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey]) else { return nil }204 return (u, v.fileSize ?? 0, v.contentModificationDate ?? .distantPast)205 }206 }207208 /// Oldest files go first until the folder fits its budget.209 private func trimDisk() {210 var list = files().sorted { $0.date < $1.date }211 var total = list.reduce(0) { $0 + $1.size }212 while total > diskLimit, !list.isEmpty {213 let f = list.removeFirst()214 try? FileManager.default.removeItem(at: f.url)215 total -= f.size216 }217 }218219 private func wipeDisk() {220 guard let directory else { return }221 try? FileManager.default.removeItem(at: directory)222 }223}224