// Copyright © 2022 Rangeproof Pty Ltd. All rights reserved. import Foundation import GRDB import PromiseKit import SignalCoreKit public enum GRDBStorageError: Error { // TODO: Rename to `StorageError` case generic case migrationFailed case invalidKeySpec case decodingFailed case failedToSave case objectNotFound case objectNotSaved } // TODO: Protocol for storage (just need to have 'read' and 'write' methods and mock 'Database'? // TODO: Rename to `Storage` public final class GRDBStorage { public static var shared: GRDBStorage! // TODO: Figure out how/if we want to do this private static let dbFileName: String = "Session.sqlite" private static let keychainService: String = "TSKeyChainService" private static let dbCipherKeySpecKey: String = "GRDBDatabaseCipherKeySpec" private static let kSQLCipherKeySpecLength: Int32 = 48 private static var sharedDatabaseDirectoryPath: String { "\(OWSFileSystem.appSharedDataDirectoryPath())/database" } private static var databasePath: String { "\(GRDBStorage.sharedDatabaseDirectoryPath)/\(GRDBStorage.dbFileName)" } private static var databasePathShm: String { "\(GRDBStorage.sharedDatabaseDirectoryPath)/\(GRDBStorage.dbFileName)-shm" } private static var databasePathWal: String { "\(GRDBStorage.sharedDatabaseDirectoryPath)/\(GRDBStorage.dbFileName)-wal" } public static var isDatabasePasswordAccessible: Bool { guard (try? getDatabaseCipherKeySpec()) != nil else { return false } return true } private let dbPool: DatabasePool private let migrator: DatabaseMigrator // MARK: - Initialization public init?( migrations: [TargetMigrations] ) throws { print("RAWR START \("\(GRDBStorage.sharedDatabaseDirectoryPath)/\(GRDBStorage.dbFileName)")") GRDBStorage.deleteDatabaseFiles() // TODO: Remove this try! GRDBStorage.deleteDbKeys() // TODO: Remove this // Create the database directory if needed and ensure it's protection level is set before attempting to // create the database KeySpec or the database itself OWSFileSystem.ensureDirectoryExists(GRDBStorage.sharedDatabaseDirectoryPath) OWSFileSystem.protectFileOrFolder(atPath: GRDBStorage.sharedDatabaseDirectoryPath) // Generate the database KeySpec if needed (this MUST be done before we try to access the database // as a different thread might attempt to access the database before the key is successfully created) // // Note: We reset the bytes immediately after generation to ensure the database key doesn't hang // around in memory unintentionally var tmpKeySpec: Data = GRDBStorage.getOrGenerateDatabaseKeySpec() tmpKeySpec.resetBytes(in: 0.. Data { return try CurrentAppContext().keychainStorage().data(forService: keychainService, key: dbCipherKeySpecKey) } @discardableResult private static func getOrGenerateDatabaseKeySpec() -> Data { do { var keySpec: Data = try getDatabaseCipherKeySpec() defer { keySpec.resetBytes(in: 0..(updates: (Database) throws -> T?) -> T? { return try? dbPool.write(updates) } public func writeAsync(updates: @escaping (Database) throws -> T) { writeAsync(updates: updates, completion: { _, _ in }) } public func writeAsync(updates: @escaping (Database) throws -> T, completion: @escaping (Database, Swift.Result) throws -> Void) { dbPool.asyncWrite( updates, completion: { db, result in try? completion(db, result) } ) } @discardableResult public func read(_ value: (Database) throws -> T?) -> T? { return try? dbPool.read(value) } /// Rever to the `ValueObservation.start` method for full documentation /// /// - parameter observation: The observation to start /// - parameter scheduler: A Scheduler. By default, fresh values are /// dispatched asynchronously on the main queue. /// - parameter onError: A closure that is provided eventual errors that /// happen during observation /// - parameter onChange: A closure that is provided fresh values /// - returns: a DatabaseCancellable public func start( _ observation: ValueObservation, scheduling scheduler: ValueObservationScheduler = .async(onQueue: .main), onError: @escaping (Error) -> Void, onChange: @escaping (Reducer.Value) -> Void ) -> DatabaseCancellable { observation.start( in: dbPool, scheduling: scheduler, onError: onError, onChange: onChange ) } } // MARK: - Promise Extensions public extension GRDBStorage { // FIXME: Would be good to replace these with Swift Combine @discardableResult func read(_ value: (Database) throws -> Promise) -> Promise { do { return try dbPool.read(value) } catch { return Promise(error: error) } } @discardableResult func write(updates: (Database) throws -> Promise) -> Promise { do { return try dbPool.write(updates) } catch { return Promise(error: error) } } }