GRPCCustomPayloadTests.swift 7.3 KB

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