forked from apple/swift-nio-http2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerConnectionManagementHandler+StateMachine.swift
More file actions
292 lines (244 loc) · 10.3 KB
/
ServerConnectionManagementHandler+StateMachine.swift
File metadata and controls
292 lines (244 loc) · 10.3 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
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2026 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
//
//===----------------------------------------------------------------------===//
/*
* Copyright 2024, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import NIOCore
extension NIOHTTP2ServerConnectionManagementHandler {
/// Tracks the state of TCP connections at the server.
///
/// The state machine manages the state for the graceful shutdown procedure.
struct StateMachine {
/// Current state.
private var state: State
/// Opaque data sent to the client in a PING frame after emitting the first GOAWAY frame
/// as part of graceful shutdown.
private let goAwayPingData: HTTP2PingData
/// Whether the connection is currently closing.
var isClosing: Bool {
self.state.isClosing
}
/// Create a new state machine.
///
/// - Parameters:
/// - goAwayPingData: Opaque data sent to the client in a PING frame when the server
/// initiates graceful shutdown.
init(goAwayPingData: HTTP2PingData = HTTP2PingData(withInteger: .random(in: .min ... .max))) {
self.state = .active(State.Active())
self.goAwayPingData = goAwayPingData
}
/// Record that the stream with the given ID has been opened.
mutating func streamOpened(_ id: HTTP2StreamID) {
switch self.state {
case .active(var state):
self.state = ._modifying
state.lastStreamID = id
let (inserted, _) = state.openStreams.insert(id)
assert(inserted, "Can't open stream \(Int(id)), it's already open")
self.state = .active(state)
case .closing(var state):
self.state = ._modifying
state.lastStreamID = id
let (inserted, _) = state.openStreams.insert(id)
assert(inserted, "Can't open stream \(Int(id)), it's already open")
self.state = .closing(state)
case .closed:
()
case ._modifying:
preconditionFailure()
}
}
enum OnStreamClosed: Equatable {
/// Start the idle timer, after which the connection should be closed gracefully.
case startIdleTimer
/// Close the connection.
case close
/// Do nothing.
case none
}
/// Record that the stream with the given ID has been closed.
mutating func streamClosed(_ id: HTTP2StreamID) -> OnStreamClosed {
let onStreamClosed: OnStreamClosed
switch self.state {
case .active(var state):
self.state = ._modifying
let removedID = state.openStreams.remove(id)
assert(removedID != nil, "Can't close stream \(Int(id)), it wasn't open")
onStreamClosed = state.openStreams.isEmpty ? .startIdleTimer : .none
self.state = .active(state)
case .closing(var state):
self.state = ._modifying
let removedID = state.openStreams.remove(id)
assert(removedID != nil, "Can't close stream \(Int(id)), it wasn't open")
// If the second GOAWAY hasn't been sent it isn't safe to close if there are no open
// streams: the client may have opened a stream which the server doesn't know about yet.
let canClose = state.sentSecondGoAway && state.openStreams.isEmpty
onStreamClosed = canClose ? .close : .none
self.state = .closing(state)
case .closed:
onStreamClosed = .none
case ._modifying:
preconditionFailure()
}
return onStreamClosed
}
enum OnPing: Equatable {
/// Send a GOAWAY frame with the code "enhance your calm" and immediately close the connection.
case enhanceYourCalmThenClose(HTTP2StreamID)
/// Acknowledge the ping.
case sendAck
/// Ignore the ping.
case none
}
/// Received a ping with the given data.
///
/// - Parameters:
/// - time: The time at which the ping was received.
/// - data: The data sent with the ping.
mutating func receivedPing(atTime time: NIODeadline, data: HTTP2PingData) -> OnPing {
let onPing: OnPing
switch self.state {
case .active(let state):
self.state = ._modifying
onPing = .sendAck
self.state = .active(state)
case .closing(let state):
self.state = ._modifying
onPing = .sendAck
self.state = .closing(state)
case .closed:
onPing = .none
case ._modifying:
preconditionFailure()
}
return onPing
}
enum OnPingAck: Equatable {
/// Send a GOAWAY frame with no error and the given last stream ID, optionally closing the
/// connection immediately afterwards.
case sendGoAway(lastStreamID: HTTP2StreamID, close: Bool)
/// Ignore the ack.
case none
}
/// Received a PING frame with the 'ack' flag set.
mutating func receivedPingAck(data: HTTP2PingData) -> OnPingAck {
let onPingAck: OnPingAck
switch self.state {
case .closing(var state):
self.state = ._modifying
// If only one GOAWAY has been sent and the data matches the data from the GOAWAY ping then
// the server should send another GOAWAY ratcheting down the last stream ID. If no streams
// are open then the server can close the connection immediately after, otherwise it must
// wait until all streams are closed.
if !state.sentSecondGoAway, data == self.goAwayPingData {
state.sentSecondGoAway = true
if state.openStreams.isEmpty {
self.state = .closed
onPingAck = .sendGoAway(lastStreamID: state.lastStreamID, close: true)
} else {
self.state = .closing(state)
onPingAck = .sendGoAway(lastStreamID: state.lastStreamID, close: false)
}
} else {
onPingAck = .none
}
self.state = .closing(state)
case .active, .closed:
onPingAck = .none
case ._modifying:
preconditionFailure()
}
return onPingAck
}
enum OnStartGracefulShutdown: Equatable {
/// Initiate graceful shutdown by sending a GOAWAY frame with the last stream ID set as the max
/// stream ID and no error. Follow it immediately with a PING frame with the given data.
case sendGoAwayAndPing(HTTP2PingData)
/// Ignore the request to start graceful shutdown.
case none
}
/// Request that the connection begins graceful shutdown.
mutating func startGracefulShutdown() -> OnStartGracefulShutdown {
let onStartGracefulShutdown: OnStartGracefulShutdown
switch self.state {
case .active(let state):
self.state = .closing(State.Closing(from: state))
onStartGracefulShutdown = .sendGoAwayAndPing(self.goAwayPingData)
case .closing, .closed:
onStartGracefulShutdown = .none
case ._modifying:
preconditionFailure()
}
return onStartGracefulShutdown
}
/// Marks the state as closed.
mutating func markClosed() {
self.state = .closed
}
}
}
extension NIOHTTP2ServerConnectionManagementHandler.StateMachine {
fileprivate enum State {
/// The connection is active.
struct Active {
/// The number of open streams.
var openStreams: Set<HTTP2StreamID>
/// The ID of the most recently opened stream (zero indicates no streams have been opened yet).
var lastStreamID: HTTP2StreamID
init() {
self.openStreams = []
self.lastStreamID = .rootStream
}
}
/// The connection is closing gracefully, an initial GOAWAY frame has been sent (with the
/// last stream ID set to max).
struct Closing {
/// The number of open streams.
var openStreams: Set<HTTP2StreamID>
/// The ID of the most recently opened stream (zero indicates no streams have been opened yet).
var lastStreamID: HTTP2StreamID
/// Whether the second GOAWAY frame has been sent with a lower stream ID.
var sentSecondGoAway: Bool
init(from state: Active) {
self.openStreams = state.openStreams
self.lastStreamID = state.lastStreamID
self.sentSecondGoAway = false
}
}
case active(Active)
case closing(Closing)
case closed
case _modifying
var isClosing: Bool {
switch self {
case .closing:
return true
case .active, .closed, ._modifying:
return false
}
}
}
}