EmbeddedClientThroughput.swift 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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 NIO
  18. import NIOHTTP2
  19. import NIOHPACK
  20. import GRPC
  21. import EchoModel
  22. import Logging
  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, let slice = buffer.readSlice(length: min(maximumResponseFrameSize, buffer.readableBytes)) {
  64. self.responseDataChunks.append(slice)
  65. }
  66. }
  67. func tearDown() throws {
  68. }
  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.writeOutbound(_GRPCClientRequestPart<Echo_EchoRequest>.message(.init(self.request, compressed: false)))
  83. try channel.writeOutbound(_GRPCClientRequestPart<Echo_EchoRequest>.end)
  84. // Read out the request frames.
  85. var requestFrames = 0
  86. while let _ = try channel.readOutbound(as: HTTP2Frame.self) {
  87. requestFrames += 1
  88. }
  89. precondition(requestFrames == 3) // headers, data, empty data (end-stream)
  90. // Okay, let's build a response.
  91. // Required headers.
  92. let responseHeaders: HPACKHeaders = [
  93. ":status": "200",
  94. "content-type": "application/grpc+proto"
  95. ]
  96. let headerFrame = HTTP2Frame(streamID: .init(1), payload: .headers(.init(headers: responseHeaders)))
  97. try channel.writeInbound(headerFrame)
  98. // The response data.
  99. for chunk in self.responseDataChunks {
  100. let frame = HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(chunk))))
  101. try channel.writeInbound(frame)
  102. }
  103. // Required trailers.
  104. let responseTrailers: HPACKHeaders = [
  105. "grpc-status": "0",
  106. "grpc-message": "ok"
  107. ]
  108. let trailersFrame = HTTP2Frame(streamID: .init(1), payload: .headers(.init(headers: responseTrailers)))
  109. try channel.writeInbound(trailersFrame)
  110. // And read them back out.
  111. var responseParts = 0
  112. while let _ = try channel.readInbound(as: _GRPCClientResponsePart<Echo_EchoResponse>.self) {
  113. responseParts += 1
  114. }
  115. precondition(responseParts == 4, "received \(responseParts) response parts")
  116. }
  117. }
  118. }