Repository Public License
1// Persistence — shared plumbing of the stores: ghost registry, ownership checks, JSON columns, frecency maths.2import Foundation3import NavigatorCore4import Synchronization56/// Remembers which identifiers belong to ghost (private) profiles during this process, so a write that7/// references one fails with `ghostWriteRejected` instead of a generic "owner not persisted".8///9/// The registry is an *explanation* aid, not the safety mechanism: the safety mechanism is that a ghost profile10/// is never inserted, so nothing that requires a stored owner can be written for it.11public final class GhostRegistry: Sendable {12 private let identifiers = Mutex<Set<UUID>>([])1314 public init() {}1516 /// Declares a ghost profile and, optionally, the spaces and windows the app created for it.17 public func declare(profile: ProfileID, spaces: [SpaceID] = [], windows: [WindowID] = []) {18 identifiers.withLock { set in19 set.insert(profile.raw)20 for space in spaces { set.insert(space.raw) }21 for window in windows { set.insert(window.raw) }22 }23 }2425 public func declare(space: SpaceID) { identifiers.withLock { _ = $0.insert(space.raw) } }26 public func declare(window: WindowID) { identifiers.withLock { _ = $0.insert(window.raw) } }2728 public func contains(_ identifier: UUID) -> Bool { identifiers.withLock { $0.contains(identifier) } }2930 /// Forgets a ghost session once the app has discarded it.31 public func forget(profile: ProfileID, spaces: [SpaceID] = [], windows: [WindowID] = []) {32 identifiers.withLock { set in33 set.remove(profile.raw)34 for space in spaces { set.remove(space.raw) }35 for window in windows { set.remove(window.raw) }36 }37 }38}3940/// What every store holds: the connection set and the ghost registry.41struct StoreContext: Sendable {42 let database: SQLiteDatabase43 let ghosts: GhostRegistry4445 func read<T: Sendable>(_ body: @Sendable (SQLiteConnection) throws -> T) async throws -> T {46 try await database.read(body)47 }4849 @discardableResult50 func transaction<T: Sendable>(_ body: @Sendable (SQLiteConnection) throws -> T) async throws -> T {51 try await database.transaction(body)52 }5354 // MARK: Ownership checks (run inside the write transaction)5556 func requireProfile(_ id: ProfileID, _ connection: SQLiteConnection) throws {57 if ghosts.contains(id.raw) { throw PersistenceError.ghostWriteRejected(entity: "profile \(id)") }58 guard try connection.scalar("SELECT 1 FROM profiles WHERE id = ?", [id], as: Int.self) != nil else {59 throw PersistenceError.ownerNotPersisted(owner: "profile", id: id.string)60 }61 }6263 func requireSpace(_ id: SpaceID, _ connection: SQLiteConnection) throws {64 if ghosts.contains(id.raw) { throw PersistenceError.ghostWriteRejected(entity: "space \(id)") }65 guard try connection.scalar("SELECT 1 FROM spaces WHERE id = ?", [id], as: Int.self) != nil else {66 throw PersistenceError.ownerNotPersisted(owner: "space", id: id.string)67 }68 }6970 func requireWindow(_ id: WindowID, _ connection: SQLiteConnection) throws {71 if ghosts.contains(id.raw) { throw PersistenceError.ghostWriteRejected(entity: "window \(id)") }72 guard try connection.scalar("SELECT 1 FROM windows WHERE id = ?", [id], as: Int.self) != nil else {73 throw PersistenceError.ownerNotPersisted(owner: "window", id: id.string)74 }75 }7677 /// Optional space link of notes, canvases and agent runs: `nil` is allowed, a ghost or unknown space is not.78 func requireSpaceIfPresent(_ id: SpaceID?, _ connection: SQLiteConnection) throws {79 if let id { try requireSpace(id, connection) }80 }81}8283/// JSON columns hold nested value types. Dates inside them use seconds since 1970, like the REAL columns.84enum JSONColumn {85 static func encode<T: Encodable>(_ value: T) throws -> String {86 let encoder = JSONEncoder()87 encoder.dateEncodingStrategy = .secondsSince197088 encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]89 return String(decoding: try encoder.encode(value), as: UTF8.self)90 }9192 static func decode<T: Decodable>(_ type: T.Type, from text: String) throws -> T {93 let decoder = JSONDecoder()94 decoder.dateDecodingStrategy = .secondsSince197095 do {96 return try decoder.decode(type, from: Data(text.utf8))97 } catch {98 throw PersistenceError.invalidData("JSON column does not decode as \(T.self)")99 }100 }101}102103extension SQLiteRow {104 func json<T: Decodable>(_ column: String, as type: T.Type = T.self) throws -> T {105 try JSONColumn.decode(type, from: try get(column, as: String.self))106 }107108 func jsonIfPresent<T: Decodable>(_ column: String, as type: T.Type = T.self) throws -> T? {109 guard let text = try get(column, as: String?.self) else { return nil }110 return try JSONColumn.decode(type, from: text)111 }112}113114/// Frecency ("frequency + recency") of a history URL.115///116/// Each visit contributes `weight · 2^(-(age / halfLife))`. Stored naively that score would have to be117/// recomputed for every row as time passes. Instead the column stores118/// `ln Σ weightᵢ · e^{λ·(tᵢ − epoch)}`: every row is scaled by the same factor `e^{λ·(now − epoch)}`, so the119/// *ordering* never changes with time, an index on the column stays valid forever, and adding a visit is one120/// log-sum-exp update. The constants are part of the stored format: changing them requires a migration that121/// recomputes the column.122public enum Frecency {123 /// Stored for a URL with no ranking visits (only reloads or session restores).124 public static let none: Double = -1_000125 public static let halfLife: TimeInterval = 30 * 86_400126 /// 2020-01-01T00:00:00Z. Keeps the exponent small; any fixed instant would do.127 static let epoch: TimeInterval = 1_577_836_800128 static let lambda = log(2.0) / halfLife129 /// Additive bonus (in log space, so a ×4 factor) when the typed text is a prefix of the host.130 static let hostPrefixBoost = log(4.0)131132 /// How much a visit counts. Reloads and session restores say nothing about interest in a page.133 public static func weight(of transition: NavigationEntry.Transition) -> Double {134 switch transition {135 case .typed: return 2.0136 case .link, .formSubmit: return 1.0137 case .agent, .other: return 0.5138 case .redirect, .backForward: return 0.25139 case .reload, .restore: return 0140 }141 }142143 /// Folds one visit into a stored score.144 public static func adding(to stored: Double, weight: Double, at date: Date) -> Double {145 guard weight > 0 else { return stored }146 let term = log(weight) + lambda * (date.timeIntervalSince1970 - epoch)147 let high = max(stored, term)148 return high + log(exp(stored - high) + exp(term - high))149 }150151 /// The decayed visit count at `now`: "this URL is worth N fresh link visits". For display and tests.152 public static func effectiveVisits(stored: Double, now: Date = .now) -> Double {153 exp(stored - lambda * (now.timeIntervalSince1970 - epoch))154 }155156 /// Host used for matching and for per-site deletion: lowercased, without a leading `www.`.157 public static func hostKey(_ host: String) -> String {158 let lower = host.lowercased()159 return lower.hasPrefix("www.") ? String(lower.dropFirst(4)) : lower160 }161}162163extension URL {164 /// ASCII (punycode) host, lowercased; empty for URLs without one (`about:blank`, `file:`).165 var persistenceHost: String {166 URLComponents(url: self, resolvingAgainstBaseURL: true)?.encodedHost?.lowercased() ?? ""167 }168}169170/// `LIKE` pattern helpers. User text is always bound, and its `%`, `_` and `\` are escaped (`ESCAPE '\'`).171enum LikePattern {172 static func escape(_ text: String) -> String {173 var result = ""174 for character in text {175 if character == "%" || character == "_" || character == "\\" { result.append("\\") }176 result.append(character)177 }178 return result179 }180181 static func contains(_ text: String) -> String { "%" + escape(text) + "%" }182}183