File: AsyncChannelOutboundWriter.swift

package info (click to toggle)
swiftlang 6.1.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,791,532 kB
  • sloc: cpp: 9,901,743; ansic: 2,201,431; asm: 1,091,827; python: 308,252; objc: 82,166; f90: 80,126; lisp: 38,358; pascal: 25,559; sh: 20,429; ml: 5,058; perl: 4,745; makefile: 4,484; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (168 lines) | stat: -rw-r--r-- 6,084 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
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2022-2023 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
//
//===----------------------------------------------------------------------===//

/// A ``NIOAsyncChannelOutboundWriter`` is used to write and flush new outbound messages in a channel.
///
/// The writer acts as a bridge between the Concurrency and NIO world. It allows to write and flush messages into the
/// underlying ``Channel``. Furthermore, it respects back-pressure of the channel by suspending the calls to write until
/// the channel becomes writable again.
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
public struct NIOAsyncChannelOutboundWriter<OutboundOut: Sendable>: Sendable {
    @usableFromInline
    typealias _Writer = NIOAsyncChannelOutboundWriterHandler<OutboundOut>.Writer

    /// An `AsyncSequence` backing a ``NIOAsyncChannelOutboundWriter`` for testing purposes.
    public struct TestSink: AsyncSequence {
        public typealias Element = OutboundOut

        @usableFromInline
        internal let stream: AsyncStream<OutboundOut>

        @usableFromInline
        internal let continuation: AsyncStream<OutboundOut>.Continuation

        @inlinable
        init(
            stream: AsyncStream<OutboundOut>,
            continuation: AsyncStream<OutboundOut>.Continuation
        ) {
            self.stream = stream
            self.continuation = continuation
        }

        public func makeAsyncIterator() -> AsyncIterator {
            AsyncIterator(iterator: self.stream.makeAsyncIterator())
        }

        public struct AsyncIterator: AsyncIteratorProtocol {
            @usableFromInline
            internal var iterator: AsyncStream<OutboundOut>.AsyncIterator

            @inlinable
            init(iterator: AsyncStream<OutboundOut>.AsyncIterator) {
                self.iterator = iterator
            }

            public mutating func next() async -> Element? {
                await self.iterator.next()
            }
        }
    }

    @usableFromInline
    enum Backing: Sendable {
        case asyncStream(AsyncStream<OutboundOut>.Continuation)
        case writer(_Writer)
    }

    @usableFromInline
    internal let _backing: Backing

    /// Creates a new ``NIOAsyncChannelOutboundWriter`` backed by a ``NIOAsyncChannelOutboundWriter/TestSink``.
    /// This is mostly useful for testing purposes where one wants to observe the written data.
    @inlinable
    public static func makeTestingWriter() -> (Self, TestSink) {
        var continuation: AsyncStream<OutboundOut>.Continuation!
        let asyncStream = AsyncStream<OutboundOut> { continuation = $0 }
        let writer = Self(continuation: continuation)
        let sink = TestSink(stream: asyncStream, continuation: continuation)

        return (writer, sink)
    }

    @inlinable
    init(
        channel: Channel,
        isOutboundHalfClosureEnabled: Bool,
        closeOnDeinit: Bool
    ) throws {
        let handler = NIOAsyncChannelOutboundWriterHandler<OutboundOut>(
            eventLoop: channel.eventLoop,
            isOutboundHalfClosureEnabled: isOutboundHalfClosureEnabled
        )
        let writer = _Writer.makeWriter(
            elementType: OutboundOut.self,
            isWritable: true,
            finishOnDeinit: closeOnDeinit,
            delegate: .init(handler: handler)
        )

        handler.sink = writer.sink
        handler.writer = writer.writer

        try channel.pipeline.syncOperations.addHandler(handler)

        self._backing = .writer(writer.writer)
    }

    @inlinable
    init(continuation: AsyncStream<OutboundOut>.Continuation) {
        self._backing = .asyncStream(continuation)
    }

    /// Send a write into the ``ChannelPipeline`` and flush it right away.
    ///
    /// This method suspends if the underlying channel is not writable and will resume once the it becomes writable again.
    @inlinable
    public func write(_ data: OutboundOut) async throws {
        switch self._backing {
        case .asyncStream(let continuation):
            continuation.yield(data)
        case .writer(let writer):
            try await writer.yield(data)
        }
    }

    /// Send a sequence of writes into the ``ChannelPipeline`` and flush them right away.
    ///
    /// This method suspends if the underlying channel is not writable and will resume once the it becomes writable again.
    @inlinable
    public func write<Writes: Sequence>(contentsOf sequence: Writes) async throws where Writes.Element == OutboundOut {
        switch self._backing {
        case .asyncStream(let continuation):
            for data in sequence {
                continuation.yield(data)
            }
        case .writer(let writer):
            try await writer.yield(contentsOf: sequence)
        }
    }

    /// Send an asynchronous sequence of writes into the ``ChannelPipeline``.
    ///
    /// This will flush after every write.
    ///
    /// This method suspends if the underlying channel is not writable and will resume once the it becomes writable again.
    @inlinable
    public func write<Writes: AsyncSequence>(contentsOf sequence: Writes) async throws where Writes.Element == OutboundOut {
        for try await data in sequence {
            try await self.write(data)
        }
    }

    /// Finishes the writer.
    ///
    /// This might trigger a half closure if the ``NIOAsyncChannel`` was configured to support it.
    public func finish() {
        switch self._backing {
        case .asyncStream(let continuation):
            continuation.finish()
        case .writer(let writer):
            writer.finish()
        }
    }
}

@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension NIOAsyncChannelOutboundWriter.TestSink: Sendable {}