File: NIOTypedHTTPClientUpgraderStateMachine.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 (335 lines) | stat: -rw-r--r-- 12,141 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
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 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
//
//===----------------------------------------------------------------------===//
#if !canImport(Darwin) || swift(>=5.10)
import DequeModule
import NIOCore

@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)
struct NIOTypedHTTPClientUpgraderStateMachine<UpgradeResult> {
    @usableFromInline
    enum State {
        /// The state before we received a TLSUserEvent. We are just forwarding any read at this point.
        case initial(upgraders: [any NIOTypedHTTPClientProtocolUpgrader<UpgradeResult>])

        /// The request has been sent. We are waiting for the upgrade response.
        case awaitingUpgradeResponseHead(upgraders: [any NIOTypedHTTPClientProtocolUpgrader<UpgradeResult>])

        @usableFromInline
        struct AwaitingUpgradeResponseEnd {
            var upgrader: any NIOTypedHTTPClientProtocolUpgrader<UpgradeResult>
            var responseHead: HTTPResponseHead
        }
        /// We received the response head and are just waiting for the response end.
        case awaitingUpgradeResponseEnd(AwaitingUpgradeResponseEnd)

        @usableFromInline
        struct Upgrading {
            var buffer: Deque<NIOAny>
        }
        /// We are either running the upgrading handler.
        case upgrading(Upgrading)

        @usableFromInline
        struct Unbuffering {
            var buffer: Deque<NIOAny>
        }
        case unbuffering(Unbuffering)

        case finished

        case modifying
    }

    private var state: State

    init(upgraders: [any NIOTypedHTTPClientProtocolUpgrader<UpgradeResult>]) {
        self.state = .initial(upgraders: upgraders)
    }

    @usableFromInline
    enum HandlerRemovedAction {
        case failUpgradePromise
    }

    @inlinable
    mutating func handlerRemoved() -> HandlerRemovedAction? {
        switch self.state {
        case .initial, .awaitingUpgradeResponseHead, .awaitingUpgradeResponseEnd, .upgrading, .unbuffering:
            self.state = .finished
            return .failUpgradePromise

        case .finished:
            return .none

        case .modifying:
            fatalError("Internal inconsistency in HTTPClientUpgradeStateMachine")
        }
    }

    @usableFromInline
    enum ChannelActiveAction {
        case writeUpgradeRequest
    }

    @inlinable
    mutating func channelActive() -> ChannelActiveAction? {
        switch self.state {
        case .initial(let upgraders):
            self.state = .awaitingUpgradeResponseHead(upgraders: upgraders)
            return .writeUpgradeRequest

        case .finished:
            return nil

        case .awaitingUpgradeResponseHead, .awaitingUpgradeResponseEnd, .unbuffering, .upgrading:
            fatalError("Internal inconsistency in HTTPClientUpgradeStateMachine")

        case .modifying:
            fatalError("Internal inconsistency in HTTPClientUpgradeStateMachine")
        }
    }

    @usableFromInline
    enum WriteAction {
        case failWrite(Error)
        case forwardWrite
    }

    @usableFromInline
    func write() -> WriteAction {
        switch self.state {
        case .initial, .awaitingUpgradeResponseHead, .awaitingUpgradeResponseEnd, .upgrading:
            return .failWrite(NIOHTTPClientUpgradeError.writingToHandlerDuringUpgrade)

        case .unbuffering, .finished:
            return .forwardWrite
            
        case .modifying:
            fatalError("Internal inconsistency in HTTPClientUpgradeStateMachine")
        }
    }

    @usableFromInline
    enum ChannelReadDataAction {
        case unwrapData
        case fireChannelRead
    }

    @inlinable
    mutating func channelReadData(_ data: NIOAny) -> ChannelReadDataAction? {
        switch self.state {
        case .initial:
            return .unwrapData

        case .awaitingUpgradeResponseHead, .awaitingUpgradeResponseEnd:
            return .unwrapData

        case .upgrading(var upgrading):
            // We got a read while running upgrading.
            // We have to buffer the read to unbuffer it afterwards
            self.state = .modifying
            upgrading.buffer.append(data)
            self.state = .upgrading(upgrading)
            return nil

        case .unbuffering(var unbuffering):
            self.state = .modifying
            unbuffering.buffer.append(data)
            self.state = .unbuffering(unbuffering)
            return nil

        case .finished:
            return .fireChannelRead

        case .modifying:
            fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine")
        }
    }


    @usableFromInline
    enum ChannelReadResponsePartAction {
        case fireErrorCaughtAndRemoveHandler(Error)
        case runNotUpgradingInitializer
        case startUpgrading(
            upgrader: any NIOTypedHTTPClientProtocolUpgrader<UpgradeResult>,
            responseHeaders: HTTPResponseHead
        )
    }

    @inlinable
    mutating func channelReadResponsePart(_ responsePart: HTTPClientResponsePart) -> ChannelReadResponsePartAction? {
        switch self.state {
        case .initial:
            fatalError("Internal inconsistency in HTTPClientUpgradeStateMachine")

        case .awaitingUpgradeResponseHead(let upgraders):
            // We should decide if we can upgrade based on the first response header: if we aren't upgrading,
            // by the time the body comes in we should be out of the pipeline. That means that if we don't think we're
            // upgrading, the only thing we should see is a response head. Anything else in an error.
            guard case .head(let response) = responsePart else {
                self.state = .finished
                return .fireErrorCaughtAndRemoveHandler(NIOHTTPClientUpgradeError.invalidHTTPOrdering)
            }

            // Assess whether the server has accepted our upgrade request.
            guard case .switchingProtocols = response.status else {
                var buffer = Deque<NIOAny>()
                buffer.append(.init(responsePart))
                self.state = .upgrading(.init(buffer: buffer))
                return .runNotUpgradingInitializer
            }

            // Ok, we have a HTTP response. Check if it's an upgrade confirmation.
            // If it's not, we want to pass it on and remove ourselves from the channel pipeline.
            let acceptedProtocols = response.headers[canonicalForm: "upgrade"]

            // At the moment we only upgrade to the first protocol returned from the server.
            guard let protocolName = acceptedProtocols.first?.lowercased() else {
                // There are no upgrade protocols returned.
                self.state = .finished
                return .fireErrorCaughtAndRemoveHandler(NIOHTTPClientUpgradeError.responseProtocolNotFound)
            }

            let matchingUpgrader = upgraders
                .first(where: { $0.supportedProtocol.lowercased() == protocolName })

            guard let upgrader = matchingUpgrader else {
                // There is no upgrader for this protocol.
                self.state = .finished
                return .fireErrorCaughtAndRemoveHandler(NIOHTTPClientUpgradeError.responseProtocolNotFound)
            }

            guard upgrader.shouldAllowUpgrade(upgradeResponse: response) else {
                // The upgrader says no.
                self.state = .finished
                return .fireErrorCaughtAndRemoveHandler(NIOHTTPClientUpgradeError.upgraderDeniedUpgrade)
            }

            // We received the response head and decided that we can upgrade.
            // We now need to wait for the response end and then we can perform the upgrade
            self.state = .awaitingUpgradeResponseEnd(.init(
                upgrader: upgrader,
                responseHead: response
            ))
            return .none

        case .awaitingUpgradeResponseEnd(let awaitingUpgradeResponseEnd):
            switch responsePart {
            case .head:
                // We got two HTTP response heads.
                self.state = .finished
                return .fireErrorCaughtAndRemoveHandler(NIOHTTPClientUpgradeError.invalidHTTPOrdering)

            case .body:
                // We tolerate body parts to be send but just ignore them
                return .none

            case .end:
                // We got the response end and can now run the upgrader.
                self.state = .upgrading(.init(buffer: .init()))
                return .startUpgrading(
                    upgrader: awaitingUpgradeResponseEnd.upgrader,
                    responseHeaders: awaitingUpgradeResponseEnd.responseHead
                )
            }

        case .upgrading, .unbuffering, .finished:
            fatalError("Internal inconsistency in HTTPClientUpgradeStateMachine")


        case .modifying:
            fatalError("Internal inconsistency in HTTPClientUpgradeStateMachine")
        }
    }

    @usableFromInline
    enum UpgradingHandlerCompletedAction {
        case fireErrorCaughtAndStartUnbuffering(Error)
        case removeHandler(UpgradeResult)
        case fireErrorCaughtAndRemoveHandler(Error)
        case startUnbuffering(UpgradeResult)
    }

    @inlinable
    mutating func upgradingHandlerCompleted(_ result: Result<UpgradeResult, Error>) -> UpgradingHandlerCompletedAction? {
        switch self.state {
        case .initial, .awaitingUpgradeResponseHead, .awaitingUpgradeResponseEnd, .unbuffering:
            fatalError("Internal inconsistency in HTTPClientUpgradeStateMachine")

        case .upgrading(let upgrading):
            switch result {
            case .success(let value):
                if !upgrading.buffer.isEmpty {
                    self.state = .unbuffering(.init(buffer: upgrading.buffer))
                    return .startUnbuffering(value)
                } else {
                    self.state = .finished
                    return .removeHandler(value)
                }

            case .failure(let error):
                if !upgrading.buffer.isEmpty {
                    // So we failed to upgrade. There is nothing really that we can do here.
                    // We are unbuffering the reads but there shouldn't be any handler in the pipeline
                    // that expects a specific type of reads anyhow.
                    self.state = .unbuffering(.init(buffer: upgrading.buffer))
                    return .fireErrorCaughtAndStartUnbuffering(error)
                } else {
                    self.state = .finished
                    return .fireErrorCaughtAndRemoveHandler(error)
                }
            }

        case .finished:
            // We have to tolerate this
            return nil

        case .modifying:
            fatalError("Internal inconsistency in HTTPClientUpgradeStateMachine")
        }
    }

    @usableFromInline
    enum UnbufferAction {
        case fireChannelRead(NIOAny)
        case fireChannelReadCompleteAndRemoveHandler
    }

    @inlinable
    mutating func unbuffer() -> UnbufferAction {
        switch self.state {
        case .initial, .awaitingUpgradeResponseHead, .awaitingUpgradeResponseEnd, .upgrading, .finished:
            preconditionFailure("Invalid state \(self.state)")

        case .unbuffering(var unbuffering):
            self.state = .modifying

            if let element = unbuffering.buffer.popFirst() {
                self.state = .unbuffering(unbuffering)

                return .fireChannelRead(element)
            } else {
                self.state = .finished

                return .fireChannelReadCompleteAndRemoveHandler
            }

        case .modifying:
            fatalError("Internal inconsistency in HTTPClientUpgradeStateMachine")

        }
    }
}
#endif