EmbeddedServer.swift 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Copyright 2020, 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 EchoImplementation
  17. import EchoModel
  18. import GRPC
  19. import Logging
  20. import NIO
  21. import NIOHPACK
  22. import NIOHTTP2
  23. final class EmbeddedServerUnaryBenchmark: Benchmark {
  24. private let count: Int
  25. private let text: String
  26. private let providers: [Substring: CallHandlerProvider]
  27. private let logger: Logger
  28. static let headersPayload = HTTP2Frame.FramePayload.headers(.init(headers: [
  29. ":path": "/echo.Echo/Get",
  30. ":method": "POST",
  31. "content-type": "application/grpc",
  32. ]))
  33. private var requestPayload: HTTP2Frame.FramePayload!
  34. init(count: Int, text: String) {
  35. self.count = count
  36. self.text = text
  37. let echo = EchoProvider()
  38. self.providers = [echo.serviceName: echo]
  39. self.logger = Logger(label: "noop") { _ in
  40. SwiftLogNoOpLogHandler()
  41. }
  42. }
  43. func setUp() throws {
  44. var buffer = ByteBuffer()
  45. let serialized = try Echo_EchoRequest.with { $0.text = self.text }.serializedData()
  46. buffer.reserveCapacity(5 + serialized.count)
  47. buffer.writeInteger(UInt8(0)) // not compressed
  48. buffer.writeInteger(UInt32(serialized.count)) // length
  49. buffer.writeData(serialized)
  50. self.requestPayload = .data(.init(data: .byteBuffer(buffer), endStream: true))
  51. }
  52. func tearDown() throws {}
  53. func run() throws {
  54. for _ in 0 ..< self.count {
  55. let channel = EmbeddedChannel()
  56. try channel._configureForEmbeddedServerTest(
  57. servicesByName: self.providers,
  58. encoding: .disabled,
  59. normalizeHeaders: true,
  60. logger: self.logger
  61. ).wait()
  62. try channel.writeInbound(Self.headersPayload)
  63. try channel.writeInbound(self.requestPayload)
  64. // headers, data, trailers
  65. _ = try channel.readOutbound(as: HTTP2Frame.FramePayload.self)
  66. _ = try channel.readOutbound(as: HTTP2Frame.FramePayload.self)
  67. _ = try channel.readOutbound(as: HTTP2Frame.FramePayload.self)
  68. }
  69. }
  70. }