EmbeddedClientThroughput.swift 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  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 EchoModel
  17. import struct Foundation.Data
  18. import GRPC
  19. import Logging
  20. import NIO
  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.writeBytes(serializedResponse)
  62. self.responseDataChunks = []
  63. while buffer.readableBytes > 0,
  64. let slice = buffer.readSlice(length: min(maximumResponseFrameSize, buffer.readableBytes)) {
  65. self.responseDataChunks.append(slice)
  66. }
  67. }
  68. func tearDown() throws {}
  69. func run() throws {
  70. for _ in 0 ..< self.requestCount {
  71. let channel = EmbeddedChannel()
  72. try channel._configureForEmbeddedThroughputTest(
  73. callType: .unary,
  74. logger: self.logger,
  75. requestType: Echo_EchoRequest.self,
  76. responseType: Echo_EchoResponse.self
  77. ).wait()
  78. // Trigger the request handler.
  79. channel.pipeline.fireChannelActive()
  80. // Write the request parts.
  81. try channel.writeOutbound(_GRPCClientRequestPart<Echo_EchoRequest>.head(self.requestHead))
  82. try channel
  83. .writeOutbound(
  84. _GRPCClientRequestPart<Echo_EchoRequest>
  85. .message(.init(self.request, compressed: false))
  86. )
  87. try channel.writeOutbound(_GRPCClientRequestPart<Echo_EchoRequest>.end)
  88. // Read out the request frames.
  89. var requestFrames = 0
  90. while let _ = try channel.readOutbound(as: HTTP2Frame.FramePayload.self) {
  91. requestFrames += 1
  92. }
  93. precondition(requestFrames == 3) // headers, data, empty data (end-stream)
  94. // Okay, let's build a response.
  95. // Required headers.
  96. let responseHeaders: HPACKHeaders = [
  97. ":status": "200",
  98. "content-type": "application/grpc+proto",
  99. ]
  100. let headerFrame = HTTP2Frame.FramePayload.headers(.init(headers: responseHeaders))
  101. try channel.writeInbound(headerFrame)
  102. // The response data.
  103. for chunk in self.responseDataChunks {
  104. let frame = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(chunk)))
  105. try channel.writeInbound(frame)
  106. }
  107. // Required trailers.
  108. let responseTrailers: HPACKHeaders = [
  109. "grpc-status": "0",
  110. "grpc-message": "ok",
  111. ]
  112. let trailersFrame = HTTP2Frame.FramePayload.headers(.init(headers: responseTrailers))
  113. try channel.writeInbound(trailersFrame)
  114. // And read them back out.
  115. var responseParts = 0
  116. while let _ = try channel.readInbound(as: _GRPCClientResponsePart<Echo_EchoResponse>.self) {
  117. responseParts += 1
  118. }
  119. precondition(responseParts == 4, "received \(responseParts) response parts")
  120. }
  121. }
  122. }