Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / apple / Shared / EnvelopeIPC.swift

EnvelopeIPC.swift391 lines · 17.5 KiBRaw
1// EverySync Apple shells — shared envelope IPC store.
2//
3// Zero sync logic in Swift. This file implements ONLY the three IPC ops from
4// `apple/IPC_CONTRACT.md` over the App-Group shared container, with identical
5// table / op / column semantics to the KMP `SyncSink` interface
6// (`querySince` / `upsertRaw` / `deleteByVault`; columns
7// `syncId / updatedAt / deleted / payloadJson / contentHash`).
8//
9// The hub is the only process that talks to the relay. Shells only touch this
10// store; the XCFramework (merge / transport / crypto) reads the same SQLite
11// files on the Kotlin side (see ../XCFramework/IOS_ACTUALS_NOTES.md).
12//
13// Loss-prevention rules honored here:
14// - A failed local read THROWS (never returns empty). Callers must abort the
15// cycle, exactly like `SyncSink.listLocalOk == false`.
16// - Only explicit tombstones delete (soft-delete tables). Absence without a
17// tombstone resurrects — never deletes.
18// - Passwords hard-delete; notes/todos soft-delete.
19//
20// MAC-CHECK (needs xcodebuild on a Mac):
21// - `import SQLite3` resolves against libsqlite3.tbd (system library).
22// - App-Group identifier below must use the real team prefix.
23
24import Foundation
25import SQLite3
26
27/// App-Group shared container identifier. The `<team>` placeholder from
28/// `IPC_CONTRACT.md` must be replaced with the real team prefix on the Mac
29/// (Xcode signing will fail otherwise). Single constant so all targets agree.
30public enum EverysyncGroup {
31 public static let identifier = "group.com.vayunmathur.everysync.shared"
32}
33
34/// One envelope row. Column semantics are identical to the KMP `SyncSink`
35/// columns (`EntityKind.syncId` -> `RemoteX.uid`, `RemoteX.updatedAt`,
36/// `RemoteX.deleted`, `PasswordKind`/`NoteKind`/`TodoKind.toJson`,
37/// `EntityKind.contentHash`).
38public struct EnvelopeRow: Equatable {
39 /// Relay sync identity (opaque 32-char id).
40 public let syncId: String
41 /// Last modification, epoch ms; drives relay LWW.
42 public let updatedAt: Int64
43 /// Tombstone flag. Included in `querySince` results for soft-delete types.
44 public let deleted: Bool
45 /// Full `RemoteX` JSON envelope. Swift treats this as OPAQUE bytes:
46 /// produced/consumed only via the XCFramework (`*Kind.toJson/fromJson`).
47 /// Swift never parses, merges, hashes, or encrypts it.
48 public let payloadJson: String
49 /// `relayContentHash(canonical + "\0deleted=…")`, computed in the
50 /// XCFramework (`EntityKind.contentHash`). Swift never computes this.
51 public let contentHash: String
52
53 public init(syncId: String, updatedAt: Int64, deleted: Bool, payloadJson: String, contentHash: String) {
54 self.syncId = syncId
55 self.updatedAt = updatedAt
56 self.deleted = deleted
57 self.payloadJson = payloadJson
58 self.contentHash = contentHash
59 }
60}
61
62/// IPC tables. Names map 1:1 to relay channels (see IPC_CONTRACT.md).
63public enum EnvelopeTable: String, CaseIterable {
64 case passwords // `passwords:<vaultId>` — HARD delete
65 case notes // `notes:<vaultId>` — SOFT delete (tombstones persist)
66 case todos // `todos:<vaultId>` — SOFT delete (tombstones persist)
67 case contacts // hub-internal; same columns
68 case calendars // hub-internal; same columns
69
70 var isHardDelete: Bool { self == .passwords }
71}
72
73public enum EnvelopeIPCError: Error {
74 case containerUnavailable
75 case sqlite(String)
76 case unhealthyRead(String)
77}
78
79/// Thread-safe, `NSFileCoordinator`-guarded SQLite envelope store.
80///
81/// - Location: `<group>/vault/<vaultId>/envelopes.sqlite` (one file per vault)
82/// plus a `blobs/` sidecar dir (see `BlobStore.swift`).
83/// - Mode: WAL + `busy_timeout=5000` so the Kotlin `RelayStore` shims (core
84/// owner, same schema — see `../XCFramework/IOS_ACTUALS_NOTES.md`) can hold
85/// the same files open concurrently. All Swift access goes through
86/// `NSFileCoordinator`; the Kotlin side relies on SQLite locking + WAL.
87/// - Schema version: v1 (see `../IPC_CONTRACT.md` appendix). Any column/table
88/// change must update the contract doc AND the Kotlin shim spec together.
89public final class EnvelopeIPC {
90 private let fileManager = FileManager.default
91 private let coordinator = NSFileCoordinator()
92 private let queue = DispatchQueue(label: "com.vayunmathur.everysync.envelope-ipc")
93
94 public init() {}
95
96 // MARK: - Ops (map 1:1 to KMP `SyncSink`)
97
98 /// `querySince` — rows with `updatedAt > since`, tombstones included.
99 /// Drives both baseline reads and delta detection. THROWS on any unhealthy
100 /// read; callers must abort (never fold failure as empty).
101 public func querySince(vaultId: String, table: EnvelopeTable, since: Int64) throws -> [EnvelopeRow] {
102 try queue.sync {
103 let url = try databaseURL(vaultId: vaultId)
104 var rows: [EnvelopeRow] = []
105 var caught: Error?
106 try coordinateReading(url: url) {
107 do {
108 rows = try self.withDatabase(at: url) { db in
109 try self.query(db: db, table: table, since: since)
110 }
111 } catch {
112 caught = error
113 }
114 }
115 if let caught { throw caught }
116 return rows
117 }
118 }
119
120 /// `upsertRaw` — idempotent upsert keyed on `syncId`; preserves pulled
121 /// timestamps (no timestamp rewriting here — `updatedAt` is stored verbatim).
122 public func upsertRaw(vaultId: String, table: EnvelopeTable, rows: [EnvelopeRow]) throws {
123 guard !rows.isEmpty else { return }
124 try queue.sync {
125 let url = try databaseURL(vaultId: vaultId)
126 var caught: Error?
127 try coordinateWriting(url: url) {
128 do {
129 try self.withDatabase(at: url) { db in
130 try self.upsert(db: db, table: table, rows: rows)
131 }
132 } catch {
133 caught = error
134 }
135 }
136 if let caught { throw caught }
137 }
138 }
139
140 /// `deleteByVault` — applies a pulled relay tombstone:
141 /// - `passwords`: HARD-delete the row (rows vanish; only the app-side
142 /// snapshot remembers them).
143 /// - `notes`/`todos`/`contacts`/`calendars`: set `deleted=1` tombstone.
144 /// The tombstone envelope itself always arrives via `upsertRaw`; this op
145 /// is for shell-side deletes, which the hub folds into tombstones.
146 /// Merge-driven deletes ALWAYS arrive as tombstone envelopes, never raw.
147 ///
148 /// - Parameter now: caller timestamp (epoch ms) stamped onto the tombstone
149 /// row so delta queries (`updatedAt > cursor`) observe the delete. The
150 /// merge overwrites it with the agreed stamp; the value here only needs
151 /// to be newer than the last cursor.
152 public func deleteByVault(vaultId: String, table: EnvelopeTable, syncId: String, now: Int64) throws {
153 try queue.sync {
154 let url = try databaseURL(vaultId: vaultId)
155 var caught: Error?
156 try coordinateWriting(url: url) {
157 do {
158 try self.withDatabase(at: url) { db in
159 if table.isHardDelete {
160 try self.exec(db: db, sql: "DELETE FROM \(table.sql) WHERE syncId = ?;", bind: [syncId])
161 } else {
162 // Tombstone the row; keep payloadJson + contentHash untouched —
163 // the hub replaces them with the tombstone envelope on merge.
164 // Stamp `now` so delta queries (updatedAt > cursor) observe
165 // the delete; the merge overwrites it with the agreed stamp.
166 try self.execTombstone(db: db, table: table, syncId: syncId, now: now)
167 }
168 }
169 } catch {
170 caught = error
171 }
172 }
173 if let caught { throw caught }
174 }
175 }
176
177 /// Removes every row for this vault (purge keeps the vault itself).
178 /// Used for account removal / re-provision; the next healthy pull
179 /// re-enables repopulation (same as the relay conformance checklist).
180 public func purgeVault(vaultId: String) throws {
181 try queue.sync {
182 let url = try databaseURL(vaultId: vaultId)
183 var caught: Error?
184 try coordinateWriting(url: url) {
185 do {
186 try self.withDatabase(at: url) { db in
187 for table in EnvelopeTable.allCases {
188 try self.exec(db: db, sql: "DELETE FROM \(table.sql);", bind: [])
189 }
190 }
191 } catch {
192 caught = error
193 }
194 }
195 if let caught { throw caught }
196 }
197 }
198
199 // MARK: - Paths
200
201 func containerURL() throws -> URL {
202 guard let url = fileManager.containerURL(forSecurityApplicationGroupIdentifier: EverysyncGroup.identifier) else {
203 throw EnvelopeIPCError.containerUnavailable
204 }
205 return url
206 }
207
208 func vaultDirectory(vaultId: String) throws -> URL {
209 precondition(!vaultId.isEmpty && !vaultId.contains("/"), "vaultId must be a bare id")
210 return try containerURL().appendingPathComponent("vault/\(vaultId)", isDirectory: true)
211 }
212
213 func databaseURL(vaultId: String) throws -> URL {
214 let dir = try vaultDirectory(vaultId: vaultId)
215 try fileManager.createDirectory(at: dir, withIntermediateDirectories: true)
216 try fileManager.createDirectory(at: dir.appendingPathComponent("blobs", isDirectory: true), withIntermediateDirectories: true)
217 return dir.appendingPathComponent("envelopes.sqlite")
218 }
219
220 // MARK: - SQLite
221
222 private func withDatabase<T>(at url: URL, _ body: (OpaquePointer) throws -> T) throws -> T {
223 var db: OpaquePointer?
224 let flags = SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE | SQLITE_OPEN_FULLMUTEX
225 guard sqlite3_open_v2(url.path, &db, flags, nil) == SQLITE_OK, let db else {
226 throw EnvelopeIPCError.sqlite("open failed: \(url.path)")
227 }
228 defer { sqlite3_close(db) }
229 // NOTE: `PRAGMA journal_mode=WAL` returns a result row (SQLITE_ROW),
230 // so it needs a query-style step — plain exec() would throw.
231 try queryPragma(db: db, sql: "PRAGMA journal_mode=WAL;")
232 try exec(db: db, sql: "PRAGMA busy_timeout=5000;", bind: [])
233 for table in EnvelopeTable.allCases {
234 try exec(db: db, sql: """
235 CREATE TABLE IF NOT EXISTS \(table.sql) (
236 syncId TEXT PRIMARY KEY,
237 updatedAt INTEGER NOT NULL,
238 deleted INTEGER NOT NULL DEFAULT 0,
239 payloadJson TEXT NOT NULL,
240 contentHash TEXT NOT NULL
241 );
242 """, bind: [])
243 try exec(db: db, sql: "CREATE INDEX IF NOT EXISTS idx_\(table.sql)_updatedAt ON \(table.sql)(updatedAt);", bind: [])
244 }
245 return try body(db)
246 }
247
248 private func query(db: OpaquePointer, table: EnvelopeTable, since: Int64) throws -> [EnvelopeRow] {
249 let sql = "SELECT syncId, updatedAt, deleted, payloadJson, contentHash FROM \(table.sql) WHERE updatedAt > ? ORDER BY updatedAt;"
250 var stmt: OpaquePointer?
251 guard sqlite3_prepare_v2(db, sql, -1, &stmt, nil) == SQLITE_OK, let stmt else {
252 throw EnvelopeIPCError.sqlite(String(cString: sqlite3_errmsg(db)))
253 }
254 defer { sqlite3_finalize(stmt) }
255 sqlite3_bind_int64(stmt, 1, since)
256 var rows: [EnvelopeRow] = []
257 while true {
258 let step = sqlite3_step(stmt)
259 if step == SQLITE_ROW {
260 guard let syncIdC = sqlite3_column_text(stmt, 0),
261 let payloadC = sqlite3_column_text(stmt, 3),
262 let hashC = sqlite3_column_text(stmt, 4) else {
263 throw EnvelopeIPCError.unhealthyRead("null column in \(table.rawValue)")
264 }
265 rows.append(EnvelopeRow(
266 syncId: String(cString: syncIdC),
267 updatedAt: sqlite3_column_int64(stmt, 1),
268 deleted: sqlite3_column_int(stmt, 2) != 0,
269 payloadJson: String(cString: payloadC),
270 contentHash: String(cString: hashC)
271 ))
272 } else if step == SQLITE_DONE {
273 break
274 } else {
275 throw EnvelopeIPCError.unhealthyRead(String(cString: sqlite3_errmsg(db)))
276 }
277 }
278 return rows
279 }
280
281 /// Idempotent upsert keyed on `syncId`; preserves pulled timestamps
282 /// (stores `updatedAt` verbatim — no rewriting). Batched in one
283 /// transaction.
284 private func upsert(db: OpaquePointer, table: EnvelopeTable, rows: [EnvelopeRow]) throws {
285 try exec(db: db, sql: "BEGIN IMMEDIATE;", bind: [])
286 do {
287 for row in rows {
288 try upsertOne(db: db, table: table, row: row)
289 }
290 try exec(db: db, sql: "COMMIT;", bind: [])
291 } catch {
292 try? exec(db: db, sql: "ROLLBACK;", bind: [])
293 throw error
294 }
295 }
296
297 /// Single-row upsert. Factored out (not inlined in the loop) so the
298 /// statement `defer`-finalize runs per row — `defer` inside a `for` body
299 /// would pile up until function return and leak statements.
300 private func upsertOne(db: OpaquePointer, table: EnvelopeTable, row: EnvelopeRow) throws {
301 var stmt: OpaquePointer?
302 let sql = "INSERT INTO \(table.sql)(syncId, updatedAt, deleted, payloadJson, contentHash) VALUES (?, ?, ?, ?, ?) ON CONFLICT(syncId) DO UPDATE SET updatedAt = excluded.updatedAt, deleted = excluded.deleted, payloadJson = excluded.payloadJson, contentHash = excluded.contentHash;"
303 guard sqlite3_prepare_v2(db, sql, -1, &stmt, nil) == SQLITE_OK, let stmt else {
304 throw EnvelopeIPCError.sqlite(String(cString: sqlite3_errmsg(db)))
305 }
306 defer { sqlite3_finalize(stmt) }
307 sqlite3_bind_text(stmt, 1, row.syncId, -1, SQLITE_TRANSIENT)
308 sqlite3_bind_int64(stmt, 2, row.updatedAt)
309 sqlite3_bind_int(stmt, 3, row.deleted ? 1 : 0)
310 sqlite3_bind_text(stmt, 4, row.payloadJson, -1, SQLITE_TRANSIENT)
311 sqlite3_bind_text(stmt, 5, row.contentHash, -1, SQLITE_TRANSIENT)
312 guard sqlite3_step(stmt) == SQLITE_DONE else {
313 throw EnvelopeIPCError.sqlite(String(cString: sqlite3_errmsg(db)))
314 }
315 }
316
317 @discardableResult
318 private func exec(db: OpaquePointer, sql: String, bind: [String]) throws -> Int {
319 var stmt: OpaquePointer?
320 guard sqlite3_prepare_v2(db, sql, -1, &stmt, nil) == SQLITE_OK, let stmt else {
321 throw EnvelopeIPCError.sqlite(String(cString: sqlite3_errmsg(db)))
322 }
323 defer { sqlite3_finalize(stmt) }
324 for (i, value) in bind.enumerated() {
325 sqlite3_bind_text(stmt, Int32(i + 1), value, -1, SQLITE_TRANSIENT)
326 }
327 guard sqlite3_step(stmt) == SQLITE_DONE else {
328 throw EnvelopeIPCError.sqlite(String(cString: sqlite3_errmsg(db)))
329 }
330 return Int(sqlite3_changes(db))
331 }
332
333 /// Tombstone update with an int64 timestamp bind (soft-delete tables).
334 private func execTombstone(db: OpaquePointer, table: EnvelopeTable, syncId: String, now: Int64) throws {
335 let sql = "UPDATE \(table.sql) SET deleted = 1, updatedAt = ? WHERE syncId = ?;"
336 var stmt: OpaquePointer?
337 guard sqlite3_prepare_v2(db, sql, -1, &stmt, nil) == SQLITE_OK, let stmt else {
338 throw EnvelopeIPCError.sqlite(String(cString: sqlite3_errmsg(db)))
339 }
340 defer { sqlite3_finalize(stmt) }
341 sqlite3_bind_int64(stmt, 1, now)
342 sqlite3_bind_text(stmt, 2, syncId, -1, SQLITE_TRANSIENT)
343 guard sqlite3_step(stmt) == SQLITE_DONE else {
344 throw EnvelopeIPCError.sqlite(String(cString: sqlite3_errmsg(db)))
345 }
346 }
347
348 /// Steps a row-returning PRAGMA to completion (e.g. `journal_mode`).
349 /// Any step result other than ROW/DONE is an unhealthy read.
350 private func queryPragma(db: OpaquePointer, sql: String) throws {
351 var stmt: OpaquePointer?
352 guard sqlite3_prepare_v2(db, sql, -1, &stmt, nil) == SQLITE_OK, let stmt else {
353 throw EnvelopeIPCError.sqlite(String(cString: sqlite3_errmsg(db)))
354 }
355 defer { sqlite3_finalize(stmt) }
356 while true {
357 switch sqlite3_step(stmt) {
358 case SQLITE_ROW: continue
359 case SQLITE_DONE: return
360 default: throw EnvelopeIPCError.unhealthyRead(String(cString: sqlite3_errmsg(db)))
361 }
362 }
363 }
364
365 // MARK: - Coordination
366
367 private func coordinateReading(url: URL, _ body: () -> Void) throws {
368 var error: NSError?
369 coordinator.coordinate(readingItemAt: url, options: [], error: &error, byAccessor: { _ in body() })
370 // A coordination failure is an unhealthy read — NEVER fold as empty.
371 if let error {
372 throw EnvelopeIPCError.unhealthyRead("NSFileCoordinator read failed: \(error)")
373 }
374 }
375
376 private func coordinateWriting(url: URL, _ body: () -> Void) throws {
377 var error: NSError?
378 coordinator.coordinate(writingItemAt: url, options: [], error: &error, byAccessor: { _ in body() })
379 if let error {
380 throw EnvelopeIPCError.unhealthyRead("NSFileCoordinator write failed: \(error)")
381 }
382 }
383}
384
385private extension EnvelopeTable {
386 /// Allowlisted table names — never interpolate raw strings into SQL.
387 var sql: String { rawValue }
388}
389
390// SQLITE_TRANSIENT helper (macro, not imported from the module map).
391private let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self)