xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / XKit / Utilities / KeyValueStorage.swift
KeyValueStorage.swift181 lines · 5.3 KiBRaw
| 1 | // |
| 2 | // KeyValueStorage.swift |
| 3 | // XKit |
| 4 | // |
| 5 | // Created by Kabir Oberai on 08/04/20. |
| 6 | // Copyright © 2020 Kabir Oberai. All rights reserved. |
| 7 | // |
| 8 | |
| 9 | import Foundation |
| 10 | import ConcurrencyExtras |
| 11 | import Dependencies |
| 12 | |
| 13 | public enum KeyValueStorageError: Error { |
| 14 | case stringConversionFailure |
| 15 | } |
| 16 | |
| 17 | public protocol KeyValueStorage: Sendable { |
| 18 | func data(forKey key: String) throws -> Data? |
| 19 | func setData(_ data: Data?, forKey key: String) throws |
| 20 | // default implementations provided |
| 21 | func string(forKey key: String) throws -> String? |
| 22 | func setString(_ string: String?, forKey key: String) throws |
| 23 | } |
| 24 | |
| 25 | private enum KeyValueStorageDependencyKey: DependencyKey { |
| 26 | static let testValue: KeyValueStorage = UnimplementedKeyValueStorage() |
| 27 | static let liveValue: KeyValueStorage = DirectoryStorage() |
| 28 | } |
| 29 | |
| 30 | extension DependencyValues { |
| 31 | public var keyValueStorage: KeyValueStorage { |
| 32 | get { self[KeyValueStorageDependencyKey.self] } |
| 33 | set { self[KeyValueStorageDependencyKey.self] = newValue } |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | extension KeyValueStorage { |
| 38 | public func string(forKey key: String) throws -> String? { |
| 39 | try data(forKey: key).map { |
| 40 | try String(data: $0, encoding: .utf8).orThrow(KeyValueStorageError.stringConversionFailure) |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | public func setString(_ string: String?, forKey key: String) throws { |
| 45 | let data = try string.map { try $0.data(using: .utf8).orThrow(KeyValueStorageError.stringConversionFailure) } |
| 46 | try setData(data, forKey: key) |
| 47 | } |
| 48 | |
| 49 | public subscript(dataForKey key: String) -> Data? { |
| 50 | get { try? data(forKey: key) } |
| 51 | nonmutating set { try? setData(newValue, forKey: key) } |
| 52 | } |
| 53 | |
| 54 | public subscript(stringForKey key: String) -> String? { |
| 55 | get { try? string(forKey: key) } |
| 56 | nonmutating set { try? setString(newValue, forKey: key) } |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | public struct UnimplementedKeyValueStorage: KeyValueStorage { |
| 61 | public func data(forKey key: String) throws -> Data? { |
| 62 | unimplemented(placeholder: nil) |
| 63 | } |
| 64 | |
| 65 | public func setData(_ data: Data?, forKey key: String) throws { |
| 66 | unimplemented() |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | public struct MemoryKeyValueStorage: KeyValueStorage { |
| 71 | |
| 72 | private let dict = LockIsolated<[String: Data]>([:]) |
| 73 | public init() {} |
| 74 | |
| 75 | public func data(forKey key: String) throws -> Data? { |
| 76 | dict[key] |
| 77 | } |
| 78 | |
| 79 | public func setData(_ data: Data?, forKey key: String) throws { |
| 80 | dict.withValue { $0[key] = data } |
| 81 | } |
| 82 | |
| 83 | } |
| 84 | |
| 85 | public struct DirectoryStorage: KeyValueStorage { |
| 86 | @Dependency(\.persistentDirectory) var directory |
| 87 | |
| 88 | private var base: URL { directory.appendingPathComponent("data") } |
| 89 | |
| 90 | public init() {} |
| 91 | |
| 92 | private func url(for key: String) -> URL { |
| 93 | base.appendingPathComponent(key) |
| 94 | } |
| 95 | |
| 96 | public func data(forKey key: String) throws -> Data? { |
| 97 | try? Data(contentsOf: url(for: key)) |
| 98 | } |
| 99 | |
| 100 | public func setData(_ data: Data?, forKey key: String) throws { |
| 101 | let url = url(for: key) |
| 102 | if !FileManager.default.fileExists(atPath: url.deletingLastPathComponent().path) { |
| 103 | try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) |
| 104 | } |
| 105 | if let data = data { |
| 106 | try data.write(to: url) |
| 107 | } else { |
| 108 | try FileManager.default.removeItem(at: url) |
| 109 | } |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | #if canImport(Security) |
| 114 | import Security |
| 115 | |
| 116 | public struct KeychainStorage: KeyValueStorage { |
| 117 | |
| 118 | public let service: String? |
| 119 | public init(service: String? = nil) { |
| 120 | self.service = service |
| 121 | } |
| 122 | |
| 123 | private let lock = NSLock() |
| 124 | |
| 125 | private static func check(_ result: OSStatus, ignoreNotFound: Bool = false) throws { |
| 126 | if result != errSecSuccess { |
| 127 | if ignoreNotFound && result == errSecItemNotFound { return } |
| 128 | let info: [String: Any]? |
| 129 | if let message = SecCopyErrorMessageString(result, nil) { |
| 130 | info = [NSLocalizedDescriptionKey: message as String] |
| 131 | } else { |
| 132 | info = nil |
| 133 | } |
| 134 | throw NSError(domain: NSOSStatusErrorDomain, code: .init(result), userInfo: info) |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | private func makeQuery(forKey key: String, _ parameters: [CFString: Any]) -> CFDictionary { |
| 139 | var query: [CFString: Any] = [ |
| 140 | kSecClass: kSecClassGenericPassword, |
| 141 | kSecAttrAccount: key, |
| 142 | kSecUseDataProtectionKeychain: true, |
| 143 | ] |
| 144 | query[kSecAttrService] = service |
| 145 | query.merge(parameters) { _, b in b } |
| 146 | return query as CFDictionary |
| 147 | } |
| 148 | |
| 149 | public func data(forKey key: String) throws -> Data? { |
| 150 | lock.lock() |
| 151 | defer { lock.unlock() } |
| 152 | |
| 153 | let query = makeQuery(forKey: key, [ |
| 154 | kSecReturnData: true |
| 155 | ]) |
| 156 | |
| 157 | var result: AnyObject? |
| 158 | try Self.check(SecItemCopyMatching(query, &result), ignoreNotFound: true) |
| 159 | |
| 160 | return result as? Data |
| 161 | } |
| 162 | |
| 163 | public func setData(_ data: Data?, forKey key: String) throws { |
| 164 | lock.lock() |
| 165 | defer { lock.unlock() } |
| 166 | |
| 167 | // remove old before setting new value |
| 168 | try Self.check(SecItemDelete(makeQuery(forKey: key, [:])), ignoreNotFound: true) |
| 169 | |
| 170 | guard let data = data else { return } |
| 171 | |
| 172 | let query = makeQuery(forKey: key, [ |
| 173 | kSecValueData: data, |
| 174 | kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlock |
| 175 | ]) |
| 176 | |
| 177 | try Self.check(SecItemAdd(query, nil)) |
| 178 | } |
| 179 | |
| 180 | } |
| 181 | #endif |