-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathEndpointFlowProtocols.swift
More file actions
537 lines (485 loc) · 17.4 KB
/
Copy pathEndpointFlowProtocols.swift
File metadata and controls
537 lines (485 loc) · 17.4 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
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2026 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(Glibc)
import Glibc
internal import Logging
#elseif canImport(Musl)
import Musl
internal import Logging
#elseif canImport(os)
internal import os
#endif
@available(Network 0.1.0, *)
protocol AbstractEndpointFlowProtocol: InboundDataHandler, LoggableProtocol {
func teardown()
}
@available(Network 0.1.0, *)
class EndpointFlowProtocol<LinkageType: InboundDataLinkage>: ProtocolInstanceContainer, AbstractEndpointFlowProtocol {
typealias LowerProtocol = LinkageType.PairedLinkage
#if !NETWORK_EMBEDDED
func accessUpper<R, E: Error>(
at index: Int?,
_ body: (inout any UpperProtocolHandler) throws(E) -> R
) throws(E) -> R {
var selfAccess: (any UpperProtocolHandler) = self
return try body(&selfAccess)
}
func accessInboundDataHandler<R, E: Error>(
at index: Int?,
_ body: (inout any InboundDataHandler) throws(E) -> R
) throws(E) -> R {
var selfAccess: (any InboundDataHandler) = self
return try body(&selfAccess)
}
#endif
// Completions: called once!
struct Completions {
public var connected: ((NetworkError?) -> Void)?
public var outputRoomAvailable: (() -> Void)?
// true when inbound data is available, false when disconnected
public var inboundDataAvailable: ((Bool) -> Void)?
// invoked when error detected
public var error: ((NetworkError) -> Void)?
// invoked when remote peer disconnects
public var disconnected: ((NetworkError) -> Void)?
public init() {}
}
var completions = Completions()
var log = NetworkLoggerState()
fileprivate(set) var context: NetworkContext
var reference: ProtocolInstanceReference { ProtocolInstanceReference(custom: self) }
var lower = LowerProtocol(reference: .init())
var asUpper: LinkageType { .init(reference: reference) }
var eventManager = ProtocolEventManager()
var local: Endpoint?
var remote: Endpoint
var parameters: Parameters
var path: PathProperties
fileprivate init(
identifier: String = "",
local: Endpoint?,
remote: Endpoint,
parameters: Parameters,
path: PathProperties,
context: NetworkContext
) {
log.logPrefix = "[EndpointFlowProtocol:\(identifier)]"
self.context = context
self.local = local
self.remote = remote
self.parameters = parameters
self.path = path
}
#if !NETWORK_EMBEDDED
init(
identifier: String = "",
local: Endpoint?,
remote: Endpoint,
parameters: Parameters,
path: PathProperties,
context: NetworkContext,
lowerProtocol: LinkageType.PairedLinkage
) throws(NetworkError) {
log.logPrefix = "[EndpointFlowProtocol:\(identifier)]"
self.context = context
self.local = local
self.remote = remote
self.parameters = parameters
self.path = path
self.lower = try lowerProtocol.invokeAttachUpperProtocol(
reference,
remote: remote,
local: local,
parameters: parameters,
path: path
)
}
#endif
func attachLowerProtocol(
_ lowerProtocol: ProtocolInstanceReference,
remote: Endpoint?,
local: Endpoint?,
parameters: Parameters?,
path: PathProperties?
) throws(NetworkError) {
throw NetworkError.posix(EINVAL)
}
func handleConnectedEvent(_ from: ProtocolInstanceReference) {
log.debug("Received connected event")
if let completion = completions.connected {
completion(nil)
self.completions.connected = nil
}
}
func handleDisconnectedEvent(_ from: ProtocolInstanceReference, error: NetworkError?) {
log.debug("Received disconnected event")
let disconnectError = error ?? .posix(ENOTCONN)
if let completion = completions.connected {
completion(disconnectError)
self.completions.connected = nil
}
if let error, let errorCompletion = self.completions.error {
errorCompletion(error)
self.completions.error = nil
}
if let inboundDataAvailableCompletion = self.completions.inboundDataAvailable {
inboundDataAvailableCompletion(false)
self.completions.inboundDataAvailable = nil
}
if let disconnectedCompletion = self.completions.disconnected {
disconnectedCompletion(disconnectError)
self.completions.disconnected = nil
}
}
func handleInboundDataAvailableEvent(_ from: ProtocolInstanceReference) {
log.debug("Received inbound data available event")
// Clear the slot before invoking: the completion may synchronously
// re-arm the waiter (when receiveStreamData returns nil because the
// requested minimum spans more than one segment). Clearing afterwards
// would clobber that re-registration and drop later notifications.
if let inboundDataAvailableCompletion = self.completions.inboundDataAvailable {
self.completions.inboundDataAvailable = nil
inboundDataAvailableCompletion(true)
}
}
public func handleOutboundRoomAvailableEvent(_ from: ProtocolInstanceReference) {
log.debug("Received outbound room available event")
if let completion = self.completions.outputRoomAvailable {
completion()
self.completions.outputRoomAvailable = nil
}
}
public func handleNetworkProtocolEvent(_ from: ProtocolInstanceReference, event: NetworkProtocolEvent) {
log.debug("Received network protocol event: \(event)")
}
public func start() {
fromExternal {
lower.invokeConnect(reference)
}
}
public func invokeApplicationEvent(_ event: ApplicationEvent) {
fromExternal {
lower.invokeApplicationEvent(reference, event: event)
}
}
public func start(_ completion: @escaping (NetworkError?) -> Void) {
self.completions.connected = completion
start()
}
public func stop() {
fromExternal {
lower.invokeDisconnect(reference)
}
}
public func teardown() {
fromExternal {
do throws(NetworkError) {
try lower.invokeDetach(reference)
lower = .init(reference: .init())
} catch {
log.error("Failed to detach lower protocol: \(error)")
}
}
}
public func waitForOutputRoomAvailable(_ completion: @escaping () -> Void) {
completions.outputRoomAvailable = completion
}
public func waitForInboundDataAvailable(completion: @escaping (Bool) -> Void) {
completions.inboundDataAvailable = completion
}
public func waitForError(completion: @escaping (NetworkError?) -> Void) {
completions.error = completion
}
public func waitForDisconnected(completion: @escaping (NetworkError) -> Void) {
completions.disconnected = completion
}
final public func getMetadata<P: NetworkProtocol>() -> ProtocolMetadata<P>? {
fromExternal {
guard let metadata = lower.invokeGetMetadata(reference) as? ProtocolMetadata<P> else {
return nil
}
return metadata
}
}
public func setApplicationError(_ applicationError: UInt64, applicationErrorReason: String) {
if let metadata: ProtocolMetadata<QUICProtocol> = self.getMetadata() {
metadata.perProtocolMetadata?.quicConnectionMetadata?.applicationError = applicationError
metadata.perProtocolMetadata?.quicConnectionMetadata?.applicationErrorReason = applicationErrorReason
}
}
}
@available(Network 0.1.0, *)
final class DatagramEndpointFlowProtocol: EndpointFlowProtocol<InboundDatagramLinkage>, InboundDatagramHandler {
override var reference: ProtocolInstanceReference { ProtocolInstanceReference(datagramEndpointFlow: self) }
convenience init(
identifier: String = "",
local: Endpoint?,
remote: Endpoint,
parameters: Parameters,
path: PathProperties,
context: NetworkContext,
lowerDatagramProtocol: OutboundDatagramLinkage
) throws(NetworkError) {
self.init(
identifier: identifier,
local: local,
remote: remote,
parameters: parameters,
path: path,
context: context
)
self.lower = try lowerDatagramProtocol.invokeAttachUpperDatagramProtocol(
reference,
remote: remote,
local: local,
parameters: parameters,
path: path
)
}
func attachLowerDatagramProtocol(
_ lowerProtocol: ProtocolInstanceReference,
remote: Endpoint?,
local: Endpoint?,
parameters: Parameters?,
path: PathProperties?
) throws(NetworkError) {
throw NetworkError.posix(EINVAL)
}
convenience init(
identifier: String = "",
local: Endpoint?,
remote: Endpoint,
parameters: Parameters,
path: PathProperties,
context: NetworkContext,
listenerProtocol: DatagramListenerLinkage
) throws(NetworkError) {
self.init(
identifier: identifier,
local: local,
remote: remote,
parameters: parameters,
path: path,
context: context
)
self.lower = try listenerProtocol.invokeAttachUpperDatagramProtocolToNewFlow(
reference,
remote: remote,
local: local,
parameters: parameters,
path: path
)
}
func write(_ datagram: consuming Frame) -> Bool {
fromExternal {
do throws(NetworkError) {
let length = datagram.unclaimedLength
let frames = try lower.invokeGetDatagramsToSend(
reference,
maximumDatagramCount: 1,
minimumDatagramSize: length
)
guard var frames = frames else {
log.error("Failed to get datagram to send")
return false
}
frames.iterateMutableFrames { frame in
let copiedLength = datagram.copyInto(&frame, length: length)
if copiedLength < length {
log.error("Failed to copy \(length) bytes, only copied \(copiedLength)")
}
let frameLength = frame.unclaimedLength
if frameLength > copiedLength {
_ = frame.collapse(to: copiedLength)
}
datagram.finalize(success: true)
return false
}
try lower.invokeSendDatagrams(reference, datagrams: frames)
return true
} catch {
return false
}
}
}
func read() -> [UInt8]? {
fromExternal {
do throws(NetworkError) {
let frames = try lower.invokeReceiveDatagrams(reference, maximumDatagramCount: 1)
guard var frames = frames else {
log.debug("Failed to receive datagrams")
return nil
}
var returnBuffer: [UInt8]? = nil
frames.iterateMutableFrames { frame in
var buffer = [UInt8]()
let length = frame.unclaimedLength
if length > 0 {
_ = Deserializer.deserialize(&frame, claim: false) { read throws(DeserializationError) in
try read.buffer(&buffer, length: length)
}
}
returnBuffer = buffer
frame.finalize(success: true)
return true
}
return returnBuffer
} catch {
return nil
}
}
}
}
@available(Network 0.1.0, *)
final class StreamEndpointFlowProtocol: EndpointFlowProtocol<InboundStreamLinkage>, InboundStreamHandler {
override var reference: ProtocolInstanceReference { ProtocolInstanceReference(streamEndpointFlow: self) }
func handleInboundAbortedEvent(_ from: ProtocolInstanceReference, error: NetworkError?) {}
func handleOutboundAbortedEvent(_ from: ProtocolInstanceReference, error: NetworkError?) {}
convenience init(
identifier: String = "",
local: Endpoint?,
remote: Endpoint,
parameters: Parameters,
path: PathProperties,
context: NetworkContext,
lowerStreamProtocol: OutboundStreamLinkage
) throws(NetworkError) {
self.init(
identifier: identifier,
local: local,
remote: remote,
parameters: parameters,
path: path,
context: context
)
self.lower = try lowerStreamProtocol.invokeAttachUpperStreamProtocol(
reference,
remote: remote,
local: local,
parameters: parameters,
path: path
)
}
func attachLowerStreamProtocol(
_ lowerProtocol: ProtocolInstanceReference,
remote: Endpoint?,
local: Endpoint?,
parameters: Parameters?,
path: PathProperties?
) throws(NetworkError) {
throw NetworkError.posix(EINVAL)
}
convenience init(
identifier: String = "",
local: Endpoint?,
remote: Endpoint,
parameters: Parameters,
path: PathProperties,
context: NetworkContext,
listenerProtocol: StreamListenerLinkage
) throws(NetworkError) {
self.init(
identifier: identifier,
local: local,
remote: remote,
parameters: parameters,
path: path,
context: context
)
self.lower = try listenerProtocol.invokeAttachUpperStreamProtocolToNewFlow(
reference,
remote: remote,
local: local,
parameters: parameters,
path: path
)
}
convenience init(
identifier: String = "",
local: Endpoint?,
remote: Endpoint,
parameters: Parameters,
path: PathProperties,
context: NetworkContext,
listenerProtocol: StreamListenerLinkage,
existingFlowReference: ProtocolInstanceReference
) throws(NetworkError) {
self.init(
identifier: identifier,
local: local,
remote: remote,
parameters: parameters,
path: path,
context: context
)
self.lower = try listenerProtocol.invokeAttachUpperStreamProtocolToExistingFlow(
reference,
flowReference: existingFlowReference
)
}
private func invokeSendStreamData(_ streamData: consuming FrameArray) throws(NetworkError) {
try fromExternal(streamData) { streamData throws(NetworkError) in
try lower.invokeSendStreamData(self.reference, streamData: streamData)
}
}
func getOutboundStreamDataRoomAvailable() throws(NetworkError) -> Int {
try fromExternal { () throws(NetworkError) in
try lower.invokeGetOutboundStreamDataRoomAvailable(self.reference)
}
}
func write(_ frame: consuming Frame) -> Bool {
do throws(NetworkError) {
try invokeSendStreamData(.init(frame: frame))
return true
} catch {
return false
}
}
func read(minimumBytes: Int, maximumBytes: Int) -> [UInt8]? {
fromExternal {
do throws(NetworkError) {
guard
var frames = try lower.invokeReceiveStreamData(
reference,
minimumBytes: minimumBytes,
maximumBytes: maximumBytes
)
else {
log.debug("No more stream data available")
return nil
}
var returnBuffer: [UInt8]? = nil
frames.iterateMutableFrames { frame in
var buffer = [UInt8]()
let length = frame.unclaimedLength
if length > 0 {
_ = Deserializer.deserialize(&frame, claim: false) { read throws(DeserializationError) in
try read.buffer(&buffer, length: length)
}
}
if returnBuffer == nil {
returnBuffer = buffer
} else {
returnBuffer?.append(contentsOf: buffer)
}
frame.finalize(success: true)
return true
}
return returnBuffer
} catch {
return nil
}
}
}
}