SPB Git

Repository Public

NotesStore+Cache.swift 6.1 KB 118 lines swift

1// SP Notes Core2// File: Sources/SPNotesStore/NotesStore+Cache.swift3// Description: Offline copies of what the server computes (2.0): the knowledge events journal and a key/value4//              cache of read models (health, brief, graph views, insights, zoom levels), each with its fetch time.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910extension NotesStore {11    // MARK: - Events journal1213    private static let eventColumns = "id, at, kind, page_id, entity_kind, entity_id, actor, device, summary, data, fetched_at"1415    private static func decodeEvent(_ r: Row) -> EventRecord {16        EventRecord(id: r.string(0), at: r.date(1), kind: r.string(2), pageId: r.optString(3), entityKind: r.optString(4), entityId: r.optString(5),17                    actor: r.string(6), device: r.optString(7), summary: r.string(8), data: r.optData(9), fetchedAt: r.date(10))18    }1920    /// Stores (inserting or replacing by id) events fetched from the server. Events are facts: nothing is ever21    /// generated locally.22    public func cacheEvents(_ events: [EventRecord], fetchedAt: Date = Date()) throws {23        guard !events.isEmpty else { return }24        try write {25            for e in events {26                try db.run("""27                INSERT INTO events(id, at, kind, page_id, entity_kind, entity_id, actor, device, summary, data, fetched_at)28                VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)29                ON CONFLICT(id) DO UPDATE SET at=excluded.at, kind=excluded.kind, page_id=excluded.page_id, entity_kind=excluded.entity_kind,30                    entity_id=excluded.entity_id, actor=excluded.actor, device=excluded.device, summary=excluded.summary, data=excluded.data,31                    fetched_at=excluded.fetched_at32                """, [e.id, e.at, e.kind, e.pageId, e.entityKind, e.entityId, e.actor, e.device, e.summary, e.data, fetchedAt])33            }34            pending.events = true35        }36    }3738    /// Cached events, newest first.39    public func events(_ query: EventQuery = EventQuery()) throws -> [EventRecord] {40        var sql = "SELECT \(Self.eventColumns) FROM events WHERE 1"41        var params: [any SQLBindable] = []42        if let pageId = query.pageId { sql += " AND page_id=?"; params.append(pageId) }43        if !query.kinds.isEmpty {44            sql += " AND kind IN (\(query.kinds.map { _ in "?" }.joined(separator: ",")))"45            params.append(contentsOf: query.kinds)46        }47        if let prefix = query.kindPrefix, !prefix.isEmpty { sql += " AND substr(kind, 1, ?)=?"; params.append(prefix.count); params.append(prefix) }48        if let from = query.from { sql += " AND at>=?"; params.append(from) }49        if let to = query.to { sql += " AND at<=?"; params.append(to) }50        if let actor = query.actor { sql += " AND actor=?"; params.append(actor) }51        sql += " ORDER BY at DESC, id LIMIT ? OFFSET ?"52        params.append(max(query.limit, 0)); params.append(max(query.offset, 0))53        return try db.query(sql, params, Self.decodeEvent)54    }5556    public func eventCount() throws -> Int { Int(try db.scalar("SELECT count(*) FROM events")) }5758    /// The moment of the most recent cached event (where an incremental fetch resumes), nil when the cache is empty.59    public func latestEventDate() throws -> Date? {60        try db.first("SELECT max(at) FROM events") { $0.optDate(0) } ?? nil61    }6263    /// Removes cached events: all, or those that happened before a date. Returns how many.64    @discardableResult65    public func clearEvents(before: Date? = nil) throws -> Int {66        try write {67            let removed = try before.map { try db.run("DELETE FROM events WHERE at<?", [$0]) } ?? db.run("DELETE FROM events")68            if removed > 0 { pending.events = true }69            return removed70        }71    }7273    // MARK: - Read-model cache7475    /// Stores a server answer under `key` (see `CacheKey`) with the moment it was fetched.76    public func setCached(_ key: String, json: Data, fetchedAt: Date = Date(), etag: String? = nil) throws {77        guard !key.isEmpty else { throw StoreError.invalid("empty cache key") }78        try write {79            try db.run("INSERT INTO kv_cache(key, json, fetched_at, etag) VALUES(?, ?, ?, ?) ON CONFLICT(key) DO UPDATE SET json=excluded.json, fetched_at=excluded.fetched_at, etag=excluded.etag",80                       [key, json, fetchedAt, etag])81            pending.cache.append(key)82        }83    }8485    /// Encodes and stores a value.86    public func setCached<T: Encodable & Sendable>(_ key: String, value: T, fetchedAt: Date = Date(), etag: String? = nil) throws {87        let encoder = JSONEncoder()88        encoder.outputFormatting = [.sortedKeys]89        try setCached(key, json: try encoder.encode(value), fetchedAt: fetchedAt, etag: etag)90    }9192    public func cached(_ key: String) throws -> CachedValue? {93        try db.first("SELECT key, json, fetched_at, etag FROM kv_cache WHERE key=?", [key]) {94            CachedValue(key: $0.string(0), json: $0.data(1), fetchedAt: $0.date(2), etag: $0.optString(3))95        }96    }9798    /// The keys present, with their fetch time (diagnostics, "last updated" labels).99    public func cachedKeys(prefix: String = "") throws -> [String: Date] {100        var out: [String: Date] = [:]101        _ = try db.query("SELECT key, fetched_at FROM kv_cache WHERE substr(key, 1, ?)=?", [prefix.count, prefix]) { out[$0.string(0)] = $0.date(1) }102        return out103    }104105    /// Removes one key, or every key starting with `prefix` (empty prefix = the whole cache). Returns how many.106    @discardableResult107    public func removeCached(key: String? = nil, prefix: String? = nil) throws -> Int {108        try write {109            var keys: [String] = []110            if let key { keys = try db.query("SELECT key FROM kv_cache WHERE key=?", [key]) { $0.string(0) } }111            if let prefix { keys += try db.query("SELECT key FROM kv_cache WHERE substr(key, 1, ?)=?", [prefix.count, prefix]) { $0.string(0) } }112            for k in Set(keys) { try db.run("DELETE FROM kv_cache WHERE key=?", [k]) }113            pending.cache.append(contentsOf: Set(keys).sorted())114            return Set(keys).count115        }116    }117}118
Files main
Menu

Theme