forked from grpc/grpc-swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHTTP2ToRawGRPCStateMachine.swift
1309 lines (1119 loc) · 42.6 KB
/
HTTP2ToRawGRPCStateMachine.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
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2020, 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 Logging
import NIOCore
import NIOHPACK
import NIOHTTP2
struct HTTP2ToRawGRPCStateMachine {
/// The current state.
private var state: State = .requestIdleResponseIdle
/// Temporarily sets `self.state` to `._modifying` before calling the provided block and setting
/// `self.state` to the `State` modified by the block.
///
/// Since we hold state as associated data on our `State` enum, any modification to that state
/// will trigger a copy on write for its heap allocated data. Temporarily setting the `self.state`
/// to `._modifying` allows us to avoid an extra reference to any heap allocated data and
/// therefore avoid a copy on write.
@inlinable
internal mutating func withStateAvoidingCoWs<Action>(_ body: (inout State) -> Action) -> Action {
var state: State = ._modifying
swap(&self.state, &state)
defer {
swap(&self.state, &state)
}
return body(&state)
}
}
extension HTTP2ToRawGRPCStateMachine {
enum State {
// Both peers are idle. Nothing has happened to the stream.
case requestIdleResponseIdle
// Received valid headers. Nothing has been sent in response.
case requestOpenResponseIdle(RequestOpenResponseIdleState)
// Received valid headers and request(s). Response headers have been sent.
case requestOpenResponseOpen(RequestOpenResponseOpenState)
// Received valid headers and request(s) but not end of the request stream. Response stream has
// been closed.
case requestOpenResponseClosed
// The request stream is closed. Nothing has been sent in response.
case requestClosedResponseIdle(RequestClosedResponseIdleState)
// The request stream is closed. Response headers have been sent.
case requestClosedResponseOpen(RequestClosedResponseOpenState)
// Both streams are closed. This state is terminal.
case requestClosedResponseClosed
// Not a real state. See 'withStateAvoidingCoWs'.
case _modifying
}
struct RequestOpenResponseIdleState {
/// A length prefixed message reader for request messages.
var reader: LengthPrefixedMessageReader
/// A length prefixed message writer for response messages.
var writer: LengthPrefixedMessageWriter
/// The content type of the RPC.
var contentType: ContentType
/// An accept encoding header to send in the response headers indicating the message encoding
/// that the server supports.
var acceptEncoding: String?
/// A message encoding header to send in the response headers indicating the encoding which will
/// be used for responses.
var responseEncoding: String?
/// Whether to normalize user-provided metadata.
var normalizeHeaders: Bool
/// The pipeline configuration state.
var configurationState: ConfigurationState
}
struct RequestClosedResponseIdleState {
/// A length prefixed message reader for request messages.
var reader: LengthPrefixedMessageReader
/// A length prefixed message writer for response messages.
var writer: LengthPrefixedMessageWriter
/// The content type of the RPC.
var contentType: ContentType
/// An accept encoding header to send in the response headers indicating the message encoding
/// that the server supports.
var acceptEncoding: String?
/// A message encoding header to send in the response headers indicating the encoding which will
/// be used for responses.
var responseEncoding: String?
/// Whether to normalize user-provided metadata.
var normalizeHeaders: Bool
/// The pipeline configuration state.
var configurationState: ConfigurationState
init(from state: RequestOpenResponseIdleState) {
self.reader = state.reader
self.writer = state.writer
self.contentType = state.contentType
self.acceptEncoding = state.acceptEncoding
self.responseEncoding = state.responseEncoding
self.normalizeHeaders = state.normalizeHeaders
self.configurationState = state.configurationState
}
}
struct RequestOpenResponseOpenState {
/// A length prefixed message reader for request messages.
var reader: LengthPrefixedMessageReader
/// A length prefixed message writer for response messages.
var writer: LengthPrefixedMessageWriter
/// Whether to normalize user-provided metadata.
var normalizeHeaders: Bool
init(from state: RequestOpenResponseIdleState) {
self.reader = state.reader
self.writer = state.writer
self.normalizeHeaders = state.normalizeHeaders
}
}
struct RequestClosedResponseOpenState {
/// A length prefixed message reader for request messages.
var reader: LengthPrefixedMessageReader
/// A length prefixed message writer for response messages.
var writer: LengthPrefixedMessageWriter
/// Whether to normalize user-provided metadata.
var normalizeHeaders: Bool
init(from state: RequestOpenResponseOpenState) {
self.reader = state.reader
self.writer = state.writer
self.normalizeHeaders = state.normalizeHeaders
}
init(from state: RequestClosedResponseIdleState) {
self.reader = state.reader
self.writer = state.writer
self.normalizeHeaders = state.normalizeHeaders
}
}
/// The pipeline configuration state.
enum ConfigurationState {
/// The pipeline is being configured. Any message data will be buffered into an appropriate
/// message reader.
case configuring(HPACKHeaders)
/// The pipeline is configured.
case configured
/// Returns true if the configuration is in the `.configured` state.
var isConfigured: Bool {
switch self {
case .configuring:
return false
case .configured:
return true
}
}
/// Configuration has completed.
mutating func configured() -> HPACKHeaders {
switch self {
case .configured:
preconditionFailure("Invalid state: already configured")
case let .configuring(headers):
self = .configured
return headers
}
}
}
}
extension HTTP2ToRawGRPCStateMachine {
enum PipelineConfiguredAction {
/// Forward the given headers.
case forwardHeaders(HPACKHeaders)
/// Forward the given headers and try reading the next message.
case forwardHeadersAndRead(HPACKHeaders)
}
enum ReceiveHeadersAction {
/// Configure the RPC to use the given server handler.
case configure(GRPCServerHandlerProtocol)
/// Reject the RPC by writing out the given headers and setting end-stream.
case rejectRPC(HPACKHeaders)
}
enum ReadNextMessageAction {
/// Do nothing.
case none
/// Forward the buffer.
case forwardMessage(ByteBuffer)
/// Forward the buffer and try reading the next message.
case forwardMessageThenReadNextMessage(ByteBuffer)
/// Forward the 'end' of stream request part.
case forwardEnd
/// Throw an error down the pipeline.
case errorCaught(Error)
}
struct StateAndReceiveHeadersAction {
/// The next state.
var state: State
/// The action to take.
var action: ReceiveHeadersAction
}
struct StateAndReceiveDataAction {
/// The next state.
var state: State
/// The action to take
var action: ReceiveDataAction
}
enum ReceiveDataAction: Hashable {
/// Try to read the next message from the state machine.
case tryReading
/// Invoke 'finish' on the RPC handler.
case finishHandler
/// Do nothing.
case nothing
}
enum SendEndAction {
/// Send trailers to the client.
case sendTrailers(HPACKHeaders)
/// Send trailers to the client and invoke 'finish' on the RPC handler.
case sendTrailersAndFinish(HPACKHeaders)
/// Fail any promise associated with this send.
case failure(Error)
}
}
// MARK: Receive Headers
// This is the only state in which we can receive headers.
extension HTTP2ToRawGRPCStateMachine.State {
private func _receive(
headers: HPACKHeaders,
eventLoop: EventLoop,
errorDelegate: ServerErrorDelegate?,
remoteAddress: SocketAddress?,
logger: Logger,
allocator: ByteBufferAllocator,
responseWriter: GRPCServerResponseWriter,
closeFuture: EventLoopFuture<Void>,
services: [Substring: CallHandlerProvider],
encoding: ServerMessageEncoding,
normalizeHeaders: Bool
) -> HTTP2ToRawGRPCStateMachine.StateAndReceiveHeadersAction {
// Extract and validate the content type. If it's nil we need to close.
guard let contentType = self.extractContentType(from: headers) else {
return self.unsupportedContentType()
}
// Now extract the request message encoding and setup an appropriate message reader.
// We may send back a list of acceptable request message encodings as well.
let reader: LengthPrefixedMessageReader
let acceptableRequestEncoding: String?
switch self.extractRequestEncoding(from: headers, encoding: encoding) {
case let .valid(messageReader, acceptEncodingHeader):
reader = messageReader
acceptableRequestEncoding = acceptEncodingHeader
case let .invalid(status, acceptableRequestEncoding):
return self.invalidRequestEncoding(
status: status,
acceptableRequestEncoding: acceptableRequestEncoding,
contentType: contentType
)
}
// Figure out which encoding we should use for responses.
let (writer, responseEncoding) = self.extractResponseEncoding(
from: headers,
encoding: encoding,
allocator: allocator
)
// Parse the path, and create a call handler.
guard let path = headers.first(name: ":path") else {
return self.methodNotImplemented("", contentType: contentType)
}
guard let callPath = CallPath(requestURI: path),
let service = services[Substring(callPath.service)] else {
return self.methodNotImplemented(path, contentType: contentType)
}
// Create a call handler context, i.e. a bunch of 'stuff' we need to create the handler with,
// some of which is exposed to service providers.
let context = CallHandlerContext(
errorDelegate: errorDelegate,
logger: logger,
encoding: encoding,
eventLoop: eventLoop,
path: path,
remoteAddress: remoteAddress,
responseWriter: responseWriter,
allocator: allocator,
closeFuture: closeFuture
)
// We have a matching service, hopefully we have a provider for the method too.
let method = Substring(callPath.method)
if let handler = service.handle(method: method, context: context) {
let nextState = HTTP2ToRawGRPCStateMachine.RequestOpenResponseIdleState(
reader: reader,
writer: writer,
contentType: contentType,
acceptEncoding: acceptableRequestEncoding,
responseEncoding: responseEncoding,
normalizeHeaders: normalizeHeaders,
configurationState: .configuring(headers)
)
return .init(
state: .requestOpenResponseIdle(nextState),
action: .configure(handler)
)
} else {
return self.methodNotImplemented(path, contentType: contentType)
}
}
/// The 'content-type' is not supported; close with status code 415.
private func unsupportedContentType() -> HTTP2ToRawGRPCStateMachine.StateAndReceiveHeadersAction {
// From: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md
//
// If 'content-type' does not begin with "application/grpc", gRPC servers SHOULD respond
// with HTTP status of 415 (Unsupported Media Type). This will prevent other HTTP/2
// clients from interpreting a gRPC error response, which uses status 200 (OK), as
// successful.
let trailers = HPACKHeaders([(":status", "415")])
return .init(
state: .requestClosedResponseClosed,
action: .rejectRPC(trailers)
)
}
/// The RPC method is not implemented. Close with an appropriate status.
private func methodNotImplemented(
_ path: String,
contentType: ContentType
) -> HTTP2ToRawGRPCStateMachine.StateAndReceiveHeadersAction {
let trailers = HTTP2ToRawGRPCStateMachine.makeResponseTrailersOnly(
for: GRPCStatus(code: .unimplemented, message: "'\(path)' is not implemented"),
contentType: contentType,
acceptableRequestEncoding: nil,
userProvidedHeaders: nil,
normalizeUserProvidedHeaders: false
)
return .init(
state: .requestClosedResponseClosed,
action: .rejectRPC(trailers)
)
}
/// The request encoding specified by the client is not supported. Close with an appropriate
/// status.
private func invalidRequestEncoding(
status: GRPCStatus,
acceptableRequestEncoding: String?,
contentType: ContentType
) -> HTTP2ToRawGRPCStateMachine.StateAndReceiveHeadersAction {
let trailers = HTTP2ToRawGRPCStateMachine.makeResponseTrailersOnly(
for: status,
contentType: contentType,
acceptableRequestEncoding: acceptableRequestEncoding,
userProvidedHeaders: nil,
normalizeUserProvidedHeaders: false
)
return .init(
state: .requestClosedResponseClosed,
action: .rejectRPC(trailers)
)
}
/// Makes a 'GRPCStatus' and response trailers suitable for returning to the client when the
/// request message encoding is not supported.
///
/// - Parameters:
/// - encoding: The unsupported request message encoding sent by the client.
/// - acceptable: The list if acceptable request message encoding the client may use.
/// - Returns: The status and trailers to return to the client.
private func makeStatusAndTrailersForUnsupportedEncoding(
_ encoding: String,
advertisedEncoding: [String]
) -> (GRPCStatus, acceptEncoding: String?) {
let status: GRPCStatus
let acceptEncoding: String?
if advertisedEncoding.isEmpty {
// No compression is supported; there's nothing to tell the client about.
status = GRPCStatus(code: .unimplemented, message: "compression is not supported")
acceptEncoding = nil
} else {
// Return a list of supported encodings which we advertise. (The list we advertise may be a
// subset of the encodings we support.)
acceptEncoding = advertisedEncoding.joined(separator: ",")
status = GRPCStatus(
code: .unimplemented,
message: "\(encoding) compression is not supported, supported algorithms are " +
"listed in '\(GRPCHeaderName.acceptEncoding)'"
)
}
return (status, acceptEncoding)
}
/// Extract and validate the 'content-type' sent by the client.
/// - Parameter headers: The headers to extract the 'content-type' from
private func extractContentType(from headers: HPACKHeaders) -> ContentType? {
return headers.first(name: GRPCHeaderName.contentType).flatMap(ContentType.init)
}
/// The result of validating the request encoding header.
private enum RequestEncodingValidation {
/// The encoding was valid.
case valid(messageReader: LengthPrefixedMessageReader, acceptEncoding: String?)
/// The encoding was invalid, the RPC should be terminated with this status.
case invalid(status: GRPCStatus, acceptEncoding: String?)
}
/// Extract and validate the request message encoding header.
/// - Parameters:
/// - headers: The headers to extract the message encoding header from.
/// - Returns: `RequestEncodingValidation`, either a message reader suitable for decoding requests
/// and an accept encoding response header if the request encoding was valid, or a pair of
/// `GRPCStatus` and trailers to close the RPC with.
private func extractRequestEncoding(
from headers: HPACKHeaders,
encoding: ServerMessageEncoding
) -> RequestEncodingValidation {
let encodings = headers[canonicalForm: GRPCHeaderName.encoding]
// Fail if there's more than one encoding header.
if encodings.count > 1 {
let status = GRPCStatus(
code: .invalidArgument,
message: "'\(GRPCHeaderName.encoding)' must contain no more than one value but was '\(encodings.joined(separator: ", "))'"
)
return .invalid(status: status, acceptEncoding: nil)
}
let encodingHeader = encodings.first
let result: RequestEncodingValidation
let validator = MessageEncodingHeaderValidator(encoding: encoding)
switch validator.validate(requestEncoding: encodingHeader) {
case let .supported(algorithm, decompressionLimit, acceptEncoding):
// Request message encoding is valid and supported.
result = .valid(
messageReader: LengthPrefixedMessageReader(
compression: algorithm,
decompressionLimit: decompressionLimit
),
acceptEncoding: acceptEncoding.isEmpty ? nil : acceptEncoding.joined(separator: ",")
)
case .noCompression:
// No message encoding header was present. This means no compression is being used.
result = .valid(
messageReader: LengthPrefixedMessageReader(),
acceptEncoding: nil
)
case let .unsupported(encoding, acceptable):
// Request encoding is not supported.
let (status, acceptEncoding) = self.makeStatusAndTrailersForUnsupportedEncoding(
encoding,
advertisedEncoding: acceptable
)
result = .invalid(status: status, acceptEncoding: acceptEncoding)
}
return result
}
/// Extract a suitable message encoding for responses.
/// - Parameters:
/// - headers: The headers to extract the acceptable response message encoding from.
/// - configuration: The encoding configuration for the server.
/// - Returns: A message writer and the response encoding header to send back to the client.
private func extractResponseEncoding(
from headers: HPACKHeaders,
encoding: ServerMessageEncoding,
allocator: ByteBufferAllocator
) -> (LengthPrefixedMessageWriter, String?) {
let writer: LengthPrefixedMessageWriter
let responseEncoding: String?
switch encoding {
case let .enabled(configuration):
// Extract the encodings acceptable to the client for response messages.
let acceptableResponseEncoding = headers[canonicalForm: GRPCHeaderName.acceptEncoding]
// Select the first algorithm that we support and have enabled. If we don't find one then we
// won't compress response messages.
let algorithm = acceptableResponseEncoding.lazy.compactMap { value in
CompressionAlgorithm(rawValue: value)
}.first {
configuration.enabledAlgorithms.contains($0)
}
writer = LengthPrefixedMessageWriter(compression: algorithm, allocator: allocator)
responseEncoding = algorithm?.name
case .disabled:
// The server doesn't have compression enabled.
writer = LengthPrefixedMessageWriter(compression: .none, allocator: allocator)
responseEncoding = nil
}
return (writer, responseEncoding)
}
}
// MARK: - Receive Data
extension HTTP2ToRawGRPCStateMachine.RequestOpenResponseIdleState {
mutating func receive(
buffer: inout ByteBuffer,
endStream: Bool
) -> HTTP2ToRawGRPCStateMachine.StateAndReceiveDataAction {
// Append the bytes to the reader.
self.reader.append(buffer: &buffer)
let state: HTTP2ToRawGRPCStateMachine.State
let action: HTTP2ToRawGRPCStateMachine.ReceiveDataAction
switch (self.configurationState.isConfigured, endStream) {
case (true, true):
/// Configured and end stream: read from the buffer, end will be sent as a result of draining
/// the reader in the next state.
state = .requestClosedResponseIdle(.init(from: self))
action = .tryReading
case (true, false):
/// Configured but not end stream, just read from the buffer.
state = .requestOpenResponseIdle(self)
action = .tryReading
case (false, true):
// Not configured yet, but end of stream. Request stream is now closed but there's no point
// reading yet.
state = .requestClosedResponseIdle(.init(from: self))
action = .nothing
case (false, false):
// Not configured yet, not end stream. No point reading a message yet since we don't have
// anywhere to deliver it.
state = .requestOpenResponseIdle(self)
action = .nothing
}
return .init(state: state, action: action)
}
}
extension HTTP2ToRawGRPCStateMachine.RequestOpenResponseOpenState {
mutating func receive(
buffer: inout ByteBuffer,
endStream: Bool
) -> HTTP2ToRawGRPCStateMachine.StateAndReceiveDataAction {
self.reader.append(buffer: &buffer)
let state: HTTP2ToRawGRPCStateMachine.State
if endStream {
// End stream, so move to the closed state. Any end of request stream events events will
// happen as a result of reading from the closed state.
state = .requestClosedResponseOpen(.init(from: self))
} else {
state = .requestOpenResponseOpen(self)
}
return .init(state: state, action: .tryReading)
}
}
// MARK: - Send Headers
extension HTTP2ToRawGRPCStateMachine.RequestOpenResponseIdleState {
func send(headers userProvidedHeaders: HPACKHeaders) -> HPACKHeaders {
return HTTP2ToRawGRPCStateMachine.makeResponseHeaders(
contentType: self.contentType,
responseEncoding: self.responseEncoding,
acceptableRequestEncoding: self.acceptEncoding,
userProvidedHeaders: userProvidedHeaders,
normalizeUserProvidedHeaders: self.normalizeHeaders
)
}
}
extension HTTP2ToRawGRPCStateMachine.RequestClosedResponseIdleState {
func send(headers userProvidedHeaders: HPACKHeaders) -> HPACKHeaders {
return HTTP2ToRawGRPCStateMachine.makeResponseHeaders(
contentType: self.contentType,
responseEncoding: self.responseEncoding,
acceptableRequestEncoding: self.acceptEncoding,
userProvidedHeaders: userProvidedHeaders,
normalizeUserProvidedHeaders: self.normalizeHeaders
)
}
}
// MARK: - Send Data
extension HTTP2ToRawGRPCStateMachine {
static func writeGRPCFramedMessage(
_ buffer: ByteBuffer,
compress: Bool,
writer: inout LengthPrefixedMessageWriter
) -> Result<(ByteBuffer, ByteBuffer?), Error> {
do {
let buffers = try writer.write(buffer: buffer, compressed: compress)
return .success(buffers)
} catch {
return .failure(error)
}
}
}
extension HTTP2ToRawGRPCStateMachine.RequestOpenResponseOpenState {
mutating func send(
buffer: ByteBuffer,
compress: Bool
) -> Result<(ByteBuffer, ByteBuffer?), Error> {
return HTTP2ToRawGRPCStateMachine.writeGRPCFramedMessage(
buffer,
compress: compress,
writer: &self.writer
)
}
}
extension HTTP2ToRawGRPCStateMachine.RequestClosedResponseOpenState {
mutating func send(
buffer: ByteBuffer,
compress: Bool
) -> Result<(ByteBuffer, ByteBuffer?), Error> {
return HTTP2ToRawGRPCStateMachine.writeGRPCFramedMessage(
buffer,
compress: compress,
writer: &self.writer
)
}
}
// MARK: - Send End
extension HTTP2ToRawGRPCStateMachine.RequestOpenResponseIdleState {
func send(
status: GRPCStatus,
trailers userProvidedTrailers: HPACKHeaders
) -> HPACKHeaders {
return HTTP2ToRawGRPCStateMachine.makeResponseTrailersOnly(
for: status,
contentType: self.contentType,
acceptableRequestEncoding: self.acceptEncoding,
userProvidedHeaders: userProvidedTrailers,
normalizeUserProvidedHeaders: self.normalizeHeaders
)
}
}
extension HTTP2ToRawGRPCStateMachine.RequestClosedResponseIdleState {
func send(
status: GRPCStatus,
trailers userProvidedTrailers: HPACKHeaders
) -> HPACKHeaders {
return HTTP2ToRawGRPCStateMachine.makeResponseTrailersOnly(
for: status,
contentType: self.contentType,
acceptableRequestEncoding: self.acceptEncoding,
userProvidedHeaders: userProvidedTrailers,
normalizeUserProvidedHeaders: self.normalizeHeaders
)
}
}
extension HTTP2ToRawGRPCStateMachine.RequestClosedResponseOpenState {
func send(
status: GRPCStatus,
trailers userProvidedTrailers: HPACKHeaders
) -> HPACKHeaders {
return HTTP2ToRawGRPCStateMachine.makeResponseTrailers(
for: status,
userProvidedHeaders: userProvidedTrailers,
normalizeUserProvidedHeaders: true
)
}
}
extension HTTP2ToRawGRPCStateMachine.RequestOpenResponseOpenState {
func send(
status: GRPCStatus,
trailers userProvidedTrailers: HPACKHeaders
) -> HPACKHeaders {
return HTTP2ToRawGRPCStateMachine.makeResponseTrailers(
for: status,
userProvidedHeaders: userProvidedTrailers,
normalizeUserProvidedHeaders: true
)
}
}
// MARK: - Pipeline Configured
extension HTTP2ToRawGRPCStateMachine.RequestOpenResponseIdleState {
mutating func pipelineConfigured() -> HTTP2ToRawGRPCStateMachine.PipelineConfiguredAction {
let headers = self.configurationState.configured()
let action: HTTP2ToRawGRPCStateMachine.PipelineConfiguredAction
// If there are unprocessed bytes then we need to read messages as well.
let hasUnprocessedBytes = self.reader.unprocessedBytes != 0
if hasUnprocessedBytes {
// If there are unprocessed bytes, we need to try to read after sending the metadata.
action = .forwardHeadersAndRead(headers)
} else {
// No unprocessed bytes; the reader is empty. Just send the metadata.
action = .forwardHeaders(headers)
}
return action
}
}
extension HTTP2ToRawGRPCStateMachine.RequestClosedResponseIdleState {
mutating func pipelineConfigured() -> HTTP2ToRawGRPCStateMachine.PipelineConfiguredAction {
let headers = self.configurationState.configured()
// Since we're already closed, we need to forward the headers and start reading.
return .forwardHeadersAndRead(headers)
}
}
// MARK: - Read Next Request
extension HTTP2ToRawGRPCStateMachine {
static func read(
from reader: inout LengthPrefixedMessageReader,
requestStreamClosed: Bool,
maxLength: Int
) -> HTTP2ToRawGRPCStateMachine.ReadNextMessageAction {
do {
if let buffer = try reader.nextMessage(maxLength: maxLength) {
if reader.unprocessedBytes > 0 || requestStreamClosed {
// Either there are unprocessed bytes or the request stream is now closed: deliver the
// message and then try to read. The subsequent read may be another message or it may
// be end stream.
return .forwardMessageThenReadNextMessage(buffer)
} else {
// Nothing left to process and the stream isn't closed yet, just forward the message.
return .forwardMessage(buffer)
}
} else if requestStreamClosed {
return .forwardEnd
} else {
return .none
}
} catch {
return .errorCaught(error)
}
}
}
extension HTTP2ToRawGRPCStateMachine.RequestOpenResponseIdleState {
mutating func readNextRequest(
maxLength: Int
) -> HTTP2ToRawGRPCStateMachine.ReadNextMessageAction {
return HTTP2ToRawGRPCStateMachine.read(
from: &self.reader,
requestStreamClosed: false,
maxLength: maxLength
)
}
}
extension HTTP2ToRawGRPCStateMachine.RequestOpenResponseOpenState {
mutating func readNextRequest(
maxLength: Int
) -> HTTP2ToRawGRPCStateMachine.ReadNextMessageAction {
return HTTP2ToRawGRPCStateMachine.read(
from: &self.reader,
requestStreamClosed: false,
maxLength: maxLength
)
}
}
extension HTTP2ToRawGRPCStateMachine.RequestClosedResponseIdleState {
mutating func readNextRequest(
maxLength: Int
) -> HTTP2ToRawGRPCStateMachine.ReadNextMessageAction {
return HTTP2ToRawGRPCStateMachine.read(
from: &self.reader,
requestStreamClosed: true,
maxLength: maxLength
)
}
}
extension HTTP2ToRawGRPCStateMachine.RequestClosedResponseOpenState {
mutating func readNextRequest(
maxLength: Int
) -> HTTP2ToRawGRPCStateMachine.ReadNextMessageAction {
return HTTP2ToRawGRPCStateMachine.read(
from: &self.reader,
requestStreamClosed: true,
maxLength: maxLength
)
}
}
// MARK: - Top Level State Changes
extension HTTP2ToRawGRPCStateMachine {
/// Receive request headers.
mutating func receive(
headers: HPACKHeaders,
eventLoop: EventLoop,
errorDelegate: ServerErrorDelegate?,
remoteAddress: SocketAddress?,
logger: Logger,
allocator: ByteBufferAllocator,
responseWriter: GRPCServerResponseWriter,
closeFuture: EventLoopFuture<Void>,
services: [Substring: CallHandlerProvider],
encoding: ServerMessageEncoding,
normalizeHeaders: Bool
) -> ReceiveHeadersAction {
return self.withStateAvoidingCoWs { state in
state.receive(
headers: headers,
eventLoop: eventLoop,
errorDelegate: errorDelegate,
remoteAddress: remoteAddress,
logger: logger,
allocator: allocator,
responseWriter: responseWriter,
closeFuture: closeFuture,
services: services,
encoding: encoding,
normalizeHeaders: normalizeHeaders
)
}
}
/// Receive request buffer.
/// - Parameters:
/// - buffer: The received buffer.
/// - endStream: Whether end stream was set.
/// - Returns: Returns whether the caller should try to read a message from the buffer.
mutating func receive(buffer: inout ByteBuffer, endStream: Bool) -> ReceiveDataAction {
return self.withStateAvoidingCoWs { state in
state.receive(buffer: &buffer, endStream: endStream)
}
}
/// Send response headers.
mutating func send(headers: HPACKHeaders) -> Result<HPACKHeaders, Error> {
return self.withStateAvoidingCoWs { state in
state.send(headers: headers)
}
}
/// Send a response buffer.
mutating func send(
buffer: ByteBuffer,
allocator: ByteBufferAllocator,
compress: Bool
) -> Result<(ByteBuffer, ByteBuffer?), Error> {
return self.withStateAvoidingCoWs { state in
state.send(buffer: buffer, allocator: allocator, compress: compress)
}
}
/// Send status and trailers.
mutating func send(
status: GRPCStatus,
trailers: HPACKHeaders
) -> HTTP2ToRawGRPCStateMachine.SendEndAction {
return self.withStateAvoidingCoWs { state in
state.send(status: status, trailers: trailers)
}
}
/// The pipeline has been configured with a service provider.
mutating func pipelineConfigured() -> PipelineConfiguredAction {
return self.withStateAvoidingCoWs { state in
state.pipelineConfigured()
}
}
/// Try to read a request message.
mutating func readNextRequest(maxLength: Int) -> ReadNextMessageAction {
return self.withStateAvoidingCoWs { state in
state.readNextRequest(maxLength: maxLength)
}
}
}
extension HTTP2ToRawGRPCStateMachine.State {
mutating func pipelineConfigured() -> HTTP2ToRawGRPCStateMachine.PipelineConfiguredAction {
switch self {
case .requestIdleResponseIdle:
preconditionFailure("Invalid state: pipeline configured before receiving request headers")
case var .requestOpenResponseIdle(state):
let action = state.pipelineConfigured()
self = .requestOpenResponseIdle(state)
return action
case var .requestClosedResponseIdle(state):
let action = state.pipelineConfigured()
self = .requestClosedResponseIdle(state)
return action
case .requestOpenResponseOpen,
.requestOpenResponseClosed,
.requestClosedResponseOpen,
.requestClosedResponseClosed:
preconditionFailure("Invalid state: response stream opened before pipeline was configured")
case ._modifying:
preconditionFailure("Left in modifying state")
}
}
mutating func receive(
headers: HPACKHeaders,
eventLoop: EventLoop,
errorDelegate: ServerErrorDelegate?,
remoteAddress: SocketAddress?,
logger: Logger,
allocator: ByteBufferAllocator,
responseWriter: GRPCServerResponseWriter,
closeFuture: EventLoopFuture<Void>,
services: [Substring: CallHandlerProvider],
encoding: ServerMessageEncoding,
normalizeHeaders: Bool
) -> HTTP2ToRawGRPCStateMachine.ReceiveHeadersAction {
switch self {
// These are the only states in which we can receive headers. Everything else is invalid.
case .requestIdleResponseIdle,
.requestClosedResponseClosed:
let stateAndAction = self._receive(
headers: headers,
eventLoop: eventLoop,
errorDelegate: errorDelegate,
remoteAddress: remoteAddress,
logger: logger,
allocator: allocator,
responseWriter: responseWriter,
closeFuture: closeFuture,
services: services,
encoding: encoding,
normalizeHeaders: normalizeHeaders
)
self = stateAndAction.state
return stateAndAction.action