File: PendingDatagramWritesManagerTests.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (616 lines) | stat: -rw-r--r-- 38,081 bytes parent folder | download
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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//

@testable import NIO
import XCTest

private extension SocketAddress {
    init(_ addr: UnsafePointer<sockaddr>) {
        switch NIOBSDSocket.AddressFamily(rawValue: CInt(addr.pointee.sa_family)) {
        case .unix:
            self = addr.withMemoryRebound(to: sockaddr_un.self, capacity: 1) {
                SocketAddress($0.pointee)
            }
        case .inet:
            self = addr.withMemoryRebound(to: sockaddr_in.self, capacity: 1) {
                SocketAddress($0.pointee, host: "")
            }
        case .inet6:
            self = addr.withMemoryRebound(to: sockaddr_in6.self, capacity: 1) {
                SocketAddress($0.pointee, host: "")
            }
        default:
            fatalError("Unexpected family type")
        }
    }

    var expectedSize: socklen_t {
        switch self {
        case .v4:
            return socklen_t(MemoryLayout<sockaddr_in>.size)
        case .v6:
            return socklen_t(MemoryLayout<sockaddr_in6>.size)
        case .unixDomainSocket:
            return socklen_t(MemoryLayout<sockaddr_un>.size)
        }
    }
}

class PendingDatagramWritesManagerTests: XCTestCase {
    private func withPendingDatagramWritesManager(_ body: (PendingDatagramWritesManager) throws -> Void) rethrows {
        try withExtendedLifetime(NSObject()) { o in
            var iovecs: [IOVector] = Array(repeating: iovec(), count: Socket.writevLimitIOVectors + 1)
            var managed: [Unmanaged<AnyObject>] = Array(repeating: Unmanaged.passUnretained(o), count: Socket.writevLimitIOVectors + 1)
            var msgs: [MMsgHdr] = Array(repeating: MMsgHdr(), count: Socket.writevLimitIOVectors + 1)
            var addresses: [sockaddr_storage] = Array(repeating: sockaddr_storage(), count: Socket.writevLimitIOVectors + 1)
            var controlMessageStorage = UnsafeControlMessageStorage.allocate(msghdrCount: Socket.writevLimitIOVectors)
            defer {
                controlMessageStorage.deallocate()
            }
            /* put a canary value at the end */
            iovecs[iovecs.count - 1] = iovec(iov_base: UnsafeMutableRawPointer(bitPattern: 0xdeadbee)!, iov_len: 0xdeadbee)
            try iovecs.withUnsafeMutableBufferPointer { iovecs in
                try managed.withUnsafeMutableBufferPointer { managed in
                    try msgs.withUnsafeMutableBufferPointer { msgs in
                        try addresses.withUnsafeMutableBufferPointer { addresses in
                            let pwm = NIO.PendingDatagramWritesManager(msgs: msgs,
                                                                       iovecs: iovecs,
                                                                       addresses: addresses,
                                                                       storageRefs: managed,
                                                                       controlMessageStorage: controlMessageStorage)
                            XCTAssertTrue(pwm.isEmpty)
                            XCTAssertTrue(pwm.isOpen)
                            XCTAssertFalse(pwm.isFlushPending)
                            XCTAssertTrue(pwm.isWritable)

                            try body(pwm)

                            XCTAssertTrue(pwm.isEmpty)
                            XCTAssertFalse(pwm.isFlushPending)
                        }
                    }
                }
            }
            /* assert that the canary values are still okay, we should definitely have never written those */
            XCTAssertEqual(managed.last!.toOpaque(), Unmanaged.passUnretained(o).toOpaque())
            XCTAssertEqual(0xdeadbee, Int(bitPattern: iovecs.last!.iov_base))
            XCTAssertEqual(0xdeadbee, iovecs.last!.iov_len)
        }
    }

    /// A frankenstein testing monster. It asserts that for `PendingDatagramWritesManager` `pwm` and `EventLoopPromises` `promises`
    /// the following conditions hold:
    ///  - The 'single write operation' is called `exepectedSingleWritabilities.count` number of times with the respective buffer lengths in the array.
    ///  - The 'vector write operation' is called `exepectedVectorWritabilities.count` number of times with the respective buffer lengths in the array.
    ///  - after calling the write operations, the promises have the states in `promiseStates`
    ///
    /// The write operations will all be faked and return the return values provided in `returns`.
    ///
    /// - parameters:
    ///     - pwm: The `PendingStreamWritesManager` to test.
    ///     - promises: The promises for the writes issued.
    ///     - expectedSingleWritabilities: The expected buffer lengths and addresses for the calls to the single write operation.
    ///     - expectedVectorWritabilities: The expected buffer lengths and addresses for the calls to the vector write operation.
    ///     - returns: The return values of the fakes write operations (both single and vector).
    ///     - promiseStates: The states of the promises _after_ the write operations are done.
    private func assertExpectedWritability(pendingWritesManager pwm: PendingDatagramWritesManager,
                                           promises: [EventLoopPromise<Void>],
                                           expectedSingleWritabilities: [(Int, SocketAddress)]?,
                                           expectedVectorWritabilities: [[(Int, SocketAddress)]]?,
                                           returns: [Result<IOResult<Int>, Error>],
                                           promiseStates: [[Bool]],
                                           file: StaticString = #file,
                                           line: UInt = #line) throws -> OverallWriteResult {
        var everythingState = 0
        var singleState = 0
        var multiState = 0
        var err: Error? = nil
        var result: OverallWriteResult? = nil

        do {
            let r = try pwm.triggerAppropriateWriteOperations(scalarWriteOperation: { (buf, addr, len, metadata) in
                defer {
                    singleState += 1
                    everythingState += 1
                }
                if let expected = expectedSingleWritabilities {
                    if expected.count > singleState {
                        XCTAssertGreaterThan(returns.count, everythingState)
                        XCTAssertEqual(expected[singleState].0, buf.count, "in single write \(singleState) (overall \(everythingState)), \(expected[singleState].0) bytes expected but \(buf.count) actual", file: (file), line: line)
                        XCTAssertEqual(expected[singleState].1, SocketAddress(addr), "in single write \(singleState) (overall \(everythingState)), \(expected[singleState].1) address expected but \(SocketAddress(addr)) received", file: (file), line: line)
                        XCTAssertEqual(expected[singleState].1.expectedSize, len, "in single write \(singleState) (overall \(everythingState)), \(expected[singleState].1.expectedSize) socklen expected but \(len) received", file: (file), line: line)

                        switch returns[everythingState] {
                        case .success(let r):
                            return r
                        case .failure(let e):
                            throw e
                        }
                    } else {
                        XCTFail("single write call \(singleState) but less than \(expected.count) expected", file: (file), line: line)
                        return IOResult.wouldBlock(-1 * (everythingState + 1))
                    }
                } else {
                    XCTFail("single write called on \(buf) but no single writes expected", file: (file), line: line)
                    return IOResult.wouldBlock(-1 * (everythingState + 1))
                }
            }, vectorWriteOperation: { ptrs in
                defer {
                    multiState += 1
                    everythingState += 1
                }
                if let expected = expectedVectorWritabilities {
                    if expected.count > multiState {
                        XCTAssertGreaterThan(returns.count, everythingState)
                        XCTAssertEqual(ptrs.map { $0.msg_hdr.msg_iovlen }, Array(repeating: 1, count: ptrs.count), "mustn't write more than one iovec element per datagram", file: (file), line: line)
                        XCTAssertEqual(expected[multiState].map { numericCast($0.0) }, ptrs.map { $0.msg_hdr.msg_iov.pointee.iov_len },
                                       "in vector write \(multiState) (overall \(everythingState)), \(expected[multiState]) byte counts expected but \(ptrs.map { $0.msg_hdr.msg_iov.pointee.iov_len }) actual",
                                       file: (file), line: line)
                        XCTAssertEqual(expected[multiState].map { $0.0 }, ptrs.map { Int($0.msg_len) },
                                       "in vector write \(multiState) (overall \(everythingState)), \(expected[multiState]) byte counts expected but \(ptrs.map { $0.msg_len }) actual",
                            file: (file), line: line)
                        XCTAssertEqual(expected[multiState].map { $0.1 }, ptrs.map { SocketAddress($0.msg_hdr.msg_name.assumingMemoryBound(to: sockaddr.self)) }, "in vector write \(multiState) (overall \(everythingState)), \(expected[multiState].map { $0.1 }) addresses expected but \(ptrs.map { SocketAddress($0.msg_hdr.msg_name.assumingMemoryBound(to: sockaddr.self)) }) actual",
                            file: (file), line: line)
                        XCTAssertEqual(expected[multiState].map { $0.1.expectedSize }, ptrs.map { $0.msg_hdr.msg_namelen }, "in vector write \(multiState) (overall \(everythingState)), \(expected[multiState].map { $0.1.expectedSize }) address lengths expected but \(ptrs.map { $0.msg_hdr.msg_namelen }) actual",
                            file: (file), line: line)

                        switch returns[everythingState] {
                        case .success(let r):
                            return r
                        case .failure(let e):
                            throw e
                        }
                    } else {
                        XCTFail("vector write call \(multiState) but less than \(expected.count) expected", file: (file), line: line)
                        return IOResult.wouldBlock(-1 * (everythingState + 1))
                    }
                } else {
                    XCTFail("vector write called on \(ptrs) but no vector writes expected",
                        file: (file), line: line)
                    return IOResult.wouldBlock(-1 * (everythingState + 1))
                }
            })
            result = r
        } catch {
            err = error
        }

        if everythingState > 0 {
            XCTAssertEqual(promises.count, promiseStates[everythingState - 1].count,
                           "number of promises (\(promises.count)) != number of promise states (\(promiseStates[everythingState - 1].count))",
                file: (file), line: line)
            _ = zip(promises, promiseStates[everythingState - 1]).map { p, pState in
                XCTAssertEqual(p.futureResult.isFulfilled, pState, "promise states incorrect (\(everythingState) callbacks)", file: (file), line: line)
            }

            XCTAssertEqual(everythingState, singleState + multiState,
                           "odd, calls the single/vector writes: \(singleState)/\(multiState)/ but overall \(everythingState+1)", file: (file), line: line)

            if singleState == 0 {
                XCTAssertNil(expectedSingleWritabilities, "no single writes have been done but we expected some", file: (file), line: line)
            } else {
                XCTAssertEqual(singleState, (expectedSingleWritabilities?.count ?? Int.min), "different number of single writes than expected", file: (file), line: line)
            }
            if multiState == 0 {
                XCTAssertNil(expectedVectorWritabilities, "no vector writes have been done but we expected some")
            } else {
                XCTAssertEqual(multiState, (expectedVectorWritabilities?.count ?? Int.min), "different number of vector writes than expected", file: (file), line: line)
            }
        } else {
            XCTAssertEqual(0, returns.count, "no callbacks called but apparently \(returns.count) expected", file: (file), line: line)
            XCTAssertNil(expectedSingleWritabilities, "no callbacks called but apparently some single writes expected", file: (file), line: line)
            XCTAssertNil(expectedVectorWritabilities, "no callbacks calles but apparently some vector writes expected", file: (file), line: line)

            _ = zip(promises, promiseStates[0]).map { p, pState in
                XCTAssertEqual(p.futureResult.isFulfilled, pState, "promise states incorrect (no callbacks)", file: (file), line: line)
            }
        }

        if let error = err {
            throw error
        }
        return result!
    }

    /// Tests that writes of empty buffers work correctly and that we don't accidentally write buffers that haven't been flushed.
    func testPendingWritesEmptyWritesWorkAndWeDontWriteUnflushedThings() throws {
        let el = EmbeddedEventLoop()
        let alloc = ByteBufferAllocator()
        let address = try SocketAddress(ipAddress: "127.0.0.1", port: 65535)
        var buffer = alloc.buffer(capacity: 12)

        try withPendingDatagramWritesManager { pwm in
            buffer.clear()
            let ps: [EventLoopPromise<Void>] = (0..<2).map { (_: Int) in el.makePromise() }
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: address, data: buffer), promise: ps[0])

            XCTAssertFalse(pwm.isEmpty)
            XCTAssertFalse(pwm.isFlushPending)

            pwm.markFlushCheckpoint()

            XCTAssertFalse(pwm.isEmpty)
            XCTAssertTrue(pwm.isFlushPending)

            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: address, data: buffer), promise: ps[1])

            var result = try assertExpectedWritability(pendingWritesManager: pwm,
                                                       promises: ps,
                                                       expectedSingleWritabilities: [(0, address)],
                                                       expectedVectorWritabilities: nil,
                                                       returns: [.success(.processed(0))],
                                                       promiseStates: [[true, false]])

            XCTAssertFalse(pwm.isEmpty)
            XCTAssertFalse(pwm.isFlushPending)
            XCTAssertEqual(.writtenCompletely, result.writeResult)

            result = try assertExpectedWritability(pendingWritesManager: pwm,
                                                   promises: ps,
                                                   expectedSingleWritabilities: nil,
                                                   expectedVectorWritabilities: nil,
                                                   returns: [],
                                                   promiseStates: [[true, false]])
            XCTAssertEqual(.writtenCompletely, result.writeResult)

            pwm.markFlushCheckpoint()

            result = try assertExpectedWritability(pendingWritesManager: pwm,
                                                   promises: ps,
                                                   expectedSingleWritabilities: [(0, address)],
                                                   expectedVectorWritabilities: nil,
                                                   returns: [.success(.processed(0))],
                                                   promiseStates: [[true, true]])
            XCTAssertEqual(.writtenCompletely, result.writeResult)
        }
    }

    /// This tests that we do use the vector write operation if we have more than one flushed and still doesn't write unflushed buffers
    func testPendingWritesUsesVectorWriteOperationAndDoesntWriteTooMuch() throws {
        let el = EmbeddedEventLoop()
        let alloc = ByteBufferAllocator()
        let firstAddress = try SocketAddress(ipAddress: "127.0.0.1", port: 65535)
        let secondAddress = try SocketAddress(ipAddress: "127.0.0.2", port: 65535)
        var buffer = alloc.buffer(capacity: 12)
        let emptyBuffer = buffer
        _ = buffer.writeString("1234")

        try withPendingDatagramWritesManager { pwm in
            let ps: [EventLoopPromise<Void>] = (0..<3).map { (_: Int) in el.makePromise() }
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: firstAddress, data: buffer), promise: ps[0])
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: secondAddress, data: buffer), promise: ps[1])
            pwm.markFlushCheckpoint()
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: firstAddress, data: emptyBuffer), promise: ps[2])

            var result = try assertExpectedWritability(pendingWritesManager: pwm,
                                                       promises: ps,
                                                       expectedSingleWritabilities: nil,
                                                       expectedVectorWritabilities: [[(4, firstAddress), (4, secondAddress)]],
                                                       returns: [.success(.processed(2))],
                                                       promiseStates: [[true, true, false]])
            XCTAssertEqual(.writtenCompletely, result.writeResult)

            pwm.markFlushCheckpoint()

            result = try assertExpectedWritability(pendingWritesManager: pwm,
                                                   promises: ps,
                                                   expectedSingleWritabilities: [(0, firstAddress)],
                                                   expectedVectorWritabilities: nil,
                                                   returns: [.success(.processed(0))],
                                                   promiseStates: [[true, true, true]])
            XCTAssertEqual(.writtenCompletely, result.writeResult)
        }
    }

    /// Tests that we can handle partial writes correctly.
    func testPendingWritesWorkWithPartialWrites() throws {
        let el = EmbeddedEventLoop()
        let alloc = ByteBufferAllocator()
        let firstAddress = try SocketAddress(ipAddress: "fe80::1", port: 65535)
        let secondAddress = try SocketAddress(ipAddress: "fe80::2", port: 65535)
        var buffer = alloc.buffer(capacity: 12)
        buffer.writeString("1234")

        try withPendingDatagramWritesManager { pwm in
            let ps: [EventLoopPromise<Void>] = (0..<4).map { (_: Int) in el.makePromise() }
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: firstAddress, data: buffer), promise: ps[0])
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: secondAddress, data: buffer), promise: ps[1])
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: firstAddress, data: buffer), promise: ps[2])
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: secondAddress, data: buffer), promise: ps[3])
            pwm.markFlushCheckpoint()

            var result = try assertExpectedWritability(pendingWritesManager: pwm,
                                                       promises: ps,
                                                       expectedSingleWritabilities: nil,
                                                       expectedVectorWritabilities: [
                                                            [(4, firstAddress), (4, secondAddress), (4, firstAddress), (4, secondAddress)],
                                                            [(4, secondAddress), (4, firstAddress), (4, secondAddress)]
                                                       ],
                                                       returns: [.success(.processed(1)), .success(.wouldBlock(0))],
                                                       promiseStates: [[true, false, false, false], [true, false, false, false]])

            XCTAssertEqual(.couldNotWriteEverything, result.writeResult)
            result = try assertExpectedWritability(pendingWritesManager: pwm,
                                                   promises: ps,
                                                   expectedSingleWritabilities: [(4, secondAddress)],
                                                   expectedVectorWritabilities: [
                                                        [(4, secondAddress), (4, firstAddress), (4, secondAddress)],
                                                   ],
                                                   returns: [.success(.processed(2)), .success(.wouldBlock(0))],
                                                   promiseStates: [[true, true, true, false], [true, true, true, false]]

            )
            XCTAssertEqual(.couldNotWriteEverything, result.writeResult)

            result = try assertExpectedWritability(pendingWritesManager: pwm,
                                                   promises: ps,
                                                   expectedSingleWritabilities: [(4, secondAddress)],
                                                   expectedVectorWritabilities: nil,
                                                   returns: [.success(.processed(4))],
                                                   promiseStates: [[true, true, true, true]])
            XCTAssertEqual(.writtenCompletely, result.writeResult)
        }
    }

    /// Tests that the spin count works for many buffers if each is written one by one.
    func testPendingWritesSpinCountWorksForSingleWrites() throws {
        let el = EmbeddedEventLoop()
        let alloc = ByteBufferAllocator()
        let address = try SocketAddress(ipAddress: "127.0.0.1", port: 65535)
        var buffer = alloc.buffer(capacity: 12)
        buffer.writeBytes(Array<UInt8>(repeating: 0xff, count: 12))

        try withPendingDatagramWritesManager { pwm in
            let ps: [EventLoopPromise<Void>] = (0...pwm.writeSpinCount+1).map { (_: UInt) in el.makePromise() }
            ps.forEach { _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: address, data: buffer), promise: $0) }
            let maxVectorWritabilities = ps.map { (_: EventLoopPromise<Void>) in (buffer.readableBytes, address) }
            let actualVectorWritabilities = maxVectorWritabilities.indices.dropLast().map { Array(maxVectorWritabilities[$0...]) }
            let actualPromiseStates = ps.indices.dropFirst().map { Array(repeating: true, count: $0) + Array(repeating: false, count: ps.count - $0) }

            pwm.markFlushCheckpoint()

            /* below, we'll write 1 datagram at a time. So the number of datagrams offered should decrease by one.
             The write operation should be repeated until we did it 1 + spin count times and then return `.couldNotWriteEverything`.
             After that, one datagram will remain */
            var result = try assertExpectedWritability(pendingWritesManager: pwm,
                                                       promises: ps,
                                                       expectedSingleWritabilities: nil,
                                                       expectedVectorWritabilities: Array(actualVectorWritabilities),
                                                       returns: Array(repeating: .success(.processed(1)), count: ps.count - 1),
                                                       promiseStates: actualPromiseStates)
            XCTAssertEqual(.couldNotWriteEverything, result.writeResult)

            /* we'll now write the one last datagram and assert that all the writes are complete */
            result = try assertExpectedWritability(pendingWritesManager: pwm,
                                                   promises: ps,
                                                   expectedSingleWritabilities: [(12, address)],
                                                   expectedVectorWritabilities: nil,
                                                   returns: [.success(.processed(12))],
                                                   promiseStates: [Array(repeating: true, count: ps.count - 1) + [true]])
            XCTAssertEqual(.writtenCompletely, result.writeResult)
        }
    }

    /// Test that cancellation of the Channel writes works correctly.
    func testPendingWritesCancellationWorksCorrectly() throws {
        let el = EmbeddedEventLoop()
        let alloc = ByteBufferAllocator()
        let address = try SocketAddress(ipAddress: "127.0.0.1", port: 65535)
        var buffer = alloc.buffer(capacity: 12)
        buffer.writeString("1234")

        try withPendingDatagramWritesManager { pwm in
            let ps: [EventLoopPromise<Void>] = (0..<3).map { (_: Int) in el.makePromise() }
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: address, data: buffer), promise: ps[0])
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: address, data: buffer), promise: ps[1])
            pwm.markFlushCheckpoint()
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: address, data: buffer), promise: ps[2])

            let result = try assertExpectedWritability(pendingWritesManager: pwm,
                                                       promises: ps,
                                                       expectedSingleWritabilities: nil,
                                                       expectedVectorWritabilities: [[(4, address), (4, address)]],
                                                       returns: [.success(.wouldBlock(0))],
                                                       promiseStates: [[false, false, false], [false, false, false]])
            XCTAssertEqual(.couldNotWriteEverything, result.writeResult)

            pwm.failAll(error: ChannelError.operationUnsupported, close: true)

            XCTAssertTrue(ps.map { $0.futureResult.isFulfilled }.allSatisfy { $0 })
        }
    }

    /// Test that with a few massive buffers, we don't offer more than we should to `writev` if the individual chunks fit.
    func testPendingWritesNoMoreThanWritevLimitIsWritten() throws {
        let el = EmbeddedEventLoop()
        let alloc = ByteBufferAllocator(hookedMalloc: { _ in return UnsafeMutableRawPointer(bitPattern: 0xdeadbee)! },
                                        hookedRealloc: { _, _ in return UnsafeMutableRawPointer(bitPattern: 0xdeadbee)! },
                                        hookedFree: { _ in },
                                        hookedMemcpy: { _, _, _ in })
        /* each buffer is half the writev limit */
        let halfTheWriteVLimit = Socket.writevLimitBytes / 2
        var buffer = alloc.buffer(capacity: halfTheWriteVLimit)
        buffer.moveReaderIndex(to: 0)
        buffer.moveWriterIndex(to: halfTheWriteVLimit)
        let address = try SocketAddress(ipAddress: "127.0.0.1", port: 65535)

        try withPendingDatagramWritesManager { pwm in
            let ps: [EventLoopPromise<Void>] = (0..<3).map { (_: Int) in el.makePromise() }
            /* add 1.5x the writev limit */
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: address, data: buffer), promise: ps[0])
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: address, data: buffer), promise: ps[1])
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: address, data: buffer), promise: ps[2])
            pwm.markFlushCheckpoint()

            let result = try assertExpectedWritability(pendingWritesManager: pwm,
                                                       promises: ps,
                                                       expectedSingleWritabilities: [(halfTheWriteVLimit, address)],
                                                       expectedVectorWritabilities: [[(halfTheWriteVLimit, address), (halfTheWriteVLimit, address)]],
                                                       returns: [.success(.processed(2)), .success(.processed(1))],
                                                       promiseStates: [[true, true, false], [true, true, true]])
            XCTAssertEqual(.writtenCompletely, result.writeResult)
        }
    }

    /// Test that with a massive buffers (bigger than writev size), we fall back to linear processing.
    func testPendingWritesNoMoreThanWritevLimitIsWrittenInOneMassiveChunk() throws {
        if MemoryLayout<Int>.size == MemoryLayout<Int32>.size  { // skip this test on 32bit system
            return
        }

        let el = EmbeddedEventLoop()
        let address = try SocketAddress(ipAddress: "127.0.0.1", port: 65535)
        let alloc = ByteBufferAllocator(hookedMalloc: { _ in return UnsafeMutableRawPointer(bitPattern: 0xdeadbee)! },
                                        hookedRealloc: { _, _ in return UnsafeMutableRawPointer(bitPattern: 0xdeadbee)! },
                                        hookedFree: { _ in },
                                        hookedMemcpy: { _, _, _ in })

        let biggerThanWriteV = Socket.writevLimitBytes + 23
        var buffer = alloc.buffer(capacity: biggerThanWriteV)
        buffer.moveReaderIndex(to: 0)
        buffer.moveWriterIndex(to: biggerThanWriteV)

        try withPendingDatagramWritesManager { pwm in
            let ps: [EventLoopPromise<Void>] = (0..<3).map { (_: Int) in el.makePromise() }
            /* add 1.5x the writev limit */
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: address, data: buffer), promise: ps[0])
            buffer.moveReaderIndex(to: 100)
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: address, data: buffer), promise: ps[1])
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: address, data: buffer), promise: ps[2])

            pwm.markFlushCheckpoint()

            let result = try assertExpectedWritability(pendingWritesManager: pwm,
                                                       promises: ps,
                                                       expectedSingleWritabilities: [(Socket.writevLimitBytes + 23, address),
                                                                                     (Socket.writevLimitBytes - 77, address)],
                                                       expectedVectorWritabilities: [[(Socket.writevLimitBytes - 77, address)]],
                                                       returns: [
                                                            .failure(IOError(errnoCode: EMSGSIZE, reason: "")),
                                                            .success(.processed(1)),
                                                            .success(.processed(1))],
                                                       promiseStates: [[true, false, false], [true, true, false], [true, true, true]])

            XCTAssertEqual(.writtenCompletely, result.writeResult)

            XCTAssertNoThrow(try ps[1].futureResult.wait())
            XCTAssertNoThrow(try ps[2].futureResult.wait())

            do {
                try ps[0].futureResult.wait()
                XCTFail("Did not throw")
            } catch ChannelError.writeMessageTooLarge {
                // Ok
            } catch {
                XCTFail("Unexpected error \(error)")
            }
        }
    }

    func testPendingWritesWorksWithManyEmptyWrites() throws {
        let el = EmbeddedEventLoop()
        let alloc = ByteBufferAllocator()
        let emptyBuffer = alloc.buffer(capacity: 12)
        let address = try SocketAddress(ipAddress: "127.0.0.1", port: 80)

        try withPendingDatagramWritesManager { pwm in
            let ps: [EventLoopPromise<Void>] = (0..<3).map { (_: Int) in el.makePromise() }
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: address, data: emptyBuffer), promise: ps[0])
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: address, data: emptyBuffer), promise: ps[1])
            pwm.markFlushCheckpoint()
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: address, data: emptyBuffer), promise: ps[2])

            var result = try assertExpectedWritability(pendingWritesManager: pwm,
                                                       promises: ps,
                                                       expectedSingleWritabilities: nil,
                                                       expectedVectorWritabilities: [[(0, address), (0, address)]],
                                                       returns: [.success(.processed(2))],
                                                       promiseStates: [[true, true, false]])
            XCTAssertEqual(.writtenCompletely, result.writeResult)

            pwm.markFlushCheckpoint()

            result = try assertExpectedWritability(pendingWritesManager: pwm,
                                                   promises: ps,
                                                   expectedSingleWritabilities: [(0, address)],
                                                   expectedVectorWritabilities: nil,
                                                   returns: [.success(.processed(0))],
                                                   promiseStates: [[true, true, true]])
            XCTAssertEqual(.writtenCompletely, result.writeResult)
        }
    }

    func testPendingWritesCloseDuringVectorWrite() throws {
        let el = EmbeddedEventLoop()
        let alloc = ByteBufferAllocator()
        let address = try SocketAddress(ipAddress: "127.0.0.1", port: 80)
        var buffer = alloc.buffer(capacity: 12)
        buffer.writeString("1234")

        try withPendingDatagramWritesManager { pwm in
            let ps: [EventLoopPromise<Void>] = (0..<3).map { (_: Int) in el.makePromise() }
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: address, data: buffer), promise: ps[0])
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: address, data: buffer), promise: ps[1])
            pwm.markFlushCheckpoint()
            _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: address, data: buffer), promise: ps[2])

            ps[0].futureResult.whenComplete { (_: Result<Void, Error>) in
                pwm.failAll(error: ChannelError.inputClosed, close: true)
            }

            let result = try assertExpectedWritability(pendingWritesManager: pwm,
                                                       promises: ps,
                                                       expectedSingleWritabilities: nil,
                                                       expectedVectorWritabilities: [[(4, address), (4, address)]],
                                                       returns: [.success(.processed(1))],
                                                       promiseStates: [[true, true, true]])
            XCTAssertEqual(.writtenCompletely, result.writeResult)
            XCTAssertNoThrow(try ps[0].futureResult.wait())
            XCTAssertThrowsError(try ps[1].futureResult.wait())
            XCTAssertThrowsError(try ps[2].futureResult.wait())
        }
    }

    func testPendingWritesMoreThanWritevIOVectorLimit() throws {
        let el = EmbeddedEventLoop()
        let alloc = ByteBufferAllocator()
        let address = try SocketAddress(ipAddress: "127.0.0.1", port: 80)
        var buffer = alloc.buffer(capacity: 12)
        buffer.writeString("1234")

        try withPendingDatagramWritesManager { pwm in
            let ps: [EventLoopPromise<Void>] = (0...Socket.writevLimitIOVectors).map { (_: Int) in el.makePromise() }
            ps.forEach { p in
                _ = pwm.add(envelope: AddressedEnvelope(remoteAddress: address, data: buffer), promise: p)
            }
            pwm.markFlushCheckpoint()

            var result = try assertExpectedWritability(pendingWritesManager: pwm,
                                                       promises: ps,
                                                       expectedSingleWritabilities: [(4, address)],
                                                       expectedVectorWritabilities: [Array(repeating: (4, address), count: Socket.writevLimitIOVectors)],
                                                       returns: [.success(.processed(Socket.writevLimitIOVectors)), .success(.wouldBlock(0))],
                                                       promiseStates: [Array(repeating: true, count: Socket.writevLimitIOVectors) + [false],
                                                                       Array(repeating: true, count: Socket.writevLimitIOVectors) + [false]])
            XCTAssertEqual(.couldNotWriteEverything, result.writeResult)
            result = try assertExpectedWritability(pendingWritesManager: pwm,
                                                   promises: ps,
                                                   expectedSingleWritabilities: [(4, address)],
                                                   expectedVectorWritabilities: nil,
                                                   returns: [.success(.processed(4))],
                                                   promiseStates: [Array(repeating: true, count: Socket.writevLimitIOVectors + 1)])
            XCTAssertEqual(.writtenCompletely, result.writeResult)
        }
    }
}