NIOChannelPipeline+GRPC.swift 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. /*
  2. * Copyright 2024, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import GRPCCore
  17. import NIOCore
  18. import NIOHPACK
  19. import NIOHTTP2
  20. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  21. extension ChannelPipeline.SynchronousOperations {
  22. @_spi(Package) public typealias HTTP2ConnectionChannel = NIOAsyncChannel<HTTP2Frame, HTTP2Frame>
  23. @_spi(Package) public typealias HTTP2StreamMultiplexer = NIOHTTP2Handler.AsyncStreamMultiplexer<
  24. (NIOAsyncChannel<RPCRequestPart, RPCResponsePart>, EventLoopFuture<MethodDescriptor>)
  25. >
  26. @_spi(Package)
  27. public func configureGRPCServerPipeline(
  28. channel: any Channel,
  29. compressionConfig: HTTP2ServerTransport.Config.Compression,
  30. connectionConfig: HTTP2ServerTransport.Config.Connection,
  31. http2Config: HTTP2ServerTransport.Config.HTTP2,
  32. rpcConfig: HTTP2ServerTransport.Config.RPC,
  33. useTLS: Bool
  34. ) throws -> (HTTP2ConnectionChannel, HTTP2StreamMultiplexer) {
  35. let serverConnectionHandler = ServerConnectionManagementHandler(
  36. eventLoop: self.eventLoop,
  37. maxIdleTime: connectionConfig.maxIdleTime.map { TimeAmount($0) },
  38. maxAge: connectionConfig.maxAge.map { TimeAmount($0) },
  39. maxGraceTime: connectionConfig.maxGraceTime.map { TimeAmount($0) },
  40. keepaliveTime: TimeAmount(connectionConfig.keepalive.time),
  41. keepaliveTimeout: TimeAmount(connectionConfig.keepalive.timeout),
  42. allowKeepaliveWithoutCalls: connectionConfig.keepalive.clientBehavior.allowWithoutCalls,
  43. minPingIntervalWithoutCalls: TimeAmount(
  44. connectionConfig.keepalive.clientBehavior.minPingIntervalWithoutCalls
  45. )
  46. )
  47. let flushNotificationHandler = GRPCServerFlushNotificationHandler(
  48. serverConnectionManagementHandler: serverConnectionHandler
  49. )
  50. try self.addHandler(flushNotificationHandler)
  51. var http2HandlerConnectionConfiguration = NIOHTTP2Handler.ConnectionConfiguration()
  52. var http2HandlerHTTP2Settings = HTTP2Settings([
  53. HTTP2Setting(parameter: .initialWindowSize, value: http2Config.targetWindowSize),
  54. HTTP2Setting(parameter: .maxFrameSize, value: http2Config.maxFrameSize),
  55. HTTP2Setting(parameter: .maxHeaderListSize, value: HPACKDecoder.defaultMaxHeaderListSize),
  56. ])
  57. if let maxConcurrentStreams = http2Config.maxConcurrentStreams {
  58. http2HandlerHTTP2Settings.append(
  59. HTTP2Setting(parameter: .maxConcurrentStreams, value: maxConcurrentStreams)
  60. )
  61. }
  62. http2HandlerConnectionConfiguration.initialSettings = http2HandlerHTTP2Settings
  63. var http2HandlerStreamConfiguration = NIOHTTP2Handler.StreamConfiguration()
  64. http2HandlerStreamConfiguration.targetWindowSize = http2Config.targetWindowSize
  65. let streamMultiplexer = try self.configureAsyncHTTP2Pipeline(
  66. mode: .server,
  67. streamDelegate: serverConnectionHandler.http2StreamDelegate,
  68. configuration: NIOHTTP2Handler.Configuration(
  69. connection: http2HandlerConnectionConfiguration,
  70. stream: http2HandlerStreamConfiguration
  71. )
  72. ) { streamChannel in
  73. return streamChannel.eventLoop.makeCompletedFuture {
  74. let methodDescriptorPromise = streamChannel.eventLoop.makePromise(of: MethodDescriptor.self)
  75. let streamHandler = GRPCServerStreamHandler(
  76. scheme: useTLS ? .https : .http,
  77. acceptedEncodings: compressionConfig.enabledAlgorithms,
  78. maximumPayloadSize: rpcConfig.maxRequestPayloadSize,
  79. methodDescriptorPromise: methodDescriptorPromise
  80. )
  81. try streamChannel.pipeline.syncOperations.addHandler(streamHandler)
  82. let asyncStreamChannel = try NIOAsyncChannel<RPCRequestPart, RPCResponsePart>(
  83. wrappingChannelSynchronously: streamChannel
  84. )
  85. return (asyncStreamChannel, methodDescriptorPromise.futureResult)
  86. }
  87. }
  88. try self.addHandler(serverConnectionHandler)
  89. let connectionChannel = try NIOAsyncChannel<HTTP2Frame, HTTP2Frame>(
  90. wrappingChannelSynchronously: channel
  91. )
  92. return (connectionChannel, streamMultiplexer)
  93. }
  94. }
  95. extension ChannelPipeline.SynchronousOperations {
  96. @_spi(Package)
  97. @available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
  98. public func configureGRPCClientPipeline(
  99. channel: any Channel,
  100. config: GRPCChannel.Config
  101. ) throws -> (
  102. NIOAsyncChannel<ClientConnectionEvent, Void>,
  103. NIOHTTP2Handler.AsyncStreamMultiplexer<Void>
  104. ) {
  105. // Window size which mustn't exceed 2^32 - 1 (RFC 9113 § 6.1.3).
  106. let clampedTargetWindowSize = min(config.http2.targetWindowSize, (1 << 31) - 1)
  107. // Max frame size must be in the range 2^14 ..< 2^24 (RFC 9113 § 6.1.3).
  108. let clampedMaxFrameSize: Int
  109. if config.http2.maxFrameSize >= (1 << 24) {
  110. clampedMaxFrameSize = (1 << 24) - 1
  111. } else if config.http2.maxFrameSize < (1 << 14) {
  112. clampedMaxFrameSize = (1 << 14)
  113. } else {
  114. clampedMaxFrameSize = config.http2.maxFrameSize
  115. }
  116. // Use NIOs defaults as a starting point.
  117. var http2 = NIOHTTP2Handler.Configuration()
  118. http2.stream.targetWindowSize = clampedTargetWindowSize
  119. http2.connection.initialSettings = [
  120. // Disallow servers from creating push streams.
  121. HTTP2Setting(parameter: .enablePush, value: 0),
  122. // Set the initial window size and max frame size to the clamped configured values.
  123. HTTP2Setting(parameter: .initialWindowSize, value: clampedTargetWindowSize),
  124. HTTP2Setting(parameter: .maxFrameSize, value: clampedMaxFrameSize),
  125. // Use NIOs default max header list size (16kB)
  126. HTTP2Setting(parameter: .maxHeaderListSize, value: HPACKDecoder.defaultMaxHeaderListSize),
  127. ]
  128. let connectionHandler = ClientConnectionHandler(
  129. eventLoop: self.eventLoop,
  130. maxIdleTime: config.connection.maxIdleTime.map { TimeAmount($0) },
  131. keepaliveTime: config.connection.keepalive.map { TimeAmount($0.time) },
  132. keepaliveTimeout: config.connection.keepalive.map { TimeAmount($0.timeout) },
  133. keepaliveWithoutCalls: config.connection.keepalive?.allowWithoutCalls ?? false
  134. )
  135. let multiplexer = try self.configureAsyncHTTP2Pipeline(
  136. mode: .client,
  137. streamDelegate: connectionHandler.http2StreamDelegate,
  138. configuration: http2
  139. ) { stream in
  140. // Shouldn't happen, push-promises are disabled so the server shouldn't be able to
  141. // open streams.
  142. stream.close()
  143. }
  144. try self.addHandler(connectionHandler)
  145. let connection = try NIOAsyncChannel(
  146. wrappingChannelSynchronously: channel,
  147. configuration: NIOAsyncChannel.Configuration(
  148. inboundType: ClientConnectionEvent.self,
  149. outboundType: Void.self
  150. )
  151. )
  152. return (connection, multiplexer)
  153. }
  154. }