-
Notifications
You must be signed in to change notification settings - Fork 43
/
SocketPool.swift
295 lines (258 loc) · 9.95 KB
/
SocketPool.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
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
//
// EventQueueSocketPool.swift
// FlyingFox
//
// Created by Simon Whitty on 10/09/2022.
// Copyright © 2022 Simon Whitty. All rights reserved.
//
// Distributed under the permissive MIT license
// Get the latest version from here:
//
// https://github.com/swhitty/FlyingFox
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Dispatch
import Foundation
public protocol EventQueue {
mutating func open() throws
mutating func stop() throws
mutating func close() throws
mutating func addEvents(_ events: Socket.Events, for socket: Socket.FileDescriptor) throws
mutating func removeEvents(_ events: Socket.Events, for socket: Socket.FileDescriptor) throws
func getNotifications() throws -> [EventNotification]
}
public struct EventNotification: Equatable, Sendable {
public var file: Socket.FileDescriptor
public var events: Socket.Events
public var errors: Set<Error>
public enum Error: Sendable {
case endOfFile
case error
}
}
@available(*, unavailable, message: "use .make(maxEvents:)")
public func makeEventQueuePool(maxEvents limit: Int = 20) -> any AsyncSocketPool {
fatalError("init pool directly")
}
public extension AsyncSocketPool where Self == SocketPool<Poll> {
static func make(maxEvents limit: Int = 20, logger: some Logging = .disabled) -> some AsyncSocketPool {
#if canImport(Darwin)
return .kQueue(maxEvents: limit, logger: logger)
#elseif canImport(CSystemLinux)
return .ePoll(maxEvents: limit, logger: logger)
#else
return .poll(interval: .seconds(0.01), logger: logger)
#endif
}
}
public final actor SocketPool<Queue: EventQueue>: AsyncSocketPool {
private(set) var queue: Queue
private let dispatchQueue: DispatchQueue
private(set) var state: State?
private let logger: any Logging
public init(queue: Queue, dispatchQueue: DispatchQueue = .init(label: "flyingfox"), logger: some Logging = .disabled) {
self.queue = queue
self.dispatchQueue = dispatchQueue
self.logger = logger
}
public func prepare() async throws {
logger.logInfo("SocketPoll prepare")
try queue.open()
state = .ready
}
public func run() async throws {
guard state == .ready else { throw Error("Not Ready") }
state = .running
defer { cancelAll() }
repeat {
if waiting.isEmpty {
try await suspendUntilContinuationsExist()
}
try await processNotifications(getNotifications())
} while true
}
public func suspendSocket(_ socket: Socket, untilReadyFor events: Socket.Events) async throws {
guard state == .running || state == .ready else { throw Error("Not Ready") }
return try await withIdentifiableThrowingContinuation(isolation: self) {
appendContinuation($0, for: socket.file, events: events)
} onCancel: { id in
Task {
await self.resumeContinuation(id: id, with: .failure(CancellationError()), for: socket.file)
}
}
}
private func getNotifications() async throws -> [EventNotification] {
try Task.checkCancellation()
let queue = UncheckedSendable(wrappedValue: queue)
return try await withIdentifiableThrowingContinuation(isolation: self) { continuation in
dispatchQueue.async {
let result = Result {
try queue.wrappedValue.getNotifications()
}
continuation.resume(with: result)
}
} onCancel: { _ in
Task { await self.stopQueue() }
}
}
private func stopQueue() {
try? queue.stop()
}
private func processNotifications(_ notifications: [EventNotification]) {
for notification in notifications {
processNotification(notification)
}
}
private func processNotification(_ notification: EventNotification) {
for id in waiting.continuationIDs(for: notification.file, events: notification.events) {
resumeContinuation(id: id, with: notification.result, for: notification.file)
}
}
enum State {
case ready
case running
case complete
}
private func cancelAll() {
logger.logInfo("SocketPoll cancelAll")
try? queue.stop()
state = .complete
waiting.cancelAll()
waiting = Waiting()
if let loop {
self.loop = nil
loop.resume(throwing: CancellationError())
}
try? queue.close()
}
typealias Continuation = IdentifiableContinuation<Void, any Swift.Error>
private var loop: Continuation?
private var waiting = Waiting() {
didSet {
if let loop, !waiting.isEmpty {
self.loop = nil
loop.resume()
}
}
}
private func suspendUntilContinuationsExist() async throws {
try await withIdentifiableThrowingContinuation(isolation: self) {
loop = $0
} onCancel: { id in
Task { await self.cancelLoopContinuation(with: id) }
}
}
private func cancelLoopContinuation(with id: Continuation.ID) {
if let loop, loop.id == id {
self.loop = nil
loop.resume(throwing: CancellationError())
}
}
private func appendContinuation(
_ continuation: Continuation,
for socket: Socket.FileDescriptor,
events: Socket.Events
) {
let events = waiting.appendContinuation(continuation, for: socket, events: events)
do {
try queue.addEvents(events, for: socket)
} catch {
resumeContinuation(
id: continuation.id,
with: .failure(error),
for: socket
)
}
}
private func resumeContinuation(
id: Continuation.ID,
with result: Result<Void, any Swift.Error>,
for socket: Socket.FileDescriptor
) {
do {
let events = waiting.resumeContinuation(id: id, with: result, for: socket)
try queue.removeEvents(events, for: socket)
} catch {
logger.logError("resumeContinuation queue.removeEvents: \(error.localizedDescription)")
}
}
private struct Error: LocalizedError {
var errorDescription: String?
init(_ description: String) {
self.errorDescription = description
}
}
struct Waiting {
private var storage: [Socket.FileDescriptor: [Continuation.ID: (continuation: Continuation, events: Socket.Events)]] = [:]
var isEmpty: Bool { storage.isEmpty }
// Adds continuation returning all events required by all waiters
mutating func appendContinuation(_ continuation: Continuation,
for socket: Socket.FileDescriptor,
events: Socket.Events) -> Socket.Events {
var entries = storage[socket] ?? [:]
entries[continuation.id] = (continuation, events)
storage[socket] = entries
return entries.values.reduce(Socket.Events()) {
$0.union($1.events)
}
}
// Resumes and removes continuation, returning any events that are no longer being waited
mutating func resumeContinuation(id: Continuation.ID,
with result: Result<Void, any Swift.Error>,
for socket: Socket.FileDescriptor) -> Socket.Events {
var entries = storage[socket] ?? [:]
guard let (continuation, events) = entries.removeValue(forKey: id) else { return [] }
continuation.resume(with: result)
storage[socket] = entries.isEmpty ? nil : entries
let remaining = entries.values.reduce(Socket.Events()) {
$0.union($1.events)
}
return events.filter { !remaining.contains($0) }
}
func continuationIDs(for socket: Socket.FileDescriptor, events: Socket.Events) -> [Continuation.ID] {
let entries = storage[socket] ?? [:]
return entries.compactMap { id, ev in
if events.intersection(ev.events).isEmpty {
return nil
} else {
return id
}
}
}
mutating func cancelAll() {
let continuations = storage.values.flatMap(\.values).map(\.continuation)
storage = [:]
for continuation in continuations {
continuation.resume(throwing: CancellationError())
}
}
}
}
private extension EventNotification {
var result: Result<Void, any Swift.Error> {
errors.isEmpty ? .success(()) : .failure(SocketError.disconnected)
}
}
struct UncheckedSendable<Value>: @unchecked Sendable {
var wrappedValue: Value
init(wrappedValue: Value) {
self.wrappedValue = wrappedValue
}
}