Repository Public License
1import Foundation2import NavigatorCore34// MARK: - Downloads56public struct DownloadStore: Sendable {7 let context: StoreContext89 public func save(_ download: Download) async throws {10 try await context.transaction { connection in11 try context.requireProfile(download.profileID, connection)12 try download.save(connection)13 }14 }1516 /// Cheap progress update while bytes arrive (the caller throttles it).17 public func updateProgress(_ id: DownloadID, bytesReceived: Int64, totalBytes: Int64?) async throws {18 try await context.transaction {19 _ = try $0.execute("UPDATE downloads SET bytes_received = ?, total_bytes = ? WHERE id = ?",20 [bytesReceived, totalBytes, id])21 }22 }2324 public func download(_ id: DownloadID) async throws -> Download? {25 try await context.read { try $0.queryOne("SELECT * FROM downloads WHERE id = ?", [id]).map(Download.init(row:)) }26 }2728 /// Downloads of a profile, most recent first, optionally restricted to some states.29 public func downloads(profile: ProfileID, states: Set<Download.State>? = nil, limit: Int = 500) async throws -> [Download] {30 let all = try await context.read { connection in31 try connection.query("SELECT * FROM downloads WHERE profile_id = ? ORDER BY started_at DESC, id LIMIT ?",32 [profile, limit]).map(Download.init(row:))33 }34 guard let states else { return all }35 return all.filter { states.contains($0.state) }36 }3738 /// Downloads that were pending or running when the app last stopped, across profiles: after a crash they39 /// must be resumed or marked failed by the download engine.40 public func interrupted() async throws -> [Download] {41 try await context.read { connection in42 try connection.query("SELECT * FROM downloads WHERE state IN ('pending', 'running') ORDER BY started_at, id")43 .map(Download.init(row:))44 }45 }4647 public func delete(_ id: DownloadID) async throws {48 try await context.transaction { _ = try $0.execute("DELETE FROM downloads WHERE id = ?", [id]) }49 }5051 /// Removes finished, failed and cancelled entries from the list (the files themselves are not touched).52 @discardableResult53 public func clearInactive(profile: ProfileID) async throws -> Int {54 try await context.transaction {55 try $0.execute("""56 DELETE FROM downloads WHERE profile_id = ? AND state IN ('finished', 'failed', 'cancelled')57 """, [profile])58 }59 }60}6162// MARK: - Permissions6364/// Per-origin permission decisions. There is at most one decision per (profile, origin, kind).65public struct PermissionStore: Sendable {66 let context: StoreContext6768 /// Stores a decision, replacing the previous one for the same profile, origin and kind.69 public func set(_ decision: PermissionDecision) async throws {70 try await context.transaction { connection in71 try context.requireProfile(decision.profileID, connection)72 try connection.execute("""73 INSERT INTO permissions (id, profile_id, origin_scheme, origin_host, origin_port, kind, verdict,74 decided_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)75 ON CONFLICT(profile_id, origin_scheme, origin_host, origin_port, kind) DO UPDATE SET76 id = excluded.id, verdict = excluded.verdict, decided_at = excluded.decided_at,77 expires_at = excluded.expires_at78 """, [decision.id, decision.profileID, decision.origin.scheme, decision.origin.host,79 decision.origin.port ?? -1, decision.kind.rawValue, decision.verdict.rawValue,80 decision.decidedAt, decision.expiresAt])81 }82 }8384 /// The decision in force at `date`, or `nil` when there is none or it has expired.85 public func decision(profile: ProfileID, origin: WebOrigin, kind: PermissionKind,86 at date: Date = .now) async throws -> PermissionDecision? {87 try await context.read { connection in88 try connection.queryOne("""89 SELECT * FROM permissions90 WHERE profile_id = ? AND origin_scheme = ? AND origin_host = ? AND origin_port = ? AND kind = ?91 AND (expires_at IS NULL OR expires_at > ?)92 """, [profile, origin.scheme, origin.host, origin.port ?? -1, kind.rawValue, date])93 .map(PermissionDecision.init(row:))94 }95 }9697 /// The verdict in force, `.ask` when nothing (unexpired) is stored.98 public func verdict(profile: ProfileID, origin: WebOrigin, kind: PermissionKind,99 at date: Date = .now) async throws -> PermissionDecision.Verdict {100 try await decision(profile: profile, origin: origin, kind: kind, at: date)?.verdict ?? .ask101 }102103 /// All stored decisions of a profile, optionally for one origin. Expired ones are included unless104 /// `activeAt` is given.105 public func decisions(profile: ProfileID, origin: WebOrigin? = nil, activeAt date: Date? = nil) async throws -> [PermissionDecision] {106 try await context.read { connection in107 try connection.query("""108 SELECT * FROM permissions WHERE profile_id = ?1109 AND (?2 IS NULL OR (origin_scheme = ?2 AND origin_host = ?3 AND origin_port = ?4))110 AND (?5 IS NULL OR expires_at IS NULL OR expires_at > ?5)111 ORDER BY origin_host, origin_scheme, origin_port, kind112 """, [profile, origin?.scheme, origin?.host, origin.map { $0.port ?? -1 }, date])113 .map(PermissionDecision.init(row:))114 }115 }116117 public func remove(_ id: PermissionID) async throws {118 try await context.transaction { _ = try $0.execute("DELETE FROM permissions WHERE id = ?", [id]) }119 }120121 /// Forgets every decision of a profile, or only those of one origin.122 @discardableResult123 public func removeAll(profile: ProfileID, origin: WebOrigin? = nil) async throws -> Int {124 try await context.transaction { connection in125 try connection.execute("""126 DELETE FROM permissions WHERE profile_id = ?1127 AND (?2 IS NULL OR (origin_scheme = ?2 AND origin_host = ?3 AND origin_port = ?4))128 """, [profile, origin?.scheme, origin?.host, origin.map { $0.port ?? -1 }])129 }130 }131132 /// Deletes decisions whose expiry has passed.133 @discardableResult134 public func purgeExpired(at date: Date = .now) async throws -> Int {135 try await context.transaction {136 try $0.execute("DELETE FROM permissions WHERE expires_at IS NOT NULL AND expires_at <= ?", [date])137 }138 }139}140141// MARK: - Archives and snapshots142143/// Metadata of offline archives. The archived bytes live in files owned by the archive module; deleting a row144/// here does not delete its file (deletion APIs return the paths so the owner can).145public struct ArchiveStore: Sendable {146 let context: StoreContext147148 public func save(_ archive: Archive) async throws {149 try await context.transaction { connection in150 try context.requireProfile(archive.profileID, connection)151 try archive.save(connection)152 }153 }154155 public func archive(_ id: ArchiveID) async throws -> Archive? {156 try await context.read { try $0.queryOne("SELECT * FROM archives WHERE id = ?", [id]).map(Archive.init(row:)) }157 }158159 /// Archives of a profile, most recent first, optionally for one URL.160 public func archives(profile: ProfileID, url: URL? = nil, limit: Int = 500) async throws -> [Archive] {161 try await context.read { connection in162 try connection.query("""163 SELECT * FROM archives WHERE profile_id = ?1 AND (?2 IS NULL OR url = ?2)164 ORDER BY captured_at DESC, id LIMIT ?3165 """, [profile, url, limit]).map(Archive.init(row:))166 }167 }168169 /// Deletes the row and returns it, so the caller can remove `relativePath` from disk.170 @discardableResult171 public func delete(_ id: ArchiveID) async throws -> Archive? {172 try await context.transaction { connection in173 let archive = try connection.queryOne("SELECT * FROM archives WHERE id = ?", [id]).map(Archive.init(row:))174 try connection.execute("DELETE FROM archives WHERE id = ?", [id])175 return archive176 }177 }178}179180public struct SnapshotStore: Sendable {181 let context: StoreContext182183 public func save(_ snapshot: PageSnapshot) async throws {184 try await context.transaction { connection in185 try context.requireProfile(snapshot.profileID, connection)186 try snapshot.save(connection)187 }188 }189190 public func snapshot(_ id: SnapshotID) async throws -> PageSnapshot? {191 try await context.read {192 try $0.queryOne("SELECT * FROM page_snapshots WHERE id = ?", [id]).map(PageSnapshot.init(row:))193 }194 }195196 /// Snapshots of a profile, most recent first; pass `url` for the timeline of one page.197 public func snapshots(profile: ProfileID, url: URL? = nil, limit: Int = 200) async throws -> [PageSnapshot] {198 try await context.read { connection in199 try connection.query("""200 SELECT * FROM page_snapshots WHERE profile_id = ?1 AND (?2 IS NULL OR url = ?2)201 ORDER BY taken_at DESC, id LIMIT ?3202 """, [profile, url, limit]).map(PageSnapshot.init(row:))203 }204 }205206 public func delete(_ id: SnapshotID) async throws {207 try await context.transaction { _ = try $0.execute("DELETE FROM page_snapshots WHERE id = ?", [id]) }208 }209}210211// MARK: - Notes, canvases, agent runs, workflows212213public struct NoteStore: Sendable {214 let context: StoreContext215216 public func save(_ note: Note) async throws {217 try await context.transaction { connection in218 try context.requireSpaceIfPresent(note.spaceID, connection)219 try note.save(connection)220 }221 }222223 public func note(_ id: NoteID) async throws -> Note? {224 try await context.read { try $0.queryOne("SELECT * FROM notes WHERE id = ?", [id]).map(Note.init(row:)) }225 }226227 /// Notes, most recently edited first. `space` and `url` narrow the list when given.228 public func notes(space: SpaceID? = nil, url: URL? = nil, limit: Int = 500) async throws -> [Note] {229 try await context.read { connection in230 try connection.query("""231 SELECT * FROM notes WHERE (?1 IS NULL OR space_id = ?1) AND (?2 IS NULL OR url = ?2)232 ORDER BY updated_at DESC, id LIMIT ?3233 """, [space, url, limit]).map(Note.init(row:))234 }235 }236237 /// Case-insensitive substring search over title, body and quote.238 public func search(_ text: String, limit: Int = 100) async throws -> [Note] {239 let needle = text.trimmingCharacters(in: .whitespacesAndNewlines)240 guard !needle.isEmpty else { return [] }241 let pattern = LikePattern.contains(needle)242 return try await context.read { connection in243 try connection.query("""244 SELECT * FROM notes245 WHERE title LIKE ?1 ESCAPE '\\' OR body LIKE ?1 ESCAPE '\\' OR quote LIKE ?1 ESCAPE '\\'246 ORDER BY updated_at DESC, id LIMIT ?2247 """, [pattern, limit]).map(Note.init(row:))248 }249 }250251 public func delete(_ id: NoteID) async throws {252 try await context.transaction { _ = try $0.execute("DELETE FROM notes WHERE id = ?", [id]) }253 }254}255256public struct CanvasStore: Sendable {257 let context: StoreContext258259 public func save(_ document: CanvasDocument) async throws {260 try await context.transaction { connection in261 try context.requireSpaceIfPresent(document.spaceID, connection)262 try document.save(connection)263 }264 }265266 public func document(_ id: CanvasID) async throws -> CanvasDocument? {267 try await context.read {268 try $0.queryOne("SELECT * FROM canvas_documents WHERE id = ?", [id]).map(CanvasDocument.init(row:))269 }270 }271272 /// Canvases, most recently edited first.273 public func documents(space: SpaceID? = nil) async throws -> [CanvasDocument] {274 try await context.read { connection in275 try connection.query("""276 SELECT * FROM canvas_documents WHERE (?1 IS NULL OR space_id = ?1) ORDER BY updated_at DESC, id277 """, [space]).map(CanvasDocument.init(row:))278 }279 }280281 public func delete(_ id: CanvasID) async throws {282 try await context.transaction { _ = try $0.execute("DELETE FROM canvas_documents WHERE id = ?", [id]) }283 }284}285286public struct AgentRunStore: Sendable {287 let context: StoreContext288289 /// Inserts or updates a run with its steps and citations (the agent runtime saves after each step).290 public func save(_ run: AgentRun) async throws {291 try await context.transaction { connection in292 try context.requireSpaceIfPresent(run.spaceID, connection)293 try run.save(connection)294 }295 }296297 public func run(_ id: AgentRunID) async throws -> AgentRun? {298 try await context.read { try $0.queryOne("SELECT * FROM agent_runs WHERE id = ?", [id]).map(AgentRun.init(row:)) }299 }300301 /// Runs, most recent first.302 public func runs(space: SpaceID? = nil, limit: Int = 100) async throws -> [AgentRun] {303 try await context.read { connection in304 try connection.query("""305 SELECT * FROM agent_runs WHERE (?1 IS NULL OR space_id = ?1) ORDER BY started_at DESC, id LIMIT ?2306 """, [space, limit]).map(AgentRun.init(row:))307 }308 }309310 /// Runs still `running` or `awaitingConfirmation`: after a crash nobody is driving them any more.311 public func unfinished() async throws -> [AgentRun] {312 try await context.read { connection in313 try connection.query("""314 SELECT * FROM agent_runs WHERE status IN ('running', 'awaitingConfirmation') ORDER BY started_at, id315 """).map(AgentRun.init(row:))316 }317 }318319 public func delete(_ id: AgentRunID) async throws {320 try await context.transaction { _ = try $0.execute("DELETE FROM agent_runs WHERE id = ?", [id]) }321 }322}323324public struct WorkflowStore: Sendable {325 let context: StoreContext326327 public func save(_ workflow: Workflow) async throws {328 try await context.transaction { try workflow.save($0) }329 }330331 public func workflow(_ id: WorkflowID) async throws -> Workflow? {332 try await context.read { try $0.queryOne("SELECT * FROM workflows WHERE id = ?", [id]).map(Workflow.init(row:)) }333 }334335 public func all() async throws -> [Workflow] {336 try await context.read {337 try $0.query("SELECT * FROM workflows ORDER BY name COLLATE NOCASE, id").map(Workflow.init(row:))338 }339 }340341 public func markRun(_ id: WorkflowID, at date: Date = .now) async throws {342 try await context.transaction {343 _ = try $0.execute("UPDATE workflows SET last_run_at = ? WHERE id = ?", [date, id])344 }345 }346347 public func delete(_ id: WorkflowID) async throws {348 try await context.transaction { _ = try $0.execute("DELETE FROM workflows WHERE id = ?", [id]) }349 }350}351352// MARK: - Sync records353354/// Change tracking for the Bridge (sync) module.355///356/// `localVersion` is a counter stored in the database that only ever grows: every local change takes the next357/// value, and applying a remote record lifts the counter to at least that record's version (Lamport clock).358/// There is one record per (entity, entityID); a deletion keeps the record as a tombstone.359public struct SyncStore: Sendable {360 let context: StoreContext361362 static let versionKey = "sync.local_version"363364 static func nextVersion(_ connection: SQLiteConnection, atLeast floor: Int64 = 0) throws -> Int64 {365 let current = try connection.scalar("SELECT value FROM app_state WHERE key = ?", [versionKey], as: String.self)366 .flatMap(Int64.init) ?? 0367 let next = max(current, floor) + 1368 try connection.execute("""369 INSERT INTO app_state (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value370 """, [versionKey, String(next)])371 return next372 }373374 private static func upsert(_ connection: SQLiteConnection, entity: SyncRecord.Entity, entityID: String,375 version: Int64, deviceID: String, modifiedAt: Date, deletedAt: Date?,376 payloadHash: String?) throws -> SyncRecord {377 try connection.execute("""378 INSERT INTO sync_records (id, entity, entity_id, version, device_id, modified_at, deleted_at, payload_hash)379 VALUES (?, ?, ?, ?, ?, ?, ?, ?)380 ON CONFLICT(entity, entity_id) DO UPDATE SET version = excluded.version, device_id = excluded.device_id,381 modified_at = excluded.modified_at, deleted_at = excluded.deleted_at, payload_hash = excluded.payload_hash382 """, [SyncRecordID(), entity.rawValue, entityID, version, deviceID, modifiedAt, deletedAt, payloadHash])383 guard let row = try connection.queryOne("SELECT * FROM sync_records WHERE entity = ? AND entity_id = ?",384 [entity.rawValue, entityID]) else {385 throw PersistenceError.notFound(entity: "sync record", id: entityID)386 }387 return try SyncRecord(row: row)388 }389390 /// Records a local creation or modification and returns the record with its new version. A previous391 /// tombstone for the same entity is cleared (the entity was recreated).392 @discardableResult393 public func recordChange(entity: SyncRecord.Entity, entityID: String, deviceID: String,394 payloadHash: String? = nil, at date: Date = .now) async throws -> SyncRecord {395 try await context.transaction { connection in396 try Self.upsert(connection, entity: entity, entityID: entityID, version: try Self.nextVersion(connection),397 deviceID: deviceID, modifiedAt: date, deletedAt: nil, payloadHash: payloadHash)398 }399 }400401 /// Records a local deletion as a tombstone.402 @discardableResult403 public func recordDeletion(entity: SyncRecord.Entity, entityID: String, deviceID: String,404 at date: Date = .now) async throws -> SyncRecord {405 try await context.transaction { connection in406 try Self.upsert(connection, entity: entity, entityID: entityID, version: try Self.nextVersion(connection),407 deviceID: deviceID, modifiedAt: date, deletedAt: date, payloadHash: nil)408 }409 }410411 /// Stores a record received from another device when it is newer than the local one (higher version; on a412 /// tie the later `modifiedAt`, then the greater device id, so every device picks the same winner). Returns413 /// whether it was applied. The local counter moves past the remote version either way.414 @discardableResult415 public func applyRemote(_ record: SyncRecord) async throws -> Bool {416 try await context.transaction { connection in417 _ = try Self.nextVersion(connection, atLeast: record.version)418 if let row = try connection.queryOne("SELECT * FROM sync_records WHERE entity = ? AND entity_id = ?",419 [record.entity.rawValue, record.entityID]) {420 let local = try SyncRecord(row: row)421 let localKey = (local.version, local.modifiedAt.timeIntervalSince1970, local.deviceID)422 let remoteKey = (record.version, record.modifiedAt.timeIntervalSince1970, record.deviceID)423 guard remoteKey > localKey else { return false }424 }425 _ = try Self.upsert(connection, entity: record.entity, entityID: record.entityID, version: record.version,426 deviceID: record.deviceID, modifiedAt: record.modifiedAt, deletedAt: record.deletedAt,427 payloadHash: record.payloadHash)428 return true429 }430 }431432 public func record(entity: SyncRecord.Entity, entityID: String) async throws -> SyncRecord? {433 try await context.read { connection in434 try connection.queryOne("SELECT * FROM sync_records WHERE entity = ? AND entity_id = ?",435 [entity.rawValue, entityID]).map(SyncRecord.init(row:))436 }437 }438439 /// Records with a version greater than `version`, oldest change first (tombstones included).440 public func changes(since version: Int64, limit: Int = 1_000) async throws -> [SyncRecord] {441 try await context.read { connection in442 try connection.query("SELECT * FROM sync_records WHERE version > ? ORDER BY version, id LIMIT ?",443 [version, limit]).map(SyncRecord.init(row:))444 }445 }446447 public func tombstones() async throws -> [SyncRecord] {448 try await context.read { connection in449 try connection.query("SELECT * FROM sync_records WHERE deleted_at IS NOT NULL ORDER BY version, id")450 .map(SyncRecord.init(row:))451 }452 }453454 /// The highest version handed out so far (0 on a new database).455 public func localVersion() async throws -> Int64 {456 try await context.read { connection in457 try connection.scalar("SELECT value FROM app_state WHERE key = ?", [Self.versionKey], as: String.self)458 .flatMap(Int64.init) ?? 0459 }460 }461462 /// Drops tombstones deleted before `cutoff`, once every device has had time to see them.463 @discardableResult464 public func purgeTombstones(olderThan cutoff: Date) async throws -> Int {465 try await context.transaction {466 try $0.execute("DELETE FROM sync_records WHERE deleted_at IS NOT NULL AND deleted_at < ?", [cutoff])467 }468 }469}470471// MARK: - Settings472473/// A typed setting: its storage key, value type and default.474public struct SettingKey<Value: Codable & Sendable>: Sendable {475 public let name: String476 public let defaultValue: Value477478 public init(_ name: String, default defaultValue: Value) {479 self.name = name; self.defaultValue = defaultValue480 }481}482483/// Typed key-value settings, stored as JSON text. Not for secrets: API keys go to `SecretStore`.484public struct SettingsStore: Sendable {485 let context: StoreContext486487 /// The stored value, or the key's default when nothing is stored or the stored JSON no longer decodes as488 /// `Value` (a type that changed between versions falls back to its default instead of failing the read).489 public func value<Value>(_ key: SettingKey<Value>) async throws -> Value {490 let text = try await context.read {491 try $0.scalar("SELECT value FROM settings WHERE key = ?", [key.name], as: String.self)492 }493 guard let text, let value = try? JSONColumn.decode(Value.self, from: text) else { return key.defaultValue }494 return value495 }496497 public func set<Value>(_ key: SettingKey<Value>, to value: Value, at date: Date = .now) async throws {498 let text = try JSONColumn.encode(value)499 try await context.transaction { connection in500 try connection.execute("""501 INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?)502 ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at503 """, [key.name, text, date])504 }505 }506507 /// Whether a value is stored (as opposed to the default being returned).508 public func isSet(_ name: String) async throws -> Bool {509 try await context.read { try $0.scalar("SELECT 1 FROM settings WHERE key = ?", [name], as: Int.self) != nil }510 }511512 /// Removes the stored value: the key reads as its default again.513 public func remove(_ name: String) async throws {514 try await context.transaction { _ = try $0.execute("DELETE FROM settings WHERE key = ?", [name]) }515 }516517 /// Every stored setting as raw JSON text, keyed by name (export, diagnostics, sync).518 public func allRaw() async throws -> [String: String] {519 try await context.read { connection in520 var result: [String: String] = [:]521 for row in try connection.query("SELECT key, value FROM settings") {522 result[try row.get("key")] = try row.get("value", as: String.self)523 }524 return result525 }526 }527}528