forked from swift-server/async-http-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHTTP1ConnectionStateMachine.swift
436 lines (369 loc) · 15.3 KB
/
HTTP1ConnectionStateMachine.swift
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the AsyncHTTPClient open source project
//
// Copyright (c) 2021 Apple Inc. and the AsyncHTTPClient project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AsyncHTTPClient project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIOCore
import NIOHTTP1
struct HTTP1ConnectionStateMachine {
fileprivate enum State {
case initialized
case idle
case inRequest(HTTPRequestStateMachine, close: Bool)
case closing
case closed
case modifying
}
enum Action {
/// A action to execute, when we consider a request "done".
enum FinalStreamAction {
/// Close the connection
case close
/// If the server has replied, with a status of 200...300 before all data was sent, a request is considered succeeded,
/// as soon as we wrote the request end onto the wire.
case sendRequestEnd
/// Inform an observer that the connection has become idle
case informConnectionIsIdle
/// Do nothing.
case none
}
case sendRequestHead(HTTPRequestHead, startBody: Bool)
case sendBodyPart(IOData)
case sendRequestEnd
case pauseRequestBodyStream
case resumeRequestBodyStream
case forwardResponseHead(HTTPResponseHead, pauseRequestBodyStream: Bool)
case forwardResponseBodyParts(CircularBuffer<ByteBuffer>)
case failRequest(Error, FinalStreamAction)
case succeedRequest(FinalStreamAction, CircularBuffer<ByteBuffer>)
case read
case close
case wait
case fireChannelActive
case fireChannelInactive
case fireChannelError(Error, closeConnection: Bool)
}
private var state: State
private var isChannelWritable: Bool = true
init() {
self.state = .initialized
}
mutating func channelActive(isWritable: Bool) -> Action {
switch self.state {
case .initialized:
self.isChannelWritable = isWritable
self.state = .idle
return .fireChannelActive
case .idle, .inRequest, .closing, .closed:
// Since NIO triggers promise before pipeline, the handler might have been added to the
// pipeline, before the channelActive callback was triggered. For this reason, we might
// get the channelActive call twice
return .wait
case .modifying:
preconditionFailure("Invalid state: \(self.state)")
}
}
mutating func channelInactive() -> Action {
switch self.state {
case .initialized:
preconditionFailure("A channel that isn't active, must not become inactive")
case .inRequest(var requestStateMachine, close: _):
return self.avoidingStateMachineCoW { state -> Action in
let action = requestStateMachine.channelInactive()
state = .closed
return state.modify(with: action)
}
case .idle, .closing:
self.state = .closed
return .fireChannelInactive
case .closed:
return .wait
case .modifying:
preconditionFailure("Invalid state: \(self.state)")
}
}
mutating func errorHappened(_ error: Error) -> Action {
switch self.state {
case .initialized:
self.state = .closed
return .fireChannelError(error, closeConnection: false)
case .inRequest(var requestStateMachine, close: _):
return self.avoidingStateMachineCoW { state -> Action in
let action = requestStateMachine.errorHappened(error)
state = .closed
return state.modify(with: action)
}
case .idle:
self.state = .closing
return .fireChannelError(error, closeConnection: true)
case .closing, .closed:
return .fireChannelError(error, closeConnection: false)
case .modifying:
preconditionFailure("Invalid state: \(self.state)")
}
}
mutating func writabilityChanged(writable: Bool) -> Action {
self.isChannelWritable = writable
switch self.state {
case .initialized, .idle, .closing, .closed:
return .wait
case .inRequest(var requestStateMachine, let close):
return self.avoidingStateMachineCoW { state -> Action in
let action = requestStateMachine.writabilityChanged(writable: writable)
state = .inRequest(requestStateMachine, close: close)
return state.modify(with: action)
}
case .modifying:
preconditionFailure("Invalid state: \(self.state)")
}
}
mutating func runNewRequest(head: HTTPRequestHead, metadata: RequestFramingMetadata) -> Action {
guard case .idle = self.state else {
preconditionFailure("Invalid state")
}
var requestStateMachine = HTTPRequestStateMachine(
isChannelWritable: self.isChannelWritable
)
let action = requestStateMachine.startRequest(head: head, metadata: metadata)
// by default we assume a persistent connection. however in `requestVerified`, we read the
// "connection" header.
self.state = .inRequest(requestStateMachine, close: metadata.connectionClose)
return self.state.modify(with: action)
}
mutating func requestStreamPartReceived(_ part: IOData) -> Action {
guard case .inRequest(var requestStateMachine, let close) = self.state else {
preconditionFailure("Invalid state")
}
return self.avoidingStateMachineCoW { state -> Action in
let action = requestStateMachine.requestStreamPartReceived(part)
state = .inRequest(requestStateMachine, close: close)
return state.modify(with: action)
}
}
mutating func requestStreamFinished() -> Action {
guard case .inRequest(var requestStateMachine, let close) = self.state else {
preconditionFailure("Invalid state")
}
return self.avoidingStateMachineCoW { state -> Action in
let action = requestStateMachine.requestStreamFinished()
state = .inRequest(requestStateMachine, close: close)
return state.modify(with: action)
}
}
mutating func requestCancelled(closeConnection: Bool) -> Action {
switch self.state {
case .initialized:
preconditionFailure("This event must only happen, if the connection is leased. During startup this is impossible")
case .idle:
if closeConnection {
self.state = .closing
return .close
} else {
return .wait
}
case .inRequest(var requestStateMachine, close: let close):
return self.avoidingStateMachineCoW { state -> Action in
let action = requestStateMachine.requestCancelled()
state = .inRequest(requestStateMachine, close: close || closeConnection)
return state.modify(with: action)
}
case .closing, .closed:
return .wait
case .modifying:
preconditionFailure("Invalid state: \(self.state)")
}
}
// MARK: - Response
mutating func read() -> Action {
switch self.state {
case .initialized:
preconditionFailure("Why should we read something, if we are not connected yet")
case .idle:
return .read
case .inRequest(var requestStateMachine, let close):
return self.avoidingStateMachineCoW { state -> Action in
let action = requestStateMachine.read()
state = .inRequest(requestStateMachine, close: close)
return state.modify(with: action)
}
case .closing, .closed:
// there might be a race in us closing the connection and receiving another read event
return .read
case .modifying:
preconditionFailure("Invalid state: \(self.state)")
}
}
mutating func channelRead(_ part: HTTPClientResponsePart) -> Action {
switch self.state {
case .initialized, .idle:
preconditionFailure("Invalid state")
case .inRequest(var requestStateMachine, var close):
return self.avoidingStateMachineCoW { state -> Action in
let action = requestStateMachine.channelRead(part)
if case .head(let head) = part, close == false {
close = head.headers[canonicalForm: "connection"].contains(where: { $0.lowercased() == "close" })
}
state = .inRequest(requestStateMachine, close: close)
return state.modify(with: action)
}
case .closing, .closed:
return .wait
case .modifying:
preconditionFailure("Invalid state: \(self.state)")
}
}
mutating func channelReadComplete() -> Action {
switch self.state {
case .initialized, .idle, .closing, .closed:
return .wait
case .inRequest(var requestStateMachine, let close):
return self.avoidingStateMachineCoW { state -> Action in
let action = requestStateMachine.channelReadComplete()
state = .inRequest(requestStateMachine, close: close)
return state.modify(with: action)
}
case .modifying:
preconditionFailure("Invalid state: \(self.state)")
}
}
mutating func demandMoreResponseBodyParts() -> Action {
guard case .inRequest(var requestStateMachine, let close) = self.state else {
preconditionFailure("Invalid state: \(self.state)")
}
return self.avoidingStateMachineCoW { state -> Action in
let action = requestStateMachine.demandMoreResponseBodyParts()
state = .inRequest(requestStateMachine, close: close)
return state.modify(with: action)
}
}
mutating func idleReadTimeoutTriggered() -> Action {
guard case .inRequest(var requestStateMachine, let close) = self.state else {
preconditionFailure("Invalid state: \(self.state)")
}
return self.avoidingStateMachineCoW { state -> Action in
let action = requestStateMachine.idleReadTimeoutTriggered()
state = .inRequest(requestStateMachine, close: close)
return state.modify(with: action)
}
}
}
extension HTTP1ConnectionStateMachine {
/// So, uh...this function needs some explaining.
///
/// While the state machine logic above is great, there is a downside to having all of the state machine data in
/// associated data on enumerations: any modification of that data will trigger copy on write for heap-allocated
/// data. That means that for _every operation on the state machine_ we will CoW our underlying state, which is
/// not good.
///
/// The way we can avoid this is by using this helper function. It will temporarily set state to a value with no
/// associated data, before attempting the body of the function. It will also verify that the state machine never
/// remains in this bad state.
///
/// A key note here is that all callers must ensure that they return to a good state before they exit.
///
/// Sadly, because it's generic and has a closure, we need to force it to be inlined at all call sites, which is
/// not ideal.
@inline(__always)
private mutating func avoidingStateMachineCoW<ReturnType>(_ body: (inout State) -> ReturnType) -> ReturnType {
self.state = .modifying
defer {
assert(!self.isModifying)
}
return body(&self.state)
}
private var isModifying: Bool {
if case .modifying = self.state {
return true
} else {
return false
}
}
}
extension HTTP1ConnectionStateMachine.State {
fileprivate mutating func modify(with action: HTTPRequestStateMachine.Action) -> HTTP1ConnectionStateMachine.Action {
switch action {
case .sendRequestHead(let head, let startBody):
return .sendRequestHead(head, startBody: startBody)
case .pauseRequestBodyStream:
return .pauseRequestBodyStream
case .resumeRequestBodyStream:
return .resumeRequestBodyStream
case .sendBodyPart(let part):
return .sendBodyPart(part)
case .sendRequestEnd:
return .sendRequestEnd
case .forwardResponseHead(let head, let pauseRequestBodyStream):
return .forwardResponseHead(head, pauseRequestBodyStream: pauseRequestBodyStream)
case .forwardResponseBodyParts(let parts):
return .forwardResponseBodyParts(parts)
case .succeedRequest(let finalAction, let finalParts):
guard case .inRequest(_, close: let close) = self else {
preconditionFailure("Invalid state")
}
let newFinalAction: HTTP1ConnectionStateMachine.Action.FinalStreamAction
switch finalAction {
case .close:
self = .closing
newFinalAction = .close
case .sendRequestEnd:
newFinalAction = .sendRequestEnd
case .none:
self = .idle
newFinalAction = close ? .close : .informConnectionIsIdle
}
return .succeedRequest(newFinalAction, finalParts)
case .failRequest(let error, let finalAction):
switch self {
case .initialized:
preconditionFailure("Invalid state")
case .idle:
preconditionFailure("How can we fail a task, if we are idle")
case .inRequest(_, close: let close):
if close || finalAction == .close {
self = .closing
return .failRequest(error, .close)
} else {
self = .idle
return .failRequest(error, .informConnectionIsIdle)
}
case .closing:
return .failRequest(error, .none)
case .closed:
// this state can be reached, if the connection was unexpectedly closed by remote
return .failRequest(error, .none)
case .modifying:
preconditionFailure("Invalid state: \(self)")
}
case .read:
return .read
case .wait:
return .wait
}
}
}
extension HTTP1ConnectionStateMachine: CustomStringConvertible {
var description: String {
switch self.state {
case .initialized:
return ".initialized"
case .idle:
return ".idle"
case .inRequest(let request, close: let close):
return ".inRequest(\(request), closeAfterRequest: \(close))"
case .closing:
return ".closing"
case .closed:
return ".closed"
case .modifying:
preconditionFailure(".modifying")
}
}
}