NIOChannelPipeline+GRPC.swift 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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. package import GRPCCore
  17. package import NIOCore
  18. internal import NIOHPACK
  19. package import NIOHTTP2
  20. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  21. extension ChannelPipeline.SynchronousOperations {
  22. package typealias HTTP2ConnectionChannel = NIOAsyncChannel<HTTP2Frame, HTTP2Frame>
  23. package typealias HTTP2StreamMultiplexer = NIOHTTP2Handler.AsyncStreamMultiplexer<
  24. (NIOAsyncChannel<RPCRequestPart, RPCResponsePart>, EventLoopFuture<MethodDescriptor>)
  25. >
  26. package func configureGRPCServerPipeline(
  27. channel: any Channel,
  28. compressionConfig: HTTP2ServerTransport.Config.Compression,
  29. connectionConfig: HTTP2ServerTransport.Config.Connection,
  30. http2Config: HTTP2ServerTransport.Config.HTTP2,
  31. rpcConfig: HTTP2ServerTransport.Config.RPC,
  32. useTLS: Bool
  33. ) throws -> (HTTP2ConnectionChannel, HTTP2StreamMultiplexer) {
  34. let serverConnectionHandler = ServerConnectionManagementHandler(
  35. eventLoop: self.eventLoop,
  36. maxIdleTime: connectionConfig.maxIdleTime.map { TimeAmount($0) },
  37. maxAge: connectionConfig.maxAge.map { TimeAmount($0) },
  38. maxGraceTime: connectionConfig.maxGraceTime.map { TimeAmount($0) },
  39. keepaliveTime: TimeAmount(connectionConfig.keepalive.time),
  40. keepaliveTimeout: TimeAmount(connectionConfig.keepalive.timeout),
  41. allowKeepaliveWithoutCalls: connectionConfig.keepalive.clientBehavior.allowWithoutCalls,
  42. minPingIntervalWithoutCalls: TimeAmount(
  43. connectionConfig.keepalive.clientBehavior.minPingIntervalWithoutCalls
  44. )
  45. )
  46. let flushNotificationHandler = GRPCServerFlushNotificationHandler(
  47. serverConnectionManagementHandler: serverConnectionHandler
  48. )
  49. try self.addHandler(flushNotificationHandler)
  50. let clampedTargetWindowSize = self.clampTargetWindowSize(http2Config.targetWindowSize)
  51. let clampedMaxFrameSize = self.clampMaxFrameSize(http2Config.maxFrameSize)
  52. var http2HandlerConnectionConfiguration = NIOHTTP2Handler.ConnectionConfiguration()
  53. var http2HandlerHTTP2Settings = HTTP2Settings([
  54. HTTP2Setting(parameter: .initialWindowSize, value: clampedTargetWindowSize),
  55. HTTP2Setting(parameter: .maxFrameSize, value: clampedMaxFrameSize),
  56. HTTP2Setting(parameter: .maxHeaderListSize, value: HPACKDecoder.defaultMaxHeaderListSize),
  57. ])
  58. if let maxConcurrentStreams = http2Config.maxConcurrentStreams {
  59. http2HandlerHTTP2Settings.append(
  60. HTTP2Setting(parameter: .maxConcurrentStreams, value: maxConcurrentStreams)
  61. )
  62. }
  63. http2HandlerConnectionConfiguration.initialSettings = http2HandlerHTTP2Settings
  64. var http2HandlerStreamConfiguration = NIOHTTP2Handler.StreamConfiguration()
  65. http2HandlerStreamConfiguration.targetWindowSize = clampedTargetWindowSize
  66. let streamMultiplexer = try self.configureAsyncHTTP2Pipeline(
  67. mode: .server,
  68. streamDelegate: serverConnectionHandler.http2StreamDelegate,
  69. configuration: NIOHTTP2Handler.Configuration(
  70. connection: http2HandlerConnectionConfiguration,
  71. stream: http2HandlerStreamConfiguration
  72. )
  73. ) { streamChannel in
  74. return streamChannel.eventLoop.makeCompletedFuture {
  75. let methodDescriptorPromise = streamChannel.eventLoop.makePromise(of: MethodDescriptor.self)
  76. let streamHandler = GRPCServerStreamHandler(
  77. scheme: useTLS ? .https : .http,
  78. acceptedEncodings: compressionConfig.enabledAlgorithms,
  79. maximumPayloadSize: rpcConfig.maxRequestPayloadSize,
  80. methodDescriptorPromise: methodDescriptorPromise
  81. )
  82. try streamChannel.pipeline.syncOperations.addHandler(streamHandler)
  83. let asyncStreamChannel = try NIOAsyncChannel<RPCRequestPart, RPCResponsePart>(
  84. wrappingChannelSynchronously: streamChannel
  85. )
  86. return (asyncStreamChannel, methodDescriptorPromise.futureResult)
  87. }
  88. }
  89. try self.addHandler(serverConnectionHandler)
  90. let connectionChannel = try NIOAsyncChannel<HTTP2Frame, HTTP2Frame>(
  91. wrappingChannelSynchronously: channel
  92. )
  93. return (connectionChannel, streamMultiplexer)
  94. }
  95. }
  96. extension ChannelPipeline.SynchronousOperations {
  97. @available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
  98. package func configureGRPCClientPipeline(
  99. channel: any Channel,
  100. config: GRPCChannel.Config
  101. ) throws -> (
  102. NIOAsyncChannel<ClientConnectionEvent, Void>,
  103. NIOHTTP2Handler.AsyncStreamMultiplexer<Void>
  104. ) {
  105. let clampedTargetWindowSize = self.clampTargetWindowSize(config.http2.targetWindowSize)
  106. let clampedMaxFrameSize = self.clampMaxFrameSize(config.http2.maxFrameSize)
  107. // Use NIOs defaults as a starting point.
  108. var http2 = NIOHTTP2Handler.Configuration()
  109. http2.stream.targetWindowSize = clampedTargetWindowSize
  110. http2.connection.initialSettings = [
  111. // Disallow servers from creating push streams.
  112. HTTP2Setting(parameter: .enablePush, value: 0),
  113. // Set the initial window size and max frame size to the clamped configured values.
  114. HTTP2Setting(parameter: .initialWindowSize, value: clampedTargetWindowSize),
  115. HTTP2Setting(parameter: .maxFrameSize, value: clampedMaxFrameSize),
  116. // Use NIOs default max header list size (16kB)
  117. HTTP2Setting(parameter: .maxHeaderListSize, value: HPACKDecoder.defaultMaxHeaderListSize),
  118. ]
  119. let connectionHandler = ClientConnectionHandler(
  120. eventLoop: self.eventLoop,
  121. maxIdleTime: config.connection.maxIdleTime.map { TimeAmount($0) },
  122. keepaliveTime: config.connection.keepalive.map { TimeAmount($0.time) },
  123. keepaliveTimeout: config.connection.keepalive.map { TimeAmount($0.timeout) },
  124. keepaliveWithoutCalls: config.connection.keepalive?.allowWithoutCalls ?? false
  125. )
  126. let multiplexer = try self.configureAsyncHTTP2Pipeline(
  127. mode: .client,
  128. streamDelegate: connectionHandler.http2StreamDelegate,
  129. configuration: http2
  130. ) { stream in
  131. // Shouldn't happen, push-promises are disabled so the server shouldn't be able to
  132. // open streams.
  133. stream.close()
  134. }
  135. try self.addHandler(connectionHandler)
  136. let connection = try NIOAsyncChannel(
  137. wrappingChannelSynchronously: channel,
  138. configuration: NIOAsyncChannel.Configuration(
  139. inboundType: ClientConnectionEvent.self,
  140. outboundType: Void.self
  141. )
  142. )
  143. return (connection, multiplexer)
  144. }
  145. }
  146. extension ChannelPipeline.SynchronousOperations {
  147. /// Max frame size must be in the range `2^14 ..< 2^24` (RFC 9113 § 4.2).
  148. fileprivate func clampMaxFrameSize(_ maxFrameSize: Int) -> Int {
  149. let clampedMaxFrameSize: Int
  150. if maxFrameSize >= (1 << 24) {
  151. clampedMaxFrameSize = (1 << 24) - 1
  152. } else if maxFrameSize < (1 << 14) {
  153. clampedMaxFrameSize = (1 << 14)
  154. } else {
  155. clampedMaxFrameSize = maxFrameSize
  156. }
  157. return clampedMaxFrameSize
  158. }
  159. /// Window size which mustn't exceed `2^31 - 1` (RFC 9113 § 6.5.2).
  160. internal func clampTargetWindowSize(_ targetWindowSize: Int) -> Int {
  161. min(targetWindowSize, (1 << 31) - 1)
  162. }
  163. }