GRPCCustomPayloadTests.swift 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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 GRPC
  17. import NIO
  18. import XCTest
  19. // These tests demonstrate how to use gRPC to create a service provider using your own payload type,
  20. // or alternatively, how to avoid deserialization and just extract the raw bytes from a payload.
  21. class GRPCCustomPayloadTests: GRPCTestCase {
  22. var group: EventLoopGroup!
  23. var server: Server!
  24. var client: AnyServiceClient!
  25. override func setUp() {
  26. super.setUp()
  27. self.group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  28. let serverConfig: Server.Configuration = .init(
  29. target: .hostAndPort("localhost", 0),
  30. eventLoopGroup: self.group,
  31. serviceProviders: [CustomPayloadProvider()]
  32. )
  33. self.server = try! Server.start(configuration: serverConfig).wait()
  34. let channel = ClientConnection.insecure(group: self.group)
  35. .connect(host: "localhost", port: server.channel.localAddress!.port!)
  36. self.client = AnyServiceClient(channel: channel)
  37. }
  38. override func tearDown() {
  39. XCTAssertNoThrow(try self.server.close().wait())
  40. XCTAssertNoThrow(try self.client.channel.close().wait())
  41. XCTAssertNoThrow(try self.group.syncShutdownGracefully())
  42. }
  43. func testCustomPayload() throws {
  44. // This test demonstrates how to call a manually created bidirectional RPC with custom payloads.
  45. let statusExpectation = self.expectation(description: "status received")
  46. var responses: [CustomPayload] = []
  47. // Make a bidirectional stream using `CustomPayload` as the request and response type.
  48. // The service defined below is called "CustomPayload", and the method we call on it
  49. // is "AddOneAndReverseMessage"
  50. let rpc: BidirectionalStreamingCall<CustomPayload, CustomPayload> = self.client.makeBidirectionalStreamingCall(
  51. path: "/CustomPayload/AddOneAndReverseMessage",
  52. handler: { responses.append($0) }
  53. )
  54. // Make and send some requests:
  55. let requests: [CustomPayload] = [
  56. CustomPayload(message: "one", number: .random(in: Int64.min..<Int64.max)),
  57. CustomPayload(message: "two", number: .random(in: Int64.min..<Int64.max)),
  58. CustomPayload(message: "three", number: .random(in: Int64.min..<Int64.max))
  59. ]
  60. rpc.sendMessages(requests, promise: nil)
  61. rpc.sendEnd(promise: nil)
  62. // Wait for the RPC to finish before comparing responses.
  63. rpc.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation)
  64. self.wait(for: [statusExpectation], timeout: 1.0)
  65. // Are the responses as expected?
  66. let expected = requests.map { request in
  67. CustomPayload(message: String(request.message.reversed()), number: request.number + 1)
  68. }
  69. XCTAssertEqual(responses, expected)
  70. }
  71. func testNoDeserializationOnTheClient() throws {
  72. // This test demonstrates how to skip the deserialization step on the client. It isn't necessary
  73. // to use a custom service provider to do this, although we do here.
  74. let statusExpectation = self.expectation(description: "status received")
  75. var responses: [IdentityPayload] = []
  76. // Here we use `IdentityPayload` for our response type: we define it below such that it does
  77. // not deserialize the bytes provided to it by gRPC.
  78. let rpc: BidirectionalStreamingCall<CustomPayload, IdentityPayload> = self.client.makeBidirectionalStreamingCall(
  79. path: "/CustomPayload/AddOneAndReverseMessage",
  80. handler: { responses.append($0) }
  81. )
  82. let request = CustomPayload(message: "message", number: 42)
  83. rpc.sendMessage(request, promise: nil)
  84. rpc.sendEnd(promise: nil)
  85. // Wait for the RPC to finish before comparing responses.
  86. rpc.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation)
  87. self.wait(for: [statusExpectation], timeout: 1.0)
  88. guard var response = responses.first?.buffer else {
  89. XCTFail("RPC completed without a response")
  90. return
  91. }
  92. // We just took the raw bytes from the payload: we can still decode it because we know the
  93. // server returned a serialized `CustomPayload`.
  94. let actual = try CustomPayload(serializedByteBuffer: &response)
  95. XCTAssertEqual(actual.message, "egassem")
  96. XCTAssertEqual(actual.number, 43)
  97. }
  98. }
  99. // MARK: Custom Payload Service
  100. fileprivate class CustomPayloadProvider: CallHandlerProvider {
  101. var serviceName: String = "CustomPayload"
  102. // Bidirectional RPC which returns a new `CustomPayload` for each `CustomPayload` received.
  103. // The returned payloads have their `message` reversed and their `number` incremented by one.
  104. fileprivate func addOneAndReverseMessage(
  105. context: StreamingResponseCallContext<CustomPayload>
  106. ) -> EventLoopFuture<(StreamEvent<CustomPayload>) -> Void> {
  107. return context.eventLoop.makeSucceededFuture({ event in
  108. switch event {
  109. case .message(let payload):
  110. let response = CustomPayload(
  111. message: String(payload.message.reversed()),
  112. number: payload.number + 1
  113. )
  114. _ = context.sendResponse(response)
  115. case .end:
  116. context.statusPromise.succeed(.ok)
  117. }
  118. })
  119. }
  120. func handleMethod(_ methodName: String, callHandlerContext: CallHandlerContext) -> GRPCCallHandler? {
  121. switch methodName {
  122. case "AddOneAndReverseMessage":
  123. return BidirectionalStreamingCallHandler<CustomPayload, CustomPayload>(callHandlerContext: callHandlerContext) { context in
  124. return self.addOneAndReverseMessage(context: context)
  125. }
  126. default:
  127. return nil
  128. }
  129. }
  130. }
  131. fileprivate struct IdentityPayload: GRPCPayload {
  132. var buffer: ByteBuffer
  133. init(serializedByteBuffer: inout ByteBuffer) throws {
  134. self.buffer = serializedByteBuffer
  135. }
  136. func serialize(into buffer: inout ByteBuffer) throws {
  137. // This will never be called, however, it could be implemented as a direct copy of the bytes
  138. // we hold, e.g.:
  139. //
  140. // var copy = self.buffer
  141. // buffer.writeBuffer(&copy)
  142. fatalError("Unimplemented")
  143. }
  144. }
  145. /// A toy custom payload which holds a `String` and an `Int64`.
  146. ///
  147. /// The payload is serialized as:
  148. /// - the `UInt32` encoded length of the message,
  149. /// - the UTF-8 encoded bytes of the message, and
  150. /// - the `Int64` bytes of the number.
  151. fileprivate struct CustomPayload: GRPCPayload, Equatable {
  152. var message: String
  153. var number: Int64
  154. init(message: String, number: Int64) {
  155. self.message = message
  156. self.number = number
  157. }
  158. init(serializedByteBuffer: inout ByteBuffer) throws {
  159. guard let messageLength = serializedByteBuffer.readInteger(as: UInt32.self),
  160. let message = serializedByteBuffer.readString(length: Int(messageLength)),
  161. let number = serializedByteBuffer.readInteger(as: Int64.self) else {
  162. throw GRPCError.DeserializationFailure()
  163. }
  164. self.message = message
  165. self.number = number
  166. }
  167. func serialize(into buffer: inout ByteBuffer) throws {
  168. buffer.writeInteger(UInt32(self.message.count))
  169. buffer.writeString(self.message)
  170. buffer.writeInteger(self.number)
  171. }
  172. }