forked from vapor/postgres-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMockConnection.swift
107 lines (88 loc) · 2.96 KB
/
MockConnection.swift
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
import DequeModule
@testable import _ConnectionPoolModule
// Sendability enforced through the lock
final class MockConnection: PooledConnection, Sendable {
typealias ID = Int
let id: ID
private enum State {
case running([CheckedContinuation<Void, any Error>], [@Sendable ((any Error)?) -> ()])
case closing([@Sendable ((any Error)?) -> ()])
case closed
}
private let lock: NIOLockedValueBox<State> = NIOLockedValueBox(.running([], []))
init(id: Int) {
self.id = id
}
var signalToClose: Void {
get async throws {
try await withCheckedThrowingContinuation { continuation in
let runRightAway = self.lock.withLockedValue { state -> Bool in
switch state {
case .running(var continuations, let callbacks):
continuations.append(continuation)
state = .running(continuations, callbacks)
return false
case .closing, .closed:
return true
}
}
if runRightAway {
continuation.resume()
}
}
}
}
func onClose(_ closure: @escaping @Sendable ((any Error)?) -> ()) {
let enqueued = self.lock.withLockedValue { state -> Bool in
switch state {
case .closed:
return false
case .running(let continuations, var callbacks):
callbacks.append(closure)
state = .running(continuations, callbacks)
return true
case .closing(var callbacks):
callbacks.append(closure)
state = .closing(callbacks)
return true
}
}
if !enqueued {
closure(nil)
}
}
func close() {
let continuations = self.lock.withLockedValue { state -> [CheckedContinuation<Void, any Error>] in
switch state {
case .running(let continuations, let callbacks):
state = .closing(callbacks)
return continuations
case .closing, .closed:
return []
}
}
for continuation in continuations {
continuation.resume()
}
}
func closeIfClosing() {
let callbacks = self.lock.withLockedValue { state -> [@Sendable ((any Error)?) -> ()] in
switch state {
case .running, .closed:
return []
case .closing(let callbacks):
state = .closed
return callbacks
}
}
for callback in callbacks {
callback(nil)
}
}
}
extension MockConnection: CustomStringConvertible {
var description: String {
let state = self.lock.withLockedValue { $0 }
return "MockConnection(id: \(self.id), state: \(state))"
}
}