-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSQLiteConnectionPool.swift
More file actions
229 lines (197 loc) · 6.3 KB
/
SQLiteConnectionPool.swift
File metadata and controls
229 lines (197 loc) · 6.3 KB
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
//
// SQLiteConnectionPool.swift
// feather-sqlite-database
//
// Created by Tibor Bödecs on 2026. 01. 26..
//
import Logging
import SQLiteNIO
actor SQLiteConnectionPool {
private struct Waiter {
let id: Int
let continuation: CheckedContinuation<SQLiteConnection, Error>
}
private struct TransactionWaiter {
let id: Int
let continuation: CheckedContinuation<Void, Error>
}
private let configuration: SQLiteClient.Configuration
private var availableConnections: [SQLiteConnection] = []
private var waiters: [Waiter] = []
private var totalConnections = 0
private var nextWaiterID = 0
private var isShutdown = false
private var transactionInUse = false
private var transactionWaiters: [TransactionWaiter] = []
private var nextTransactionWaiterID = 0
init(
configuration: SQLiteClient.Configuration
) {
self.configuration = configuration
}
func warmup() async throws {
guard !isShutdown else { return }
let target = configuration.minimumConnections
guard totalConnections < target else { return }
let newConnections = target - totalConnections
for _ in 0..<newConnections {
let connection = try await makeConnection()
availableConnections.append(connection)
totalConnections += 1
}
}
func leaseConnection() async throws -> SQLiteConnection {
guard !isShutdown else {
throw SQLiteConnectionPoolError.shutdown
}
if let connection = availableConnections.popLast() {
return connection
}
if totalConnections < configuration.maximumConnections {
totalConnections += 1
do {
return try await makeConnection()
}
catch {
totalConnections -= 1
throw error
}
}
let waiterID = nextWaiterID
nextWaiterID += 1
return try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
waiters.append(
Waiter(id: waiterID, continuation: continuation)
)
}
} onCancel: {
Task { await self.cancelWaiter(id: waiterID) }
}
}
func releaseConnection(
_ connection: SQLiteConnection
) async {
if isShutdown {
await closeConnection(connection)
return
}
if waiters.isEmpty {
availableConnections.append(connection)
return
}
let waiter = waiters.removeFirst()
waiter.continuation.resume(returning: connection)
}
func shutdown() async {
guard !isShutdown else { return }
isShutdown = true
let connections = availableConnections
availableConnections.removeAll(keepingCapacity: false)
for connection in connections {
await closeConnection(connection)
}
for waiter in waiters {
waiter.continuation.resume(
throwing: SQLiteConnectionPoolError.shutdown
)
}
waiters.removeAll(keepingCapacity: false)
for waiter in transactionWaiters {
waiter.continuation.resume(
throwing: SQLiteConnectionPoolError.shutdown
)
}
transactionWaiters.removeAll(keepingCapacity: false)
transactionInUse = false
}
func connectionCount() -> Int {
totalConnections
}
func leaseTransactionPermit() async throws {
guard !isShutdown else {
throw SQLiteConnectionPoolError.shutdown
}
if !transactionInUse {
transactionInUse = true
return
}
let waiterID = nextTransactionWaiterID
nextTransactionWaiterID += 1
return try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
transactionWaiters.append(
TransactionWaiter(id: waiterID, continuation: continuation)
)
}
} onCancel: {
Task { await self.cancelTransactionWaiter(id: waiterID) }
}
}
func releaseTransactionPermit() {
if transactionWaiters.isEmpty {
transactionInUse = false
return
}
let waiter = transactionWaiters.removeFirst()
waiter.continuation.resume()
}
private func cancelWaiter(
id: Int
) {
guard let index = waiters.firstIndex(where: { $0.id == id }) else {
return
}
let waiter = waiters.remove(at: index)
waiter.continuation.resume(throwing: CancellationError())
}
private func cancelTransactionWaiter(
id: Int
) {
guard let index = transactionWaiters.firstIndex(where: { $0.id == id })
else {
return
}
let waiter = transactionWaiters.remove(at: index)
waiter.continuation.resume(throwing: CancellationError())
}
private func makeConnection() async throws -> SQLiteConnection {
let connection = try await SQLiteConnection.open(
storage: configuration.storage,
logger: configuration.logger
)
do {
_ = try await connection.query(
"PRAGMA journal_mode = \(configuration.journalMode.rawValue);"
)
_ = try await connection.query(
"PRAGMA busy_timeout = \(configuration.busyTimeoutMilliseconds);"
)
_ = try await connection.query(
"PRAGMA foreign_keys = \(configuration.foreignKeysMode.rawValue);"
)
}
catch {
await closeConnection(connection)
throw error
}
return connection
}
private func closeConnection(
_ connection: SQLiteConnection
) async {
let result =
await Task.detached {
try await connection.close()
}
.result
if case .failure(let error) = result {
configuration.logger.warning(
"Failed to close SQLite connection",
metadata: [
"error": "\(error)"
]
)
}
}
}