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