1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
import protocol TSCBasic.Closable
import var TSCBasic.localFileSystem
/// SQLite backed persistent cache.
package final class SQLiteBackedCache<Value: Codable>: Closable {
package typealias Key = String
package let tableName: String
package let fileSystem: FileSystem
package let location: SQLite.Location
package let configuration: SQLiteBackedCacheConfiguration
private var state = State.idle
private let stateLock = NSLock()
private let jsonEncoder: JSONEncoder
private let jsonDecoder: JSONDecoder
/// Creates a SQLite-backed cache.
///
/// - Parameters:
/// - tableName: The SQLite table name. Must follow SQLite naming rules (e.g., no spaces).
/// - location: SQLite.Location
/// - configuration: Optional. Configuration for the cache.
package init(tableName: String, location: SQLite.Location, configuration: SQLiteBackedCacheConfiguration = .init()) {
self.tableName = tableName
self.location = location
switch self.location {
case .path, .temporary:
self.fileSystem = localFileSystem
case .memory:
self.fileSystem = InMemoryFileSystem()
}
self.configuration = configuration
self.jsonEncoder = JSONEncoder.makeWithDefaults()
self.jsonDecoder = JSONDecoder.makeWithDefaults()
}
/// Creates a SQLite-backed cache.
///
/// - Parameters:
/// - tableName: The SQLite table name. Must follow SQLite naming rules (e.g., no spaces).
/// - path: The path of the SQLite database.
/// - configuration: Optional. Configuration for the cache.
package convenience init(
tableName: String,
path: AbsolutePath,
configuration: SQLiteBackedCacheConfiguration = .init()
) {
self.init(tableName: tableName, location: .path(path), configuration: configuration)
}
deinit {
try? self.withStateLock {
if case .connected(let db) = self.state {
// TODO: we could wrap the failure here with diagnostics if it was available
assertionFailure("db should be closed")
try db.close()
}
}
}
package func close() throws {
try self.withStateLock {
if case .connected(let db) = self.state {
try db.close()
}
self.state = .disconnected
}
}
private func put(
rawKey key: SQLite.SQLiteValue,
value: Value,
replace: Bool = false,
observabilityScope: ObservabilityScope? = nil
) throws {
do {
let query = "INSERT OR \(replace ? "REPLACE" : "IGNORE") INTO \(self.tableName) VALUES (?, ?);"
try self.executeStatement(query) { statement in
let data = try self.jsonEncoder.encode(value)
let bindings: [SQLite.SQLiteValue] = [
key,
.blob(data),
]
try statement.bind(bindings)
try statement.step()
}
} catch (let error as SQLite.Errors) where error == .databaseFull {
if !self.configuration.truncateWhenFull {
throw error
}
observabilityScope?
.emit(
warning: """
truncating \(self.tableName) cache database since it reached max size of \(
self.configuration.maxSizeInBytes ?? 0
) bytes
"""
)
try self.executeStatement("DELETE FROM \(self.tableName);") { statement in
try statement.step()
}
try self.put(rawKey: key, value: value, replace: replace, observabilityScope: observabilityScope)
} catch {
throw error
}
}
package func put(
blobKey key: some Sequence<UInt8>,
value: Value,
replace: Bool = false,
observabilityScope: ObservabilityScope? = nil
) throws {
try self.put(rawKey: .blob(Data(key)), value: value, observabilityScope: observabilityScope)
}
package func put(
key: Key,
value: Value,
replace: Bool = false,
observabilityScope: ObservabilityScope? = nil
) throws {
try self.put(rawKey: .string(key), value: value, replace: replace, observabilityScope: observabilityScope)
}
package func get(key: Key) throws -> Value? {
let query = "SELECT value FROM \(self.tableName) WHERE key = ? LIMIT 1;"
return try self.executeStatement(query) { statement -> Value? in
try statement.bind([.string(key)])
let data = try statement.step()?.blob(at: 0)
return try data.flatMap {
try self.jsonDecoder.decode(Value.self, from: $0)
}
}
}
package func get(blobKey key: some Sequence<UInt8>) throws -> Value? {
let query = "SELECT value FROM \(self.tableName) WHERE key = ? LIMIT 1;"
return try self.executeStatement(query) { statement -> Value? in
try statement.bind([.blob(Data(key))])
let data = try statement.step()?.blob(at: 0)
return try data.flatMap {
try self.jsonDecoder.decode(Value.self, from: $0)
}
}
}
package func remove(key: Key) throws {
let query = "DELETE FROM \(self.tableName) WHERE key = ?;"
try self.executeStatement(query) { statement in
try statement.bind([.string(key)])
try statement.step()
}
}
@discardableResult
private func executeStatement<T>(_ query: String, _ body: (SQLite.PreparedStatement) throws -> T) throws -> T {
try self.withDB { db in
let result: Result<T, Error>
let statement = try db.prepare(query: query)
do {
result = try .success(body(statement))
} catch {
result = .failure(error)
}
try statement.finalize()
switch result {
case .failure(let error):
throw error
case .success(let value):
return value
}
}
}
private func withDB<T>(_ body: (SQLite) throws -> T) throws -> T {
let createDB = { () throws -> SQLite in
let db = try SQLite(location: self.location, configuration: self.configuration.underlying)
try self.createSchemaIfNecessary(db: db)
return db
}
return try self.withStateLock { () -> T in
let db: SQLite
switch (self.location, self.state) {
case (.path(let path), .connected(let database)):
if self.fileSystem.exists(path) {
db = database
} else {
try database.close()
try self.fileSystem.createDirectory(path.parentDirectory, recursive: true)
db = try createDB()
}
case (.path(let path), _):
if !self.fileSystem.exists(path) {
try self.fileSystem.createDirectory(path.parentDirectory, recursive: true)
}
db = try createDB()
case (_, .connected(let database)):
db = database
case (_, _):
db = try createDB()
}
self.state = .connected(db)
return try body(db)
}
}
private func createSchemaIfNecessary(db: SQLite) throws {
let table = """
CREATE TABLE IF NOT EXISTS \(self.tableName) (
key STRING PRIMARY KEY NOT NULL,
value BLOB NOT NULL
);
"""
try db.exec(query: table)
try db.exec(query: "PRAGMA journal_mode=WAL;")
}
private func withStateLock<T>(_ body: () throws -> T) throws -> T {
switch self.location {
case .path(let path):
if !self.fileSystem.exists(path.parentDirectory) {
try self.fileSystem.createDirectory(path.parentDirectory, recursive: true)
}
return try self.fileSystem.withLock(on: path, type: .exclusive, body)
case .memory, .temporary:
return try self.stateLock.withLock(body)
}
}
private enum State {
case idle
case connected(SQLite)
case disconnected
}
}
package struct SQLiteBackedCacheConfiguration {
package var truncateWhenFull: Bool
fileprivate var underlying: SQLite.Configuration
package init() {
self.underlying = .init()
self.truncateWhenFull = true
self.maxSizeInMegabytes = 100
// see https://www.sqlite.org/c3ref/busy_timeout.html
self.busyTimeoutMilliseconds = 1000
}
package var maxSizeInMegabytes: Int? {
get {
self.underlying.maxSizeInMegabytes
}
set {
self.underlying.maxSizeInMegabytes = newValue
}
}
package var maxSizeInBytes: Int? {
get {
self.underlying.maxSizeInBytes
}
set {
self.underlying.maxSizeInBytes = newValue
}
}
package var busyTimeoutMilliseconds: Int32 {
get {
self.underlying.busyTimeoutMilliseconds
}
set {
self.underlying.busyTimeoutMilliseconds = newValue
}
}
}
|