EmbeddedClientThroughput.swift 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. /*
  2. * Copyright 2019, 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 struct Foundation.Data
  17. import GRPC
  18. import Logging
  19. import NIOCore
  20. import NIOEmbedded
  21. import NIOHPACK
  22. import NIOHTTP2
  23. /// Tests the throughput on the client side by firing a unary request through an embedded channel
  24. /// and writing back enough gRPC as HTTP/2 frames to get through the state machine.
  25. ///
  26. /// This only measures the handlers in the child channel.
  27. class EmbeddedClientThroughput: Benchmark {
  28. private let requestCount: Int
  29. private let requestText: String
  30. private let maximumResponseFrameSize: Int
  31. private var logger: Logger!
  32. private var requestHead: _GRPCRequestHead!
  33. private var request: Echo_EchoRequest!
  34. private var responseDataChunks: [ByteBuffer]!
  35. init(requests: Int, text: String, maxResponseFrameSize: Int = .max) {
  36. self.requestCount = requests
  37. self.requestText = text
  38. self.maximumResponseFrameSize = maxResponseFrameSize
  39. }
  40. func setUp() throws {
  41. self.logger = Logger(label: "io.grpc.testing", factory: { _ in SwiftLogNoOpLogHandler() })
  42. self.requestHead = _GRPCRequestHead(
  43. method: "POST",
  44. scheme: "http",
  45. path: "/echo.Echo/Get",
  46. host: "localhost",
  47. deadline: .distantFuture,
  48. customMetadata: [:],
  49. encoding: .disabled
  50. )
  51. self.request = .with {
  52. $0.text = self.requestText
  53. }
  54. let response = Echo_EchoResponse.with {
  55. $0.text = self.requestText
  56. }
  57. let serializedResponse = try response.serializedData()
  58. var buffer = ByteBufferAllocator().buffer(capacity: serializedResponse.count + 5)
  59. buffer.writeInteger(UInt8(0)) // compression byte
  60. buffer.writeInteger(UInt32(serializedResponse.count))
  61. buffer.writeContiguousBytes(serializedResponse)
  62. self.responseDataChunks = []
  63. while buffer.readableBytes > 0,
  64. let slice = buffer.readSlice(
  65. length: min(maximumResponseFrameSize, buffer.readableBytes)
  66. ) {
  67. self.responseDataChunks.append(slice)
  68. }
  69. }
  70. func tearDown() throws {}
  71. func run() throws -> Int {
  72. var messages = 0
  73. for _ in 0 ..< self.requestCount {
  74. let channel = EmbeddedChannel()
  75. try channel._configureForEmbeddedThroughputTest(
  76. callType: .unary,
  77. logger: self.logger,
  78. requestType: Echo_EchoRequest.self,
  79. responseType: Echo_EchoResponse.self
  80. ).wait()
  81. // Trigger the request handler.
  82. channel.pipeline.fireChannelActive()
  83. // Write the request parts.
  84. try channel.writeOutbound(_GRPCClientRequestPart<Echo_EchoRequest>.head(self.requestHead))
  85. try channel.writeOutbound(
  86. _GRPCClientRequestPart<Echo_EchoRequest>.message(.init(self.request, compressed: false))
  87. )
  88. try channel.writeOutbound(_GRPCClientRequestPart<Echo_EchoRequest>.end)
  89. messages += 1
  90. // Read out the request frames.
  91. var requestFrames = 0
  92. while let _ = try channel.readOutbound(as: HTTP2Frame.FramePayload.self) {
  93. requestFrames += 1
  94. }
  95. precondition(requestFrames == 3) // headers, data, empty data (end-stream)
  96. // Okay, let's build a response.
  97. // Required headers.
  98. let responseHeaders: HPACKHeaders = [
  99. ":status": "200",
  100. "content-type": "application/grpc+proto",
  101. ]
  102. let headerFrame = HTTP2Frame.FramePayload.headers(.init(headers: responseHeaders))
  103. try channel.writeInbound(headerFrame)
  104. // The response data.
  105. for chunk in self.responseDataChunks {
  106. let frame = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(chunk)))
  107. try channel.writeInbound(frame)
  108. }
  109. // Required trailers.
  110. let responseTrailers: HPACKHeaders = [
  111. "grpc-status": "0",
  112. "grpc-message": "ok",
  113. ]
  114. let trailersFrame = HTTP2Frame.FramePayload.headers(.init(headers: responseTrailers))
  115. try channel.writeInbound(trailersFrame)
  116. // And read them back out.
  117. var responseParts = 0
  118. while let _ = try channel.readInbound(as: _GRPCClientResponsePart<Echo_EchoResponse>.self) {
  119. responseParts += 1
  120. }
  121. precondition(responseParts == 4, "received \(responseParts) response parts")
  122. }
  123. return messages
  124. }
  125. }