forked from vapor/postgres-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMockClock.swift
176 lines (140 loc) · 5.72 KB
/
MockClock.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
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
import _ConnectionPoolModule
import Atomics
import DequeModule
import NIOConcurrencyHelpers
@available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *)
public final class MockClock: Clock {
public struct Instant: InstantProtocol, Comparable {
public typealias Duration = Swift.Duration
public func advanced(by duration: Self.Duration) -> Self {
.init(self.base + duration)
}
public func duration(to other: Self) -> Self.Duration {
self.base - other.base
}
private var base: Swift.Duration
public init(_ base: Duration) {
self.base = base
}
public static func < (lhs: Self, rhs: Self) -> Bool {
lhs.base < rhs.base
}
public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.base == rhs.base
}
}
private struct State: Sendable {
var now: Instant
var sleepersHeap: Array<Sleeper>
var waiters: Deque<Waiter>
var nextDeadlines: Deque<Instant>
init() {
self.now = .init(.seconds(0))
self.sleepersHeap = Array()
self.waiters = Deque()
self.nextDeadlines = Deque()
}
}
private struct Waiter {
var continuation: CheckedContinuation<Instant, Never>
}
private struct Sleeper {
var id: Int
var deadline: Instant
var continuation: CheckedContinuation<Void, any Error>
}
public typealias Duration = Swift.Duration
public var minimumResolution: Duration { .nanoseconds(1) }
public var now: Instant { self.stateBox.withLockedValue { $0.now } }
private let stateBox = NIOLockedValueBox(State())
private let waiterIDGenerator = ManagedAtomic(0)
public init() {}
public func sleep(until deadline: Instant, tolerance: Duration?) async throws {
let waiterID = self.waiterIDGenerator.loadThenWrappingIncrement(ordering: .relaxed)
return try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, any Error>) in
enum SleepAction {
case none
case resume
case cancel
}
let action = self.stateBox.withLockedValue { state -> (SleepAction, Waiter?) in
let waiter: Waiter?
if let next = state.waiters.popFirst() {
waiter = next
} else {
state.nextDeadlines.append(deadline)
waiter = nil
}
if Task.isCancelled {
return (.cancel, waiter)
}
if state.now >= deadline {
return (.resume, waiter)
}
let newSleeper = Sleeper(id: waiterID, deadline: deadline, continuation: continuation)
if let index = state.sleepersHeap.lastIndex(where: { $0.deadline < deadline }) {
state.sleepersHeap.insert(newSleeper, at: index + 1)
} else if let first = state.sleepersHeap.first, first.deadline > deadline {
state.sleepersHeap.insert(newSleeper, at: 0)
} else {
state.sleepersHeap.append(newSleeper)
}
return (.none, waiter)
}
switch action.0 {
case .cancel:
continuation.resume(throwing: CancellationError())
case .resume:
continuation.resume()
case .none:
break
}
action.1?.continuation.resume(returning: deadline)
}
} onCancel: {
let continuation = self.stateBox.withLockedValue { state -> CheckedContinuation<Void, any Error>? in
if let index = state.sleepersHeap.firstIndex(where: { $0.id == waiterID }) {
return state.sleepersHeap.remove(at: index).continuation
}
return nil
}
continuation?.resume(throwing: CancellationError())
}
}
@discardableResult
public func nextTimerScheduled() async -> Instant {
await withCheckedContinuation { (continuation: CheckedContinuation<Instant, Never>) in
let instant = self.stateBox.withLockedValue { state -> Instant? in
if let scheduled = state.nextDeadlines.popFirst() {
return scheduled
} else {
let waiter = Waiter(continuation: continuation)
state.waiters.append(waiter)
return nil
}
}
if let instant {
continuation.resume(returning: instant)
}
}
}
public func advance(to deadline: Instant) {
let waiters = self.stateBox.withLockedValue { state -> ArraySlice<Sleeper> in
precondition(deadline > state.now, "Time can only move forward")
state.now = deadline
if let newFirstIndex = state.sleepersHeap.firstIndex(where: { $0.deadline > deadline }) {
defer { state.sleepersHeap.removeFirst(newFirstIndex) }
return state.sleepersHeap[0..<newFirstIndex]
} else if let first = state.sleepersHeap.first, first.deadline <= deadline {
defer { state.sleepersHeap = [] }
return state.sleepersHeap[...]
} else {
return []
}
}
for waiter in waiters {
waiter.continuation.resume()
}
}
}