GRPCCustomPayloadTests.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. .withLogger(self.serverLogger)
  31. .bind(host: "localhost", port: 0)
  32. .wait()
  33. let channel = ClientConnection.insecure(group: self.group)
  34. .withBackgroundActivityLogger(self.clientLogger)
  35. .connect(host: "localhost", port: self.server.channel.localAddress!.port!)
  36. self.client = AnyServiceClient(channel: channel, defaultCallOptions: self.callOptionsWithLogger)
  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. super.tearDown()
  43. }
  44. func testCustomPayload() throws {
  45. // This test demonstrates how to call a manually created bidirectional RPC with custom payloads.
  46. let statusExpectation = self.expectation(description: "status received")
  47. var responses: [CustomPayload] = []
  48. // Make a bidirectional stream using `CustomPayload` as the request and response type.
  49. // The service defined below is called "CustomPayload", and the method we call on it
  50. // is "AddOneAndReverseMessage"
  51. let rpc: BidirectionalStreamingCall<CustomPayload, CustomPayload> = self.client
  52. .makeBidirectionalStreamingCall(
  53. path: "/CustomPayload/AddOneAndReverseMessage",
  54. handler: { responses.append($0) }
  55. )
  56. // Make and send some requests:
  57. let requests: [CustomPayload] = [
  58. CustomPayload(message: "one", number: .random(in: Int64.min ..< Int64.max)),
  59. CustomPayload(message: "two", number: .random(in: Int64.min ..< Int64.max)),
  60. CustomPayload(message: "three", number: .random(in: Int64.min ..< Int64.max)),
  61. ]
  62. rpc.sendMessages(requests, promise: nil)
  63. rpc.sendEnd(promise: nil)
  64. // Wait for the RPC to finish before comparing responses.
  65. rpc.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation)
  66. self.wait(for: [statusExpectation], timeout: 1.0)
  67. // Are the responses as expected?
  68. let expected = requests.map { request in
  69. CustomPayload(message: String(request.message.reversed()), number: request.number + 1)
  70. }
  71. XCTAssertEqual(responses, expected)
  72. }
  73. func testNoDeserializationOnTheClient() throws {
  74. // This test demonstrates how to skip the deserialization step on the client. It isn't necessary
  75. // to use a custom service provider to do this, although we do here.
  76. let statusExpectation = self.expectation(description: "status received")
  77. var responses: [IdentityPayload] = []
  78. // Here we use `IdentityPayload` for our response type: we define it below such that it does
  79. // not deserialize the bytes provided to it by gRPC.
  80. let rpc: BidirectionalStreamingCall<CustomPayload, IdentityPayload> = self.client
  81. .makeBidirectionalStreamingCall(
  82. path: "/CustomPayload/AddOneAndReverseMessage",
  83. handler: { responses.append($0) }
  84. )
  85. let request = CustomPayload(message: "message", number: 42)
  86. rpc.sendMessage(request, promise: nil)
  87. rpc.sendEnd(promise: nil)
  88. // Wait for the RPC to finish before comparing responses.
  89. rpc.status.map { $0.code }.assertEqual(.ok, fulfill: statusExpectation)
  90. self.wait(for: [statusExpectation], timeout: 1.0)
  91. guard var response = responses.first?.buffer else {
  92. XCTFail("RPC completed without a response")
  93. return
  94. }
  95. // We just took the raw bytes from the payload: we can still decode it because we know the
  96. // server returned a serialized `CustomPayload`.
  97. let actual = try CustomPayload(serializedByteBuffer: &response)
  98. XCTAssertEqual(actual.message, "egassem")
  99. XCTAssertEqual(actual.number, 43)
  100. }
  101. func testCustomPayloadUnary() throws {
  102. let rpc: UnaryCall<StringPayload, StringPayload> = self.client.makeUnaryCall(
  103. path: "/CustomPayload/Reverse",
  104. request: StringPayload(message: "foobarbaz")
  105. )
  106. XCTAssertEqual(try rpc.response.map { $0.message }.wait(), "zabraboof")
  107. XCTAssertEqual(try rpc.status.map { $0.code }.wait(), .ok)
  108. }
  109. func testCustomPayloadClientStreaming() throws {
  110. let rpc: ClientStreamingCall<StringPayload, StringPayload> = self.client
  111. .makeClientStreamingCall(path: "/CustomPayload/ReverseThenJoin")
  112. rpc.sendMessages(["foo", "bar", "baz"].map(StringPayload.init(message:)), promise: nil)
  113. rpc.sendEnd(promise: nil)
  114. XCTAssertEqual(try rpc.response.map { $0.message }.wait(), "baz bar foo")
  115. XCTAssertEqual(try rpc.status.map { $0.code }.wait(), .ok)
  116. }
  117. func testCustomPayloadServerStreaming() throws {
  118. let message = "abc"
  119. var expectedIterator = message.reversed().makeIterator()
  120. let rpc: ServerStreamingCall<StringPayload, StringPayload> = self.client
  121. .makeServerStreamingCall(
  122. path: "/CustomPayload/ReverseThenSplit",
  123. request: StringPayload(message: message)
  124. ) { response in
  125. if let next = expectedIterator.next() {
  126. XCTAssertEqual(String(next), response.message)
  127. } else {
  128. XCTFail("Unexpected message: \(response.message)")
  129. }
  130. }
  131. XCTAssertEqual(try rpc.status.map { $0.code }.wait(), .ok)
  132. }
  133. }
  134. // MARK: Custom Payload Service
  135. private class CustomPayloadProvider: CallHandlerProvider {
  136. var serviceName: Substring = "CustomPayload"
  137. fileprivate func reverseString(
  138. request: StringPayload,
  139. context: UnaryResponseCallContext<StringPayload>
  140. ) -> EventLoopFuture<StringPayload> {
  141. let reversed = StringPayload(message: String(request.message.reversed()))
  142. return context.eventLoop.makeSucceededFuture(reversed)
  143. }
  144. fileprivate func reverseThenJoin(
  145. context: UnaryResponseCallContext<StringPayload>
  146. ) -> EventLoopFuture<(StreamEvent<StringPayload>) -> Void> {
  147. var messages: [String] = []
  148. return context.eventLoop.makeSucceededFuture({ event in
  149. switch event {
  150. case let .message(request):
  151. messages.append(request.message)
  152. case .end:
  153. let response = messages.reversed().joined(separator: " ")
  154. context.responsePromise.succeed(StringPayload(message: response))
  155. }
  156. })
  157. }
  158. fileprivate func reverseThenSplit(
  159. request: StringPayload,
  160. context: StreamingResponseCallContext<StringPayload>
  161. ) -> EventLoopFuture<GRPCStatus> {
  162. let responses = request.message.reversed().map {
  163. context.sendResponse(StringPayload(message: String($0)))
  164. }
  165. return EventLoopFuture.andAllSucceed(responses, on: context.eventLoop).map { .ok }
  166. }
  167. // Bidirectional RPC which returns a new `CustomPayload` for each `CustomPayload` received.
  168. // The returned payloads have their `message` reversed and their `number` incremented by one.
  169. fileprivate func addOneAndReverseMessage(
  170. context: StreamingResponseCallContext<CustomPayload>
  171. ) -> EventLoopFuture<(StreamEvent<CustomPayload>) -> Void> {
  172. return context.eventLoop.makeSucceededFuture({ event in
  173. switch event {
  174. case let .message(payload):
  175. let response = CustomPayload(
  176. message: String(payload.message.reversed()),
  177. number: payload.number + 1
  178. )
  179. _ = context.sendResponse(response)
  180. case .end:
  181. context.statusPromise.succeed(.ok)
  182. }
  183. })
  184. }
  185. func handleMethod(_ methodName: Substring,
  186. callHandlerContext: CallHandlerContext) -> GRPCCallHandler? {
  187. switch methodName {
  188. case "Reverse":
  189. return CallHandlerFactory.makeUnary(callHandlerContext: callHandlerContext) { context in
  190. { request in
  191. self.reverseString(request: request, context: context)
  192. }
  193. }
  194. case "ReverseThenJoin":
  195. return CallHandlerFactory
  196. .makeClientStreaming(callHandlerContext: callHandlerContext) { context in
  197. self.reverseThenJoin(context: context)
  198. }
  199. case "ReverseThenSplit":
  200. return CallHandlerFactory
  201. .makeServerStreaming(callHandlerContext: callHandlerContext) { context in
  202. { request in
  203. self.reverseThenSplit(request: request, context: context)
  204. }
  205. }
  206. case "AddOneAndReverseMessage":
  207. return CallHandlerFactory
  208. .makeBidirectionalStreaming(callHandlerContext: callHandlerContext) { context in
  209. self.addOneAndReverseMessage(context: context)
  210. }
  211. default:
  212. return nil
  213. }
  214. }
  215. }
  216. private struct IdentityPayload: GRPCPayload {
  217. var buffer: ByteBuffer
  218. init(serializedByteBuffer: inout ByteBuffer) throws {
  219. self.buffer = serializedByteBuffer
  220. }
  221. func serialize(into buffer: inout ByteBuffer) throws {
  222. // This will never be called, however, it could be implemented as a direct copy of the bytes
  223. // we hold, e.g.:
  224. //
  225. // var copy = self.buffer
  226. // buffer.writeBuffer(&copy)
  227. fatalError("Unimplemented")
  228. }
  229. }
  230. /// A toy custom payload which holds a `String` and an `Int64`.
  231. ///
  232. /// The payload is serialized as:
  233. /// - the `UInt32` encoded length of the message,
  234. /// - the UTF-8 encoded bytes of the message, and
  235. /// - the `Int64` bytes of the number.
  236. private struct CustomPayload: GRPCPayload, Equatable {
  237. var message: String
  238. var number: Int64
  239. init(message: String, number: Int64) {
  240. self.message = message
  241. self.number = number
  242. }
  243. init(serializedByteBuffer: inout ByteBuffer) throws {
  244. guard let messageLength = serializedByteBuffer.readInteger(as: UInt32.self),
  245. let message = serializedByteBuffer.readString(length: Int(messageLength)),
  246. let number = serializedByteBuffer.readInteger(as: Int64.self) else {
  247. throw GRPCError.DeserializationFailure()
  248. }
  249. self.message = message
  250. self.number = number
  251. }
  252. func serialize(into buffer: inout ByteBuffer) throws {
  253. buffer.writeInteger(UInt32(self.message.count))
  254. buffer.writeString(self.message)
  255. buffer.writeInteger(self.number)
  256. }
  257. }
  258. private struct StringPayload: GRPCPayload {
  259. var message: String
  260. init(message: String) {
  261. self.message = message
  262. }
  263. init(serializedByteBuffer: inout ByteBuffer) throws {
  264. self.message = serializedByteBuffer.readString(length: serializedByteBuffer.readableBytes)!
  265. }
  266. func serialize(into buffer: inout ByteBuffer) throws {
  267. buffer.writeString(self.message)
  268. }
  269. }