From e61979e2ec3634807fa90765715e08601112fbe1 Mon Sep 17 00:00:00 2001 From: feuyeux Date: Wed, 9 Oct 2024 01:00:41 +0800 Subject: [PATCH] neat swift --- hello-grpc-swift/Package.swift | 2 +- hello-grpc-swift/README.md | 27 +- .../Sources/Client/HelloClient.swift | 352 +++--- .../Sources/Common/Connection.swift | 24 +- hello-grpc-swift/Sources/Common/Utils.swift | 31 +- .../Sources/Common/landing.grpc.swift | 1092 ++++++++--------- .../Sources/Common/landing.pb.swift | 411 +++---- .../Sources/Server/HelloServer.swift | 87 +- .../Sources/Server/HelloServiceProvider.swift | 175 ++- hello-grpc-swift/doc/create_symlink.md | 8 + hello-grpc-swift/fmt.sh | 2 +- hello-grpc-swift/proto2swift.sh | 9 +- 12 files changed, 1091 insertions(+), 1129 deletions(-) create mode 100644 hello-grpc-swift/doc/create_symlink.md diff --git a/hello-grpc-swift/Package.swift b/hello-grpc-swift/Package.swift index ee0cee4..b0499b1 100644 --- a/hello-grpc-swift/Package.swift +++ b/hello-grpc-swift/Package.swift @@ -4,7 +4,7 @@ import PackageDescription let packageDependencies: [Package.Dependency] = [ - .package(url: "https://github.com/grpc/grpc-swift.git", from: "1.23.1"), + .package(url: "https://github.com/grpc/grpc-swift.git", from: "1.24.1"), .package(url: "https://github.com/apple/swift-nio.git", from: "2.74.0"), .package(url: "https://github.com/apple/swift-protobuf.git", from: "1.28.2"), .package(url: "https://github.com/apple/swift-log.git", from: "1.6.1"), diff --git a/hello-grpc-swift/README.md b/hello-grpc-swift/README.md index b643e4e..f3f9f93 100644 --- a/hello-grpc-swift/README.md +++ b/hello-grpc-swift/README.md @@ -45,16 +45,26 @@ swiftformat --indent 4 --swiftversion 6.0.1 --exclude "**/*.grpc.swift,**/*.pb.s ## build ```sh -# 老 Mac 用上最新 macOS -# https://dortania.github.io/OpenCore-Legacy-Patcher/INSTALLER.html#creating-the-installer -# https://github.com/getlantern/lantern +export PATH=/home/han/swift-6.0.1-RELEASE-ubuntu22.04/usr/bin:$PATH +``` -brew install swift-protobuf grpc-swift -cd Sources/Common +```sh +swift build +swift build --product protoc-gen-swift +swift build --product protoc-gen-grpc-swift +``` + +```sh +export protoc_gen_swift=/mnt/d/coding/hello-grpc/hello-grpc-swift/.build/x86_64-unknown-linux-gnu/debug/protoc-gen-swift +export protoc_generate_grpc_swift=/mnt/d/coding/hello-grpc/hello-grpc-swift/.build/x86_64-unknown-linux-gnu/debug/protoc-gen-grpc-swift sh proto2swift.sh ``` ```sh +# 老 Mac 用上最新 macOS +# https://dortania.github.io/OpenCore-Legacy-Patcher/INSTALLER.html#creating-the-installer +# https://github.com/getlantern/lantern + # clean if meeting issue: "PCH was compiled with module cache path ..., but the path is currently ..." rm -rf ~/Library/Developer/Xcode/DerivedData rm -rf .build @@ -62,18 +72,11 @@ Clean: ⇧shift+⌘cmd+K in xcode ``` ```sh - export proxy_port=56458 export http_proxy=127.0.0.1:$proxy_port export https_proxy=127.0.0.1:$proxy_port ``` -```sh -swift build -swift build --product protoc-gen-swift -swift build --product protoc-gen-grpc-swift -``` - ## run ```sh diff --git a/hello-grpc-swift/Sources/Client/HelloClient.swift b/hello-grpc-swift/Sources/Client/HelloClient.swift index ba29615..5f0fbda 100644 --- a/hello-grpc-swift/Sources/Client/HelloClient.swift +++ b/hello-grpc-swift/Sources/Client/HelloClient.swift @@ -1,200 +1,212 @@ -import ArgumentParser - -import Foundation - -import GRPC - -import HelloCommon - -import Logging - -import NIOCore - -import NIOPosix - -struct HelloExample { - let logger = Logger(label: "HelloClient") - - private let client: Hello_LandingServiceAsyncClient - - init(client: Hello_LandingServiceAsyncClient) { - self.client = client - } - - func run() async { - await talk() - await talkOneAnswerMore() - await talkMoreAnswerOne() - await talkBidirectional() - } -} -extension HelloExample { - private func talk() async { - logger.info("\n→ talk:") - let request: Hello_TalkRequest = .with { - $0.data = "0" - $0.meta = "SWIFT" +#if compiler(>=5.6) + import ArgumentParser + import Foundation + import GRPC + import HelloCommon + import Logging + import NIOCore + import NIOPosix + + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + struct HelloExample { + let logger = Logger(label: "HelloClient") + + private let client: Hello_LandingServiceAsyncClient + + init(client: Hello_LandingServiceAsyncClient) { + self.client = client } - let callOptions = CallOptions( - customMetadata: [ - "k1": "v1" - ], - timeLimit: .deadline(.now() + .seconds(1)) - ) - do { - let response = try await client.talk(request, callOptions: callOptions) - logger.info("Talk Response \(response.status) \(response.results)") - } catch { - logger.info("RPC failed: \(error)") - } - } - private func talkOneAnswerMore() async { - logger.info("\n→ talkOneAnswerMore:") - let request: Hello_TalkRequest = .with { - $0.data = "0,1,2" - $0.meta = "SWIFT" + func run() async { + await talk() + await talkOneAnswerMore() + await talkMoreAnswerOne() + await talkBidirectional() } + } - do { - var resultCount = 1 + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + extension HelloExample { + private func talk() async { + logger.info("\n→ talk:") + let request: Hello_TalkRequest = .with { + $0.data = "0" + $0.meta = "SWIFT" + } let callOptions = CallOptions( customMetadata: [ "k1": "v1" ], timeLimit: .deadline(.now() + .seconds(1)) ) - for try await response in client.talkOneAnswerMore(request, callOptions: callOptions) { - logger.info( - "TalkOneAnswerMore Response[\(resultCount)] \(response.status) \(response.results)" - ) - resultCount += 1 + do { + let response = try await client.talk(request, callOptions: callOptions) + logger.info("Talk Response \(response.status) \(response.results)") + } catch { + logger.info("RPC failed: \(error)") } - } catch { - logger.info("RPC failed: \(error)") } - } - private func talkMoreAnswerOne() async { - logger.info("\n→ talkMoreAnswerOne") - let rid = Int.random(in: 0..<6) - let requests: [Hello_TalkRequest] = [ - .with { - $0.data = String(rid) + private func talkOneAnswerMore() async { + logger.info("\n→ talkOneAnswerMore:") + let request: Hello_TalkRequest = .with { + $0.data = "0,1,2" $0.meta = "SWIFT" - }, - .with { - $0.data = "1" - $0.meta = "SWIFT" - }, - .with { - $0.data = "2" - $0.meta = "SWIFT" - }, - ] - let callOptions = CallOptions( - customMetadata: [ - "k1": "v1" - ], - timeLimit: .deadline(.now() + .seconds(2)) - ) - let streamingCall = client.makeTalkMoreAnswerOneCall(callOptions: callOptions) - do { - for request in requests { - try await streamingCall.requestStream.send(request) - - // Sleep for 0.2s ... 1.0s before sending the next point. - try await Task.sleep(nanoseconds: UInt64.random(in: UInt64(2e8)...UInt64(1e9))) } - streamingCall.requestStream.finish() - let response = try await streamingCall.response - logger.info("TalkMoreAnswerOne Response \(response.status) \(response.results)") - } catch { - logger.info("TalkMoreAnswerOne Failed: \(error)") + do { + var resultCount = 1 + let callOptions = CallOptions( + customMetadata: [ + "k1": "v1" + ], + timeLimit: .deadline(.now() + .seconds(1)) + ) + for try await response in client.talkOneAnswerMore( + request, callOptions: callOptions) + { + logger.info( + "TalkOneAnswerMore Response[\(resultCount)] \(response.status) \(response.results)" + ) + resultCount += 1 + } + } catch { + logger.info("RPC failed: \(error)") + } } - } - private func talkBidirectional() async { - logger.info("\n→ talkBidirectional") - let requests: [Hello_TalkRequest] = [ - .with { - $0.data = "0" - $0.meta = "SWIFT" - }, - .with { - $0.data = "1" - $0.meta = "SWIFT" - }, - .with { - $0.data = "2" - $0.meta = "SWIFT" - }, - ] - let callOptions = CallOptions( - customMetadata: [ - "k1": "v1" - ], - timeLimit: .deadline(.now() + .seconds(3)) - ) - do { - try await withThrowingTaskGroup(of: Void.self) { group in - let streamingCall = client.makeTalkBidirectionalCall(callOptions: callOptions) - - // Add a task to send each message adding a small sleep between each. - group.addTask { - for request in requests { - try await streamingCall.requestStream.send(request) - // Sleep for 0.2s ... 1.0s before sending the next note. - try await Task.sleep( - nanoseconds: UInt64.random(in: UInt64(2e8)...UInt64(1e9))) - } - streamingCall.requestStream.finish() + private func talkMoreAnswerOne() async { + logger.info("\n→ talkMoreAnswerOne") + let rid = Int.random(in: 0..<6) + let requests: [Hello_TalkRequest] = [ + .with { + $0.data = String(rid) + $0.meta = "SWIFT" + }, + .with { + $0.data = "1" + $0.meta = "SWIFT" + }, + .with { + $0.data = "2" + $0.meta = "SWIFT" + }, + ] + let callOptions = CallOptions( + customMetadata: [ + "k1": "v1" + ], + timeLimit: .deadline(.now() + .seconds(2)) + ) + let streamingCall = client.makeTalkMoreAnswerOneCall(callOptions: callOptions) + do { + for request in requests { + try await streamingCall.requestStream.send(request) + + // Sleep for 0.2s ... 1.0s before sending the next point. + try await Task.sleep(nanoseconds: UInt64.random(in: UInt64(2e8)...UInt64(1e9))) } - // Add a task to logger.info each message received on the response stream. - group.addTask { - do { - for try await response in streamingCall.responseStream { - logger.info( - "TalkBidirectional Response \(response.status) \(response.results)") + streamingCall.requestStream.finish() + let response = try await streamingCall.response + logger.info("TalkMoreAnswerOne Response \(response.status) \(response.results)") + } catch { + logger.info("TalkMoreAnswerOne Failed: \(error)") + } + } + + private func talkBidirectional() async { + logger.info("\n→ talkBidirectional") + let requests: [Hello_TalkRequest] = [ + .with { + $0.data = "0" + $0.meta = "SWIFT" + }, + .with { + $0.data = "1" + $0.meta = "SWIFT" + }, + .with { + $0.data = "2" + $0.meta = "SWIFT" + }, + ] + let callOptions = CallOptions( + customMetadata: [ + "k1": "v1" + ], + timeLimit: .deadline(.now() + .seconds(3)) + ) + do { + try await withThrowingTaskGroup(of: Void.self) { group in + let streamingCall = client.makeTalkBidirectionalCall(callOptions: callOptions) + + // Add a task to send each message adding a small sleep between each. + group.addTask { + for request in requests { + try await streamingCall.requestStream.send(request) + // Sleep for 0.2s ... 1.0s before sending the next note. + try await Task.sleep( + nanoseconds: UInt64.random(in: UInt64(2e8)...UInt64(1e9))) } - } catch { - logger.info("TalkBidirectional Failed: \(error)") + streamingCall.requestStream.finish() } - } - try await group.waitForAll() + // Add a task to logger.info each message received on the response stream. + group.addTask { + do { + for try await response in streamingCall.responseStream { + logger.info( + "TalkBidirectional Response \(response.status) \(response.results)" + ) + } + } catch { + logger.info("TalkBidirectional Failed: \(error)") + } + } + + try await group.waitForAll() + } + } catch { + logger.info("TalkBidirectional Failed: \(error)") } - } catch { - logger.info("TalkBidirectional Failed: \(error)") } } -} -struct HelloClient: AsyncParsableCommand { - func run() async throws { - let conn = HelloConn() - let group = PlatformSupport.makeEventLoopGroup(loopCount: 1) - defer { - try? group.syncShutdownGracefully() - } - let connectTo = ProcessInfo.processInfo.environment["GRPC_SERVER"] ?? "localhost" - let channel = try GRPCChannelPool.with( - target: .host(connectTo, port: conn.port), - transportSecurity: .plaintext, - eventLoopGroup: group - ) - defer { - try? channel.close().wait() - } + @main + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + struct HelloClient: AsyncParsableCommand { + func run() async throws { + let conn = HelloConn() + let group = PlatformSupport.makeEventLoopGroup(loopCount: 1) + defer { + try? group.syncShutdownGracefully() + } - let client = Hello_LandingServiceAsyncClient(channel: channel) - let example = HelloExample(client: client) - await example.run() - } + let connectTo = ProcessInfo.processInfo.environment["GRPC_SERVER"] ?? "localhost" + let channel = try GRPCChannelPool.with( + target: .host(connectTo, port: conn.port), + transportSecurity: .plaintext, + eventLoopGroup: group + ) + defer { + try? channel.close().wait() + } + + let client = Hello_LandingServiceAsyncClient(channel: channel) + let example = HelloExample(client: client) + await example.run() + } - init() {} + init() {} - init(from _: Decoder) throws {} -} + init(from _: Decoder) throws {} + } +#else + @main + enum NotAvailable { + static func main() { + logger.info("This example requires Swift >= 5.6") + } + } +#endif // compiler(>=5.6) diff --git a/hello-grpc-swift/Sources/Common/Connection.swift b/hello-grpc-swift/Sources/Common/Connection.swift index 9583d89..42bd007 100644 --- a/hello-grpc-swift/Sources/Common/Connection.swift +++ b/hello-grpc-swift/Sources/Common/Connection.swift @@ -1,17 +1,19 @@ import Foundation - import Logging -public protocol Connection { - var port: Int { get } -} -public class HelloConn: Connection { - let logger = Logger(label: "HelloConn") +#if compiler(>=5.6) - public var port: Int = 9996 + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + public protocol Connection { + var port: Int { get } + } - public init() { - // let user = ProcessInfo.processInfo.environment["USER"] - // logger.info("Hello \(user!)") + public class HelloConn: Connection { + let logger = Logger(label: "HelloConn") + public var port: Int = 9996 + public init() { + // let user = ProcessInfo.processInfo.environment["USER"] + // logger.info("Hello \(user!)") + } } -} +#endif // compiler(>=5.6) diff --git a/hello-grpc-swift/Sources/Common/Utils.swift b/hello-grpc-swift/Sources/Common/Utils.swift index fcf9f2a..96df0fe 100644 --- a/hello-grpc-swift/Sources/Common/Utils.swift +++ b/hello-grpc-swift/Sources/Common/Utils.swift @@ -1,16 +1,21 @@ import Foundation - import Logging -public enum Utils { - public static let helloList: [String] = ["Hello", "Bonjour", "Hola", "こんにちは", "Ciao", "안녕하세요"] - public static let ansMap: [String: String] = [ - "你好": "非常感谢", - "Hello": "Thank you very much", - "Bonjour": "Merci beaucoup", - "Hola": "Muchas Gracias", - "こんにちは": "どうも ありがとう ございます", - "Ciao": "Mille Grazie", - "안녕하세요": "대단히 감사합니다", - ] -} +#if compiler(>=5.6) + + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + public enum Utils { + public static let helloList: [String] = [ + "Hello", "Bonjour", "Hola", "こんにちは", "Ciao", "안녕하세요", + ] + public static let ansMap: [String: String] = [ + "你好": "非常感谢", + "Hello": "Thank you very much", + "Bonjour": "Merci beaucoup", + "Hola": "Muchas Gracias", + "こんにちは": "どうも ありがとう ございます", + "Ciao": "Mille Grazie", + "안녕하세요": "대단히 감사합니다", + ] + } +#endif // compiler(>=5.6) diff --git a/hello-grpc-swift/Sources/Common/landing.grpc.swift b/hello-grpc-swift/Sources/Common/landing.grpc.swift index 02da5a7..8887da1 100644 --- a/hello-grpc-swift/Sources/Common/landing.grpc.swift +++ b/hello-grpc-swift/Sources/Common/landing.grpc.swift @@ -5,7 +5,6 @@ // Generated by the protocol buffer compiler. // Source: landing.proto // - import GRPC import NIO import NIOConcurrencyHelpers @@ -14,632 +13,615 @@ import SwiftProtobuf /// Usage: instantiate `Hello_LandingServiceClient`, then call methods of this protocol to make API calls. public protocol Hello_LandingServiceClientProtocol: GRPCClient { - var serviceName: String { get } - var interceptors: Hello_LandingServiceClientInterceptorFactoryProtocol? { get } - - func talk( - _ request: Hello_TalkRequest, - callOptions: CallOptions? - ) -> UnaryCall - - func talkOneAnswerMore( - _ request: Hello_TalkRequest, - callOptions: CallOptions?, - handler: @escaping (Hello_TalkResponse) -> Void - ) -> ServerStreamingCall - - func talkMoreAnswerOne( - callOptions: CallOptions? - ) -> ClientStreamingCall - - func talkBidirectional( - callOptions: CallOptions?, - handler: @escaping (Hello_TalkResponse) -> Void - ) -> BidirectionalStreamingCall + var serviceName: String { get } + var interceptors: Hello_LandingServiceClientInterceptorFactoryProtocol? { get } + + func talk( + _ request: Hello_TalkRequest, + callOptions: CallOptions? + ) -> UnaryCall + + func talkOneAnswerMore( + _ request: Hello_TalkRequest, + callOptions: CallOptions?, + handler: @escaping (Hello_TalkResponse) -> Void + ) -> ServerStreamingCall + + func talkMoreAnswerOne( + callOptions: CallOptions? + ) -> ClientStreamingCall + + func talkBidirectional( + callOptions: CallOptions?, + handler: @escaping (Hello_TalkResponse) -> Void + ) -> BidirectionalStreamingCall } extension Hello_LandingServiceClientProtocol { - public var serviceName: String { - return "hello.LandingService" - } - - ///Unary RPC - /// - /// - Parameters: - /// - request: Request to send to Talk. - /// - callOptions: Call options. - /// - Returns: A `UnaryCall` with futures for the metadata, status and response. - public func talk( - _ request: Hello_TalkRequest, - callOptions: CallOptions? = nil - ) -> UnaryCall { - return self.makeUnaryCall( - path: Hello_LandingServiceClientMetadata.Methods.talk.path, - request: request, - callOptions: callOptions ?? self.defaultCallOptions, - interceptors: self.interceptors?.makeTalkInterceptors() ?? [] - ) - } - - ///Server streaming RPC - /// - /// - Parameters: - /// - request: Request to send to TalkOneAnswerMore. - /// - callOptions: Call options. - /// - handler: A closure called when each response is received from the server. - /// - Returns: A `ServerStreamingCall` with futures for the metadata and status. - public func talkOneAnswerMore( - _ request: Hello_TalkRequest, - callOptions: CallOptions? = nil, - handler: @escaping (Hello_TalkResponse) -> Void - ) -> ServerStreamingCall { - return self.makeServerStreamingCall( - path: Hello_LandingServiceClientMetadata.Methods.talkOneAnswerMore.path, - request: request, - callOptions: callOptions ?? self.defaultCallOptions, - interceptors: self.interceptors?.makeTalkOneAnswerMoreInterceptors() ?? [], - handler: handler - ) - } - - ///Client streaming RPC with random & sleep - /// - /// Callers should use the `send` method on the returned object to send messages - /// to the server. The caller should send an `.end` after the final message has been sent. - /// - /// - Parameters: - /// - callOptions: Call options. - /// - Returns: A `ClientStreamingCall` with futures for the metadata, status and response. - public func talkMoreAnswerOne( - callOptions: CallOptions? = nil - ) -> ClientStreamingCall { - return self.makeClientStreamingCall( - path: Hello_LandingServiceClientMetadata.Methods.talkMoreAnswerOne.path, - callOptions: callOptions ?? self.defaultCallOptions, - interceptors: self.interceptors?.makeTalkMoreAnswerOneInterceptors() ?? [] - ) - } - - ///Bidirectional streaming RPC - /// - /// Callers should use the `send` method on the returned object to send messages - /// to the server. The caller should send an `.end` after the final message has been sent. - /// - /// - Parameters: - /// - callOptions: Call options. - /// - handler: A closure called when each response is received from the server. - /// - Returns: A `ClientStreamingCall` with futures for the metadata and status. - public func talkBidirectional( - callOptions: CallOptions? = nil, - handler: @escaping (Hello_TalkResponse) -> Void - ) -> BidirectionalStreamingCall { - return self.makeBidirectionalStreamingCall( - path: Hello_LandingServiceClientMetadata.Methods.talkBidirectional.path, - callOptions: callOptions ?? self.defaultCallOptions, - interceptors: self.interceptors?.makeTalkBidirectionalInterceptors() ?? [], - handler: handler - ) - } + public var serviceName: String { + return "hello.LandingService" + } + + ///Unary RPC + /// + /// - Parameters: + /// - request: Request to send to Talk. + /// - callOptions: Call options. + /// - Returns: A `UnaryCall` with futures for the metadata, status and response. + public func talk( + _ request: Hello_TalkRequest, + callOptions: CallOptions? = nil + ) -> UnaryCall { + return self.makeUnaryCall( + path: Hello_LandingServiceClientMetadata.Methods.talk.path, + request: request, + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeTalkInterceptors() ?? [] + ) + } + + ///Server streaming RPC + /// + /// - Parameters: + /// - request: Request to send to TalkOneAnswerMore. + /// - callOptions: Call options. + /// - handler: A closure called when each response is received from the server. + /// - Returns: A `ServerStreamingCall` with futures for the metadata and status. + public func talkOneAnswerMore( + _ request: Hello_TalkRequest, + callOptions: CallOptions? = nil, + handler: @escaping (Hello_TalkResponse) -> Void + ) -> ServerStreamingCall { + return self.makeServerStreamingCall( + path: Hello_LandingServiceClientMetadata.Methods.talkOneAnswerMore.path, + request: request, + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeTalkOneAnswerMoreInterceptors() ?? [], + handler: handler + ) + } + + ///Client streaming RPC with random & sleep + /// + /// Callers should use the `send` method on the returned object to send messages + /// to the server. The caller should send an `.end` after the final message has been sent. + /// + /// - Parameters: + /// - callOptions: Call options. + /// - Returns: A `ClientStreamingCall` with futures for the metadata, status and response. + public func talkMoreAnswerOne( + callOptions: CallOptions? = nil + ) -> ClientStreamingCall { + return self.makeClientStreamingCall( + path: Hello_LandingServiceClientMetadata.Methods.talkMoreAnswerOne.path, + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeTalkMoreAnswerOneInterceptors() ?? [] + ) + } + + ///Bidirectional streaming RPC + /// + /// Callers should use the `send` method on the returned object to send messages + /// to the server. The caller should send an `.end` after the final message has been sent. + /// + /// - Parameters: + /// - callOptions: Call options. + /// - handler: A closure called when each response is received from the server. + /// - Returns: A `ClientStreamingCall` with futures for the metadata and status. + public func talkBidirectional( + callOptions: CallOptions? = nil, + handler: @escaping (Hello_TalkResponse) -> Void + ) -> BidirectionalStreamingCall { + return self.makeBidirectionalStreamingCall( + path: Hello_LandingServiceClientMetadata.Methods.talkBidirectional.path, + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeTalkBidirectionalInterceptors() ?? [], + handler: handler + ) + } } @available(*, deprecated) -extension Hello_LandingServiceClient: @unchecked Sendable { -} +extension Hello_LandingServiceClient: @unchecked Sendable {} @available(*, deprecated, renamed: "Hello_LandingServiceNIOClient") public final class Hello_LandingServiceClient: Hello_LandingServiceClientProtocol { - private let lock = Lock() - private var _defaultCallOptions: CallOptions - private var _interceptors: Hello_LandingServiceClientInterceptorFactoryProtocol? - public let channel: GRPCChannel - public var defaultCallOptions: CallOptions { - get { - self.lock.withLock { - return self._defaultCallOptions - } - } - set { - self.lock.withLockVoid { - self._defaultCallOptions = newValue - } - } - } - public var interceptors: Hello_LandingServiceClientInterceptorFactoryProtocol? { - get { - self.lock.withLock { - return self._interceptors - } - } - set { - self.lock.withLockVoid { - self._interceptors = newValue - } - } - } - - /// Creates a client for the hello.LandingService service. - /// - /// - Parameters: - /// - channel: `GRPCChannel` to the service host. - /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them. - /// - interceptors: A factory providing interceptors for each RPC. - public init( - channel: GRPCChannel, - defaultCallOptions: CallOptions = CallOptions(), - interceptors: Hello_LandingServiceClientInterceptorFactoryProtocol? = nil - ) { - self.channel = channel - self._defaultCallOptions = defaultCallOptions - self._interceptors = interceptors - } + private let lock = Lock() + private var _defaultCallOptions: CallOptions + private var _interceptors: Hello_LandingServiceClientInterceptorFactoryProtocol? + public let channel: GRPCChannel + public var defaultCallOptions: CallOptions { + get { self.lock.withLock { return self._defaultCallOptions } } + set { self.lock.withLockVoid { self._defaultCallOptions = newValue } } + } + public var interceptors: Hello_LandingServiceClientInterceptorFactoryProtocol? { + get { self.lock.withLock { return self._interceptors } } + set { self.lock.withLockVoid { self._interceptors = newValue } } + } + + /// Creates a client for the hello.LandingService service. + /// + /// - Parameters: + /// - channel: `GRPCChannel` to the service host. + /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them. + /// - interceptors: A factory providing interceptors for each RPC. + public init( + channel: GRPCChannel, + defaultCallOptions: CallOptions = CallOptions(), + interceptors: Hello_LandingServiceClientInterceptorFactoryProtocol? = nil + ) { + self.channel = channel + self._defaultCallOptions = defaultCallOptions + self._interceptors = interceptors + } } public struct Hello_LandingServiceNIOClient: Hello_LandingServiceClientProtocol { - public var channel: GRPCChannel - public var defaultCallOptions: CallOptions - public var interceptors: Hello_LandingServiceClientInterceptorFactoryProtocol? - - /// Creates a client for the hello.LandingService service. - /// - /// - Parameters: - /// - channel: `GRPCChannel` to the service host. - /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them. - /// - interceptors: A factory providing interceptors for each RPC. - public init( - channel: GRPCChannel, - defaultCallOptions: CallOptions = CallOptions(), - interceptors: Hello_LandingServiceClientInterceptorFactoryProtocol? = nil - ) { - self.channel = channel - self.defaultCallOptions = defaultCallOptions - self.interceptors = interceptors - } + public var channel: GRPCChannel + public var defaultCallOptions: CallOptions + public var interceptors: Hello_LandingServiceClientInterceptorFactoryProtocol? + + /// Creates a client for the hello.LandingService service. + /// + /// - Parameters: + /// - channel: `GRPCChannel` to the service host. + /// - defaultCallOptions: Options to use for each service call if the user doesn't provide them. + /// - interceptors: A factory providing interceptors for each RPC. + public init( + channel: GRPCChannel, + defaultCallOptions: CallOptions = CallOptions(), + interceptors: Hello_LandingServiceClientInterceptorFactoryProtocol? = nil + ) { + self.channel = channel + self.defaultCallOptions = defaultCallOptions + self.interceptors = interceptors + } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public protocol Hello_LandingServiceAsyncClientProtocol: GRPCClient { - static var serviceDescriptor: GRPCServiceDescriptor { get } - var interceptors: Hello_LandingServiceClientInterceptorFactoryProtocol? { get } - - func makeTalkCall( - _ request: Hello_TalkRequest, - callOptions: CallOptions? - ) -> GRPCAsyncUnaryCall - - func makeTalkOneAnswerMoreCall( - _ request: Hello_TalkRequest, - callOptions: CallOptions? - ) -> GRPCAsyncServerStreamingCall - - func makeTalkMoreAnswerOneCall( - callOptions: CallOptions? - ) -> GRPCAsyncClientStreamingCall - - func makeTalkBidirectionalCall( - callOptions: CallOptions? - ) -> GRPCAsyncBidirectionalStreamingCall + static var serviceDescriptor: GRPCServiceDescriptor { get } + var interceptors: Hello_LandingServiceClientInterceptorFactoryProtocol? { get } + + func makeTalkCall( + _ request: Hello_TalkRequest, + callOptions: CallOptions? + ) -> GRPCAsyncUnaryCall + + func makeTalkOneAnswerMoreCall( + _ request: Hello_TalkRequest, + callOptions: CallOptions? + ) -> GRPCAsyncServerStreamingCall + + func makeTalkMoreAnswerOneCall( + callOptions: CallOptions? + ) -> GRPCAsyncClientStreamingCall + + func makeTalkBidirectionalCall( + callOptions: CallOptions? + ) -> GRPCAsyncBidirectionalStreamingCall } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension Hello_LandingServiceAsyncClientProtocol { - public static var serviceDescriptor: GRPCServiceDescriptor { - return Hello_LandingServiceClientMetadata.serviceDescriptor - } - - public var interceptors: Hello_LandingServiceClientInterceptorFactoryProtocol? { - return nil - } - - public func makeTalkCall( - _ request: Hello_TalkRequest, - callOptions: CallOptions? = nil - ) -> GRPCAsyncUnaryCall { - return self.makeAsyncUnaryCall( - path: Hello_LandingServiceClientMetadata.Methods.talk.path, - request: request, - callOptions: callOptions ?? self.defaultCallOptions, - interceptors: self.interceptors?.makeTalkInterceptors() ?? [] - ) - } - - public func makeTalkOneAnswerMoreCall( - _ request: Hello_TalkRequest, - callOptions: CallOptions? = nil - ) -> GRPCAsyncServerStreamingCall { - return self.makeAsyncServerStreamingCall( - path: Hello_LandingServiceClientMetadata.Methods.talkOneAnswerMore.path, - request: request, - callOptions: callOptions ?? self.defaultCallOptions, - interceptors: self.interceptors?.makeTalkOneAnswerMoreInterceptors() ?? [] - ) - } - - public func makeTalkMoreAnswerOneCall( - callOptions: CallOptions? = nil - ) -> GRPCAsyncClientStreamingCall { - return self.makeAsyncClientStreamingCall( - path: Hello_LandingServiceClientMetadata.Methods.talkMoreAnswerOne.path, - callOptions: callOptions ?? self.defaultCallOptions, - interceptors: self.interceptors?.makeTalkMoreAnswerOneInterceptors() ?? [] - ) - } - - public func makeTalkBidirectionalCall( - callOptions: CallOptions? = nil - ) -> GRPCAsyncBidirectionalStreamingCall { - return self.makeAsyncBidirectionalStreamingCall( - path: Hello_LandingServiceClientMetadata.Methods.talkBidirectional.path, - callOptions: callOptions ?? self.defaultCallOptions, - interceptors: self.interceptors?.makeTalkBidirectionalInterceptors() ?? [] - ) - } + public static var serviceDescriptor: GRPCServiceDescriptor { + return Hello_LandingServiceClientMetadata.serviceDescriptor + } + + public var interceptors: Hello_LandingServiceClientInterceptorFactoryProtocol? { + return nil + } + + public func makeTalkCall( + _ request: Hello_TalkRequest, + callOptions: CallOptions? = nil + ) -> GRPCAsyncUnaryCall { + return self.makeAsyncUnaryCall( + path: Hello_LandingServiceClientMetadata.Methods.talk.path, + request: request, + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeTalkInterceptors() ?? [] + ) + } + + public func makeTalkOneAnswerMoreCall( + _ request: Hello_TalkRequest, + callOptions: CallOptions? = nil + ) -> GRPCAsyncServerStreamingCall { + return self.makeAsyncServerStreamingCall( + path: Hello_LandingServiceClientMetadata.Methods.talkOneAnswerMore.path, + request: request, + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeTalkOneAnswerMoreInterceptors() ?? [] + ) + } + + public func makeTalkMoreAnswerOneCall( + callOptions: CallOptions? = nil + ) -> GRPCAsyncClientStreamingCall { + return self.makeAsyncClientStreamingCall( + path: Hello_LandingServiceClientMetadata.Methods.talkMoreAnswerOne.path, + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeTalkMoreAnswerOneInterceptors() ?? [] + ) + } + + public func makeTalkBidirectionalCall( + callOptions: CallOptions? = nil + ) -> GRPCAsyncBidirectionalStreamingCall { + return self.makeAsyncBidirectionalStreamingCall( + path: Hello_LandingServiceClientMetadata.Methods.talkBidirectional.path, + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeTalkBidirectionalInterceptors() ?? [] + ) + } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension Hello_LandingServiceAsyncClientProtocol { - public func talk( - _ request: Hello_TalkRequest, - callOptions: CallOptions? = nil - ) async throws -> Hello_TalkResponse { - return try await self.performAsyncUnaryCall( - path: Hello_LandingServiceClientMetadata.Methods.talk.path, - request: request, - callOptions: callOptions ?? self.defaultCallOptions, - interceptors: self.interceptors?.makeTalkInterceptors() ?? [] - ) - } - - public func talkOneAnswerMore( - _ request: Hello_TalkRequest, - callOptions: CallOptions? = nil - ) -> GRPCAsyncResponseStream { - return self.performAsyncServerStreamingCall( - path: Hello_LandingServiceClientMetadata.Methods.talkOneAnswerMore.path, - request: request, - callOptions: callOptions ?? self.defaultCallOptions, - interceptors: self.interceptors?.makeTalkOneAnswerMoreInterceptors() ?? [] - ) - } - - public func talkMoreAnswerOne( - _ requests: RequestStream, - callOptions: CallOptions? = nil - ) async throws -> Hello_TalkResponse where RequestStream: Sequence, RequestStream.Element == Hello_TalkRequest { - return try await self.performAsyncClientStreamingCall( - path: Hello_LandingServiceClientMetadata.Methods.talkMoreAnswerOne.path, - requests: requests, - callOptions: callOptions ?? self.defaultCallOptions, - interceptors: self.interceptors?.makeTalkMoreAnswerOneInterceptors() ?? [] - ) - } - - public func talkMoreAnswerOne( - _ requests: RequestStream, - callOptions: CallOptions? = nil - ) async throws -> Hello_TalkResponse where RequestStream: AsyncSequence & Sendable, RequestStream.Element == Hello_TalkRequest { - return try await self.performAsyncClientStreamingCall( - path: Hello_LandingServiceClientMetadata.Methods.talkMoreAnswerOne.path, - requests: requests, - callOptions: callOptions ?? self.defaultCallOptions, - interceptors: self.interceptors?.makeTalkMoreAnswerOneInterceptors() ?? [] - ) - } - - public func talkBidirectional( - _ requests: RequestStream, - callOptions: CallOptions? = nil - ) -> GRPCAsyncResponseStream where RequestStream: Sequence, RequestStream.Element == Hello_TalkRequest { - return self.performAsyncBidirectionalStreamingCall( - path: Hello_LandingServiceClientMetadata.Methods.talkBidirectional.path, - requests: requests, - callOptions: callOptions ?? self.defaultCallOptions, - interceptors: self.interceptors?.makeTalkBidirectionalInterceptors() ?? [] - ) - } - - public func talkBidirectional( - _ requests: RequestStream, - callOptions: CallOptions? = nil - ) -> GRPCAsyncResponseStream where RequestStream: AsyncSequence & Sendable, RequestStream.Element == Hello_TalkRequest { - return self.performAsyncBidirectionalStreamingCall( - path: Hello_LandingServiceClientMetadata.Methods.talkBidirectional.path, - requests: requests, - callOptions: callOptions ?? self.defaultCallOptions, - interceptors: self.interceptors?.makeTalkBidirectionalInterceptors() ?? [] - ) - } + public func talk( + _ request: Hello_TalkRequest, + callOptions: CallOptions? = nil + ) async throws -> Hello_TalkResponse { + return try await self.performAsyncUnaryCall( + path: Hello_LandingServiceClientMetadata.Methods.talk.path, + request: request, + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeTalkInterceptors() ?? [] + ) + } + + public func talkOneAnswerMore( + _ request: Hello_TalkRequest, + callOptions: CallOptions? = nil + ) -> GRPCAsyncResponseStream { + return self.performAsyncServerStreamingCall( + path: Hello_LandingServiceClientMetadata.Methods.talkOneAnswerMore.path, + request: request, + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeTalkOneAnswerMoreInterceptors() ?? [] + ) + } + + public func talkMoreAnswerOne( + _ requests: RequestStream, + callOptions: CallOptions? = nil + ) async throws -> Hello_TalkResponse where RequestStream: Sequence, RequestStream.Element == Hello_TalkRequest { + return try await self.performAsyncClientStreamingCall( + path: Hello_LandingServiceClientMetadata.Methods.talkMoreAnswerOne.path, + requests: requests, + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeTalkMoreAnswerOneInterceptors() ?? [] + ) + } + + public func talkMoreAnswerOne( + _ requests: RequestStream, + callOptions: CallOptions? = nil + ) async throws -> Hello_TalkResponse where RequestStream: AsyncSequence & Sendable, RequestStream.Element == Hello_TalkRequest { + return try await self.performAsyncClientStreamingCall( + path: Hello_LandingServiceClientMetadata.Methods.talkMoreAnswerOne.path, + requests: requests, + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeTalkMoreAnswerOneInterceptors() ?? [] + ) + } + + public func talkBidirectional( + _ requests: RequestStream, + callOptions: CallOptions? = nil + ) -> GRPCAsyncResponseStream where RequestStream: Sequence, RequestStream.Element == Hello_TalkRequest { + return self.performAsyncBidirectionalStreamingCall( + path: Hello_LandingServiceClientMetadata.Methods.talkBidirectional.path, + requests: requests, + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeTalkBidirectionalInterceptors() ?? [] + ) + } + + public func talkBidirectional( + _ requests: RequestStream, + callOptions: CallOptions? = nil + ) -> GRPCAsyncResponseStream where RequestStream: AsyncSequence & Sendable, RequestStream.Element == Hello_TalkRequest { + return self.performAsyncBidirectionalStreamingCall( + path: Hello_LandingServiceClientMetadata.Methods.talkBidirectional.path, + requests: requests, + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeTalkBidirectionalInterceptors() ?? [] + ) + } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public struct Hello_LandingServiceAsyncClient: Hello_LandingServiceAsyncClientProtocol { - public var channel: GRPCChannel - public var defaultCallOptions: CallOptions - public var interceptors: Hello_LandingServiceClientInterceptorFactoryProtocol? - - public init( - channel: GRPCChannel, - defaultCallOptions: CallOptions = CallOptions(), - interceptors: Hello_LandingServiceClientInterceptorFactoryProtocol? = nil - ) { - self.channel = channel - self.defaultCallOptions = defaultCallOptions - self.interceptors = interceptors - } + public var channel: GRPCChannel + public var defaultCallOptions: CallOptions + public var interceptors: Hello_LandingServiceClientInterceptorFactoryProtocol? + + public init( + channel: GRPCChannel, + defaultCallOptions: CallOptions = CallOptions(), + interceptors: Hello_LandingServiceClientInterceptorFactoryProtocol? = nil + ) { + self.channel = channel + self.defaultCallOptions = defaultCallOptions + self.interceptors = interceptors + } } public protocol Hello_LandingServiceClientInterceptorFactoryProtocol: Sendable { - /// - Returns: Interceptors to use when invoking 'talk'. - func makeTalkInterceptors() -> [ClientInterceptor] + /// - Returns: Interceptors to use when invoking 'talk'. + func makeTalkInterceptors() -> [ClientInterceptor] - /// - Returns: Interceptors to use when invoking 'talkOneAnswerMore'. - func makeTalkOneAnswerMoreInterceptors() -> [ClientInterceptor] + /// - Returns: Interceptors to use when invoking 'talkOneAnswerMore'. + func makeTalkOneAnswerMoreInterceptors() -> [ClientInterceptor] - /// - Returns: Interceptors to use when invoking 'talkMoreAnswerOne'. - func makeTalkMoreAnswerOneInterceptors() -> [ClientInterceptor] + /// - Returns: Interceptors to use when invoking 'talkMoreAnswerOne'. + func makeTalkMoreAnswerOneInterceptors() -> [ClientInterceptor] - /// - Returns: Interceptors to use when invoking 'talkBidirectional'. - func makeTalkBidirectionalInterceptors() -> [ClientInterceptor] + /// - Returns: Interceptors to use when invoking 'talkBidirectional'. + func makeTalkBidirectionalInterceptors() -> [ClientInterceptor] } public enum Hello_LandingServiceClientMetadata { - public static let serviceDescriptor = GRPCServiceDescriptor( - name: "LandingService", - fullName: "hello.LandingService", - methods: [ - Hello_LandingServiceClientMetadata.Methods.talk, - Hello_LandingServiceClientMetadata.Methods.talkOneAnswerMore, - Hello_LandingServiceClientMetadata.Methods.talkMoreAnswerOne, - Hello_LandingServiceClientMetadata.Methods.talkBidirectional, - ] + public static let serviceDescriptor = GRPCServiceDescriptor( + name: "LandingService", + fullName: "hello.LandingService", + methods: [ + Hello_LandingServiceClientMetadata.Methods.talk, + Hello_LandingServiceClientMetadata.Methods.talkOneAnswerMore, + Hello_LandingServiceClientMetadata.Methods.talkMoreAnswerOne, + Hello_LandingServiceClientMetadata.Methods.talkBidirectional, + ] + ) + + public enum Methods { + public static let talk = GRPCMethodDescriptor( + name: "Talk", + path: "/hello.LandingService/Talk", + type: GRPCCallType.unary ) - public enum Methods { - public static let talk = GRPCMethodDescriptor( - name: "Talk", - path: "/hello.LandingService/Talk", - type: GRPCCallType.unary - ) - - public static let talkOneAnswerMore = GRPCMethodDescriptor( - name: "TalkOneAnswerMore", - path: "/hello.LandingService/TalkOneAnswerMore", - type: GRPCCallType.serverStreaming - ) - - public static let talkMoreAnswerOne = GRPCMethodDescriptor( - name: "TalkMoreAnswerOne", - path: "/hello.LandingService/TalkMoreAnswerOne", - type: GRPCCallType.clientStreaming - ) - - public static let talkBidirectional = GRPCMethodDescriptor( - name: "TalkBidirectional", - path: "/hello.LandingService/TalkBidirectional", - type: GRPCCallType.bidirectionalStreaming - ) - } + public static let talkOneAnswerMore = GRPCMethodDescriptor( + name: "TalkOneAnswerMore", + path: "/hello.LandingService/TalkOneAnswerMore", + type: GRPCCallType.serverStreaming + ) + + public static let talkMoreAnswerOne = GRPCMethodDescriptor( + name: "TalkMoreAnswerOne", + path: "/hello.LandingService/TalkMoreAnswerOne", + type: GRPCCallType.clientStreaming + ) + + public static let talkBidirectional = GRPCMethodDescriptor( + name: "TalkBidirectional", + path: "/hello.LandingService/TalkBidirectional", + type: GRPCCallType.bidirectionalStreaming + ) + } } /// To build a server, implement a class that conforms to this protocol. public protocol Hello_LandingServiceProvider: CallHandlerProvider { - var interceptors: Hello_LandingServiceServerInterceptorFactoryProtocol? { get } + var interceptors: Hello_LandingServiceServerInterceptorFactoryProtocol? { get } - ///Unary RPC - func talk(request: Hello_TalkRequest, context: StatusOnlyCallContext) -> EventLoopFuture + ///Unary RPC + func talk(request: Hello_TalkRequest, context: StatusOnlyCallContext) -> EventLoopFuture - ///Server streaming RPC - func talkOneAnswerMore(request: Hello_TalkRequest, context: StreamingResponseCallContext) -> EventLoopFuture + ///Server streaming RPC + func talkOneAnswerMore(request: Hello_TalkRequest, context: StreamingResponseCallContext) -> EventLoopFuture - ///Client streaming RPC with random & sleep - func talkMoreAnswerOne(context: UnaryResponseCallContext) -> EventLoopFuture<(StreamEvent) -> Void> + ///Client streaming RPC with random & sleep + func talkMoreAnswerOne(context: UnaryResponseCallContext) -> EventLoopFuture<(StreamEvent) -> Void> - ///Bidirectional streaming RPC - func talkBidirectional(context: StreamingResponseCallContext) -> EventLoopFuture<(StreamEvent) -> Void> + ///Bidirectional streaming RPC + func talkBidirectional(context: StreamingResponseCallContext) -> EventLoopFuture<(StreamEvent) -> Void> } extension Hello_LandingServiceProvider { - public var serviceName: Substring { - return Hello_LandingServiceServerMetadata.serviceDescriptor.fullName[...] - } - - /// Determines, calls and returns the appropriate request handler, depending on the request's method. - /// Returns nil for methods not handled by this service. - public func handle( - method name: Substring, - context: CallHandlerContext - ) -> GRPCServerHandlerProtocol? { - switch name { - case "Talk": - return UnaryServerHandler( - context: context, - requestDeserializer: ProtobufDeserializer(), - responseSerializer: ProtobufSerializer(), - interceptors: self.interceptors?.makeTalkInterceptors() ?? [], - userFunction: self.talk(request:context:) - ) - - case "TalkOneAnswerMore": - return ServerStreamingServerHandler( - context: context, - requestDeserializer: ProtobufDeserializer(), - responseSerializer: ProtobufSerializer(), - interceptors: self.interceptors?.makeTalkOneAnswerMoreInterceptors() ?? [], - userFunction: self.talkOneAnswerMore(request:context:) - ) - - case "TalkMoreAnswerOne": - return ClientStreamingServerHandler( - context: context, - requestDeserializer: ProtobufDeserializer(), - responseSerializer: ProtobufSerializer(), - interceptors: self.interceptors?.makeTalkMoreAnswerOneInterceptors() ?? [], - observerFactory: self.talkMoreAnswerOne(context:) - ) - - case "TalkBidirectional": - return BidirectionalStreamingServerHandler( - context: context, - requestDeserializer: ProtobufDeserializer(), - responseSerializer: ProtobufSerializer(), - interceptors: self.interceptors?.makeTalkBidirectionalInterceptors() ?? [], - observerFactory: self.talkBidirectional(context:) - ) - - default: - return nil - } + public var serviceName: Substring { + return Hello_LandingServiceServerMetadata.serviceDescriptor.fullName[...] + } + + /// Determines, calls and returns the appropriate request handler, depending on the request's method. + /// Returns nil for methods not handled by this service. + public func handle( + method name: Substring, + context: CallHandlerContext + ) -> GRPCServerHandlerProtocol? { + switch name { + case "Talk": + return UnaryServerHandler( + context: context, + requestDeserializer: ProtobufDeserializer(), + responseSerializer: ProtobufSerializer(), + interceptors: self.interceptors?.makeTalkInterceptors() ?? [], + userFunction: self.talk(request:context:) + ) + + case "TalkOneAnswerMore": + return ServerStreamingServerHandler( + context: context, + requestDeserializer: ProtobufDeserializer(), + responseSerializer: ProtobufSerializer(), + interceptors: self.interceptors?.makeTalkOneAnswerMoreInterceptors() ?? [], + userFunction: self.talkOneAnswerMore(request:context:) + ) + + case "TalkMoreAnswerOne": + return ClientStreamingServerHandler( + context: context, + requestDeserializer: ProtobufDeserializer(), + responseSerializer: ProtobufSerializer(), + interceptors: self.interceptors?.makeTalkMoreAnswerOneInterceptors() ?? [], + observerFactory: self.talkMoreAnswerOne(context:) + ) + + case "TalkBidirectional": + return BidirectionalStreamingServerHandler( + context: context, + requestDeserializer: ProtobufDeserializer(), + responseSerializer: ProtobufSerializer(), + interceptors: self.interceptors?.makeTalkBidirectionalInterceptors() ?? [], + observerFactory: self.talkBidirectional(context:) + ) + + default: + return nil } + } } /// To implement a server, implement an object which conforms to this protocol. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) public protocol Hello_LandingServiceAsyncProvider: CallHandlerProvider, Sendable { - static var serviceDescriptor: GRPCServiceDescriptor { get } - var interceptors: Hello_LandingServiceServerInterceptorFactoryProtocol? { get } - - ///Unary RPC - func talk( - request: Hello_TalkRequest, - context: GRPCAsyncServerCallContext - ) async throws -> Hello_TalkResponse - - ///Server streaming RPC - func talkOneAnswerMore( - request: Hello_TalkRequest, - responseStream: GRPCAsyncResponseStreamWriter, - context: GRPCAsyncServerCallContext - ) async throws - - ///Client streaming RPC with random & sleep - func talkMoreAnswerOne( - requestStream: GRPCAsyncRequestStream, - context: GRPCAsyncServerCallContext - ) async throws -> Hello_TalkResponse - - ///Bidirectional streaming RPC - func talkBidirectional( - requestStream: GRPCAsyncRequestStream, - responseStream: GRPCAsyncResponseStreamWriter, - context: GRPCAsyncServerCallContext - ) async throws + static var serviceDescriptor: GRPCServiceDescriptor { get } + var interceptors: Hello_LandingServiceServerInterceptorFactoryProtocol? { get } + + ///Unary RPC + func talk( + request: Hello_TalkRequest, + context: GRPCAsyncServerCallContext + ) async throws -> Hello_TalkResponse + + ///Server streaming RPC + func talkOneAnswerMore( + request: Hello_TalkRequest, + responseStream: GRPCAsyncResponseStreamWriter, + context: GRPCAsyncServerCallContext + ) async throws + + ///Client streaming RPC with random & sleep + func talkMoreAnswerOne( + requestStream: GRPCAsyncRequestStream, + context: GRPCAsyncServerCallContext + ) async throws -> Hello_TalkResponse + + ///Bidirectional streaming RPC + func talkBidirectional( + requestStream: GRPCAsyncRequestStream, + responseStream: GRPCAsyncResponseStreamWriter, + context: GRPCAsyncServerCallContext + ) async throws } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension Hello_LandingServiceAsyncProvider { - public static var serviceDescriptor: GRPCServiceDescriptor { - return Hello_LandingServiceServerMetadata.serviceDescriptor - } - - public var serviceName: Substring { - return Hello_LandingServiceServerMetadata.serviceDescriptor.fullName[...] - } - - public var interceptors: Hello_LandingServiceServerInterceptorFactoryProtocol? { - return nil - } - - public func handle( - method name: Substring, - context: CallHandlerContext - ) -> GRPCServerHandlerProtocol? { - switch name { - case "Talk": - return GRPCAsyncServerHandler( - context: context, - requestDeserializer: ProtobufDeserializer(), - responseSerializer: ProtobufSerializer(), - interceptors: self.interceptors?.makeTalkInterceptors() ?? [], - wrapping: { try await self.talk(request: $0, context: $1) } - ) - - case "TalkOneAnswerMore": - return GRPCAsyncServerHandler( - context: context, - requestDeserializer: ProtobufDeserializer(), - responseSerializer: ProtobufSerializer(), - interceptors: self.interceptors?.makeTalkOneAnswerMoreInterceptors() ?? [], - wrapping: { try await self.talkOneAnswerMore(request: $0, responseStream: $1, context: $2) } - ) - - case "TalkMoreAnswerOne": - return GRPCAsyncServerHandler( - context: context, - requestDeserializer: ProtobufDeserializer(), - responseSerializer: ProtobufSerializer(), - interceptors: self.interceptors?.makeTalkMoreAnswerOneInterceptors() ?? [], - wrapping: { try await self.talkMoreAnswerOne(requestStream: $0, context: $1) } - ) - - case "TalkBidirectional": - return GRPCAsyncServerHandler( - context: context, - requestDeserializer: ProtobufDeserializer(), - responseSerializer: ProtobufSerializer(), - interceptors: self.interceptors?.makeTalkBidirectionalInterceptors() ?? [], - wrapping: { try await self.talkBidirectional(requestStream: $0, responseStream: $1, context: $2) } - ) - - default: - return nil - } + public static var serviceDescriptor: GRPCServiceDescriptor { + return Hello_LandingServiceServerMetadata.serviceDescriptor + } + + public var serviceName: Substring { + return Hello_LandingServiceServerMetadata.serviceDescriptor.fullName[...] + } + + public var interceptors: Hello_LandingServiceServerInterceptorFactoryProtocol? { + return nil + } + + public func handle( + method name: Substring, + context: CallHandlerContext + ) -> GRPCServerHandlerProtocol? { + switch name { + case "Talk": + return GRPCAsyncServerHandler( + context: context, + requestDeserializer: ProtobufDeserializer(), + responseSerializer: ProtobufSerializer(), + interceptors: self.interceptors?.makeTalkInterceptors() ?? [], + wrapping: { try await self.talk(request: $0, context: $1) } + ) + + case "TalkOneAnswerMore": + return GRPCAsyncServerHandler( + context: context, + requestDeserializer: ProtobufDeserializer(), + responseSerializer: ProtobufSerializer(), + interceptors: self.interceptors?.makeTalkOneAnswerMoreInterceptors() ?? [], + wrapping: { try await self.talkOneAnswerMore(request: $0, responseStream: $1, context: $2) } + ) + + case "TalkMoreAnswerOne": + return GRPCAsyncServerHandler( + context: context, + requestDeserializer: ProtobufDeserializer(), + responseSerializer: ProtobufSerializer(), + interceptors: self.interceptors?.makeTalkMoreAnswerOneInterceptors() ?? [], + wrapping: { try await self.talkMoreAnswerOne(requestStream: $0, context: $1) } + ) + + case "TalkBidirectional": + return GRPCAsyncServerHandler( + context: context, + requestDeserializer: ProtobufDeserializer(), + responseSerializer: ProtobufSerializer(), + interceptors: self.interceptors?.makeTalkBidirectionalInterceptors() ?? [], + wrapping: { try await self.talkBidirectional(requestStream: $0, responseStream: $1, context: $2) } + ) + + default: + return nil } + } } public protocol Hello_LandingServiceServerInterceptorFactoryProtocol: Sendable { - /// - Returns: Interceptors to use when handling 'talk'. - /// Defaults to calling `self.makeInterceptors()`. - func makeTalkInterceptors() -> [ServerInterceptor] + /// - Returns: Interceptors to use when handling 'talk'. + /// Defaults to calling `self.makeInterceptors()`. + func makeTalkInterceptors() -> [ServerInterceptor] - /// - Returns: Interceptors to use when handling 'talkOneAnswerMore'. - /// Defaults to calling `self.makeInterceptors()`. - func makeTalkOneAnswerMoreInterceptors() -> [ServerInterceptor] + /// - Returns: Interceptors to use when handling 'talkOneAnswerMore'. + /// Defaults to calling `self.makeInterceptors()`. + func makeTalkOneAnswerMoreInterceptors() -> [ServerInterceptor] - /// - Returns: Interceptors to use when handling 'talkMoreAnswerOne'. - /// Defaults to calling `self.makeInterceptors()`. - func makeTalkMoreAnswerOneInterceptors() -> [ServerInterceptor] + /// - Returns: Interceptors to use when handling 'talkMoreAnswerOne'. + /// Defaults to calling `self.makeInterceptors()`. + func makeTalkMoreAnswerOneInterceptors() -> [ServerInterceptor] - /// - Returns: Interceptors to use when handling 'talkBidirectional'. - /// Defaults to calling `self.makeInterceptors()`. - func makeTalkBidirectionalInterceptors() -> [ServerInterceptor] + /// - Returns: Interceptors to use when handling 'talkBidirectional'. + /// Defaults to calling `self.makeInterceptors()`. + func makeTalkBidirectionalInterceptors() -> [ServerInterceptor] } public enum Hello_LandingServiceServerMetadata { - public static let serviceDescriptor = GRPCServiceDescriptor( - name: "LandingService", - fullName: "hello.LandingService", - methods: [ - Hello_LandingServiceServerMetadata.Methods.talk, - Hello_LandingServiceServerMetadata.Methods.talkOneAnswerMore, - Hello_LandingServiceServerMetadata.Methods.talkMoreAnswerOne, - Hello_LandingServiceServerMetadata.Methods.talkBidirectional, - ] + public static let serviceDescriptor = GRPCServiceDescriptor( + name: "LandingService", + fullName: "hello.LandingService", + methods: [ + Hello_LandingServiceServerMetadata.Methods.talk, + Hello_LandingServiceServerMetadata.Methods.talkOneAnswerMore, + Hello_LandingServiceServerMetadata.Methods.talkMoreAnswerOne, + Hello_LandingServiceServerMetadata.Methods.talkBidirectional, + ] + ) + + public enum Methods { + public static let talk = GRPCMethodDescriptor( + name: "Talk", + path: "/hello.LandingService/Talk", + type: GRPCCallType.unary ) - public enum Methods { - public static let talk = GRPCMethodDescriptor( - name: "Talk", - path: "/hello.LandingService/Talk", - type: GRPCCallType.unary - ) - - public static let talkOneAnswerMore = GRPCMethodDescriptor( - name: "TalkOneAnswerMore", - path: "/hello.LandingService/TalkOneAnswerMore", - type: GRPCCallType.serverStreaming - ) - - public static let talkMoreAnswerOne = GRPCMethodDescriptor( - name: "TalkMoreAnswerOne", - path: "/hello.LandingService/TalkMoreAnswerOne", - type: GRPCCallType.clientStreaming - ) - - public static let talkBidirectional = GRPCMethodDescriptor( - name: "TalkBidirectional", - path: "/hello.LandingService/TalkBidirectional", - type: GRPCCallType.bidirectionalStreaming - ) - } + public static let talkOneAnswerMore = GRPCMethodDescriptor( + name: "TalkOneAnswerMore", + path: "/hello.LandingService/TalkOneAnswerMore", + type: GRPCCallType.serverStreaming + ) + + public static let talkMoreAnswerOne = GRPCMethodDescriptor( + name: "TalkMoreAnswerOne", + path: "/hello.LandingService/TalkMoreAnswerOne", + type: GRPCCallType.clientStreaming + ) + + public static let talkBidirectional = GRPCMethodDescriptor( + name: "TalkBidirectional", + path: "/hello.LandingService/TalkBidirectional", + type: GRPCCallType.bidirectionalStreaming + ) + } } diff --git a/hello-grpc-swift/Sources/Common/landing.pb.swift b/hello-grpc-swift/Sources/Common/landing.pb.swift index 342b7d0..db22ed8 100644 --- a/hello-grpc-swift/Sources/Common/landing.pb.swift +++ b/hello-grpc-swift/Sources/Common/landing.pb.swift @@ -1,5 +1,6 @@ // DO NOT EDIT. // swift-format-ignore-file +// swiftlint:disable all // // Generated by the Swift generator plugin for the protocol buffer compiler. // Source: landing.proto @@ -7,7 +8,6 @@ // For information on using the generated types, please see the documentation: // https://github.com/apple/swift-protobuf/ -import Foundation import SwiftProtobuf // If the compiler emits an error on this type, it is because this file @@ -16,282 +16,223 @@ import SwiftProtobuf // Please ensure that you are building against the same version of the API // that was used to generate this file. fileprivate struct _GeneratedWithProtocGenSwiftVersion: SwiftProtobuf.ProtobufAPIVersionCheck { - struct _2: SwiftProtobuf.ProtobufAPIVersion_2 { - } - - typealias Version = _2 + struct _2: SwiftProtobuf.ProtobufAPIVersion_2 {} + typealias Version = _2 } -public enum Hello_ResultType: SwiftProtobuf.Enum { - public typealias RawValue = Int - case ok // = 0 - case fail // = 1 - case UNRECOGNIZED(Int) +public enum Hello_ResultType: SwiftProtobuf.Enum, Swift.CaseIterable { + public typealias RawValue = Int + case ok // = 0 + case fail // = 1 + case UNRECOGNIZED(Int) - public init() { - self = .ok - } + public init() { + self = .ok + } - public init?(rawValue: Int) { - switch rawValue { - case 0: self = .ok - case 1: self = .fail - default: self = .UNRECOGNIZED(rawValue) - } + public init?(rawValue: Int) { + switch rawValue { + case 0: self = .ok + case 1: self = .fail + default: self = .UNRECOGNIZED(rawValue) } + } - public var rawValue: Int { - switch self { - case .ok: return 0 - case .fail: return 1 - case .UNRECOGNIZED(let i): return i - } + public var rawValue: Int { + switch self { + case .ok: return 0 + case .fail: return 1 + case .UNRECOGNIZED(let i): return i } + } -} - -#if swift(>=4.2) + // The compiler won't synthesize support with the UNRECOGNIZED case. + public static let allCases: [Hello_ResultType] = [ + .ok, + .fail, + ] -extension Hello_ResultType: CaseIterable { - // The compiler won't synthesize support with the UNRECOGNIZED case. - public static let allCases: [Hello_ResultType] = [ - .ok, - .fail, - ] } -#endif // swift(>=4.2) - -public struct Hello_TalkRequest { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. +public struct Hello_TalkRequest: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. - ///language index - public var data: String = String() + ///language index + public var data: String = String() - ///clientside language - public var meta: String = String() + ///clientside language + public var meta: String = String() - public var unknownFields = SwiftProtobuf.UnknownStorage() + public var unknownFields = SwiftProtobuf.UnknownStorage() - public init() { - } + public init() {} } -public struct Hello_TalkResponse { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. +public struct Hello_TalkResponse: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. - public var status: Int32 = 0 + public var status: Int32 = 0 - public var results: [Hello_TalkResult] = [] + public var results: [Hello_TalkResult] = [] - public var unknownFields = SwiftProtobuf.UnknownStorage() + public var unknownFields = SwiftProtobuf.UnknownStorage() - public init() { - } + public init() {} } -public struct Hello_TalkResult { - // SwiftProtobuf.Message conformance is added in an extension below. See the - // `Message` and `Message+*Additions` files in the SwiftProtobuf library for - // methods supported on all messages. +public struct Hello_TalkResult: Sendable { + // SwiftProtobuf.Message conformance is added in an extension below. See the + // `Message` and `Message+*Additions` files in the SwiftProtobuf library for + // methods supported on all messages. - ///timestamp - public var id: Int64 = 0 + ///timestamp + public var id: Int64 = 0 - ///enum - public var type: Hello_ResultType = .ok + ///enum + public var type: Hello_ResultType = .ok - /// id:result uuid - /// idx:language index - /// data: hello - /// meta: serverside language - public var kv: Dictionary = [:] - - public var unknownFields = SwiftProtobuf.UnknownStorage() - - public init() { - } -} - -#if swift(>=5.5) && canImport(_Concurrency) -extension Hello_ResultType: @unchecked Sendable { -} - -extension Hello_TalkRequest: @unchecked Sendable { -} + /// id:result uuid + /// idx:language index + /// data: hello + /// meta: serverside language + public var kv: Dictionary = [:] -extension Hello_TalkResponse: @unchecked Sendable { -} + public var unknownFields = SwiftProtobuf.UnknownStorage() -extension Hello_TalkResult: @unchecked Sendable { + public init() {} } -#endif // swift(>=5.5) && canImport(_Concurrency) // MARK: - Code below here is support for the SwiftProtobuf runtime. fileprivate let _protobuf_package = "hello" extension Hello_ResultType: SwiftProtobuf._ProtoNameProviding { - public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 0: .same(proto: "OK"), - 1: .same(proto: "FAIL"), - ] + public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 0: .same(proto: "OK"), + 1: .same(proto: "FAIL"), + ] } extension Hello_TalkRequest: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - public static let protoMessageName: String = _protobuf_package + ".TalkRequest" - public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "data"), - 2: .same(proto: "meta"), - ] - - public mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try { - try decoder.decodeSingularStringField(value: &self.data) - }() - case 2: try { - try decoder.decodeSingularStringField(value: &self.meta) - }() - default: break - } - } - } - - public func traverse(visitor: inout V) throws { - if !self.data.isEmpty { - try visitor.visitSingularStringField(value: self.data, fieldNumber: 1) - } - if !self.meta.isEmpty { - try visitor.visitSingularStringField(value: self.meta, fieldNumber: 2) - } - try unknownFields.traverse(visitor: &visitor) - } - - public static func ==(lhs: Hello_TalkRequest, rhs: Hello_TalkRequest) -> Bool { - if lhs.data != rhs.data { - return false - } - if lhs.meta != rhs.meta { - return false - } - if lhs.unknownFields != rhs.unknownFields { - return false - } - return true - } + public static let protoMessageName: String = _protobuf_package + ".TalkRequest" + public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .same(proto: "data"), + 2: .same(proto: "meta"), + ] + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularStringField(value: &self.data) }() + case 2: try { try decoder.decodeSingularStringField(value: &self.meta) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if !self.data.isEmpty { + try visitor.visitSingularStringField(value: self.data, fieldNumber: 1) + } + if !self.meta.isEmpty { + try visitor.visitSingularStringField(value: self.meta, fieldNumber: 2) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Hello_TalkRequest, rhs: Hello_TalkRequest) -> Bool { + if lhs.data != rhs.data {return false} + if lhs.meta != rhs.meta {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } } extension Hello_TalkResponse: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - public static let protoMessageName: String = _protobuf_package + ".TalkResponse" - public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "status"), - 2: .same(proto: "results"), - ] - - public mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try { - try decoder.decodeSingularInt32Field(value: &self.status) - }() - case 2: try { - try decoder.decodeRepeatedMessageField(value: &self.results) - }() - default: break - } - } - } - - public func traverse(visitor: inout V) throws { - if self.status != 0 { - try visitor.visitSingularInt32Field(value: self.status, fieldNumber: 1) - } - if !self.results.isEmpty { - try visitor.visitRepeatedMessageField(value: self.results, fieldNumber: 2) - } - try unknownFields.traverse(visitor: &visitor) - } - - public static func ==(lhs: Hello_TalkResponse, rhs: Hello_TalkResponse) -> Bool { - if lhs.status != rhs.status { - return false - } - if lhs.results != rhs.results { - return false - } - if lhs.unknownFields != rhs.unknownFields { - return false - } - return true - } + public static let protoMessageName: String = _protobuf_package + ".TalkResponse" + public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .same(proto: "status"), + 2: .same(proto: "results"), + ] + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularInt32Field(value: &self.status) }() + case 2: try { try decoder.decodeRepeatedMessageField(value: &self.results) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if self.status != 0 { + try visitor.visitSingularInt32Field(value: self.status, fieldNumber: 1) + } + if !self.results.isEmpty { + try visitor.visitRepeatedMessageField(value: self.results, fieldNumber: 2) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Hello_TalkResponse, rhs: Hello_TalkResponse) -> Bool { + if lhs.status != rhs.status {return false} + if lhs.results != rhs.results {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } } extension Hello_TalkResult: SwiftProtobuf.Message, SwiftProtobuf._MessageImplementationBase, SwiftProtobuf._ProtoNameProviding { - public static let protoMessageName: String = _protobuf_package + ".TalkResult" - public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ - 1: .same(proto: "id"), - 2: .same(proto: "type"), - 3: .same(proto: "kv"), - ] - - public mutating func decodeMessage(decoder: inout D) throws { - while let fieldNumber = try decoder.nextFieldNumber() { - // The use of inline closures is to circumvent an issue where the compiler - // allocates stack space for every case branch when no optimizations are - // enabled. https://github.com/apple/swift-protobuf/issues/1034 - switch fieldNumber { - case 1: try { - try decoder.decodeSingularInt64Field(value: &self.id) - }() - case 2: try { - try decoder.decodeSingularEnumField(value: &self.type) - }() - case 3: try { - try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.kv) - }() - default: break - } - } - } - - public func traverse(visitor: inout V) throws { - if self.id != 0 { - try visitor.visitSingularInt64Field(value: self.id, fieldNumber: 1) - } - if self.type != .ok { - try visitor.visitSingularEnumField(value: self.type, fieldNumber: 2) - } - if !self.kv.isEmpty { - try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.kv, fieldNumber: 3) - } - try unknownFields.traverse(visitor: &visitor) - } - - public static func ==(lhs: Hello_TalkResult, rhs: Hello_TalkResult) -> Bool { - if lhs.id != rhs.id { - return false - } - if lhs.type != rhs.type { - return false - } - if lhs.kv != rhs.kv { - return false - } - if lhs.unknownFields != rhs.unknownFields { - return false - } - return true - } + public static let protoMessageName: String = _protobuf_package + ".TalkResult" + public static let _protobuf_nameMap: SwiftProtobuf._NameMap = [ + 1: .same(proto: "id"), + 2: .same(proto: "type"), + 3: .same(proto: "kv"), + ] + + public mutating func decodeMessage(decoder: inout D) throws { + while let fieldNumber = try decoder.nextFieldNumber() { + // The use of inline closures is to circumvent an issue where the compiler + // allocates stack space for every case branch when no optimizations are + // enabled. https://github.com/apple/swift-protobuf/issues/1034 + switch fieldNumber { + case 1: try { try decoder.decodeSingularInt64Field(value: &self.id) }() + case 2: try { try decoder.decodeSingularEnumField(value: &self.type) }() + case 3: try { try decoder.decodeMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: &self.kv) }() + default: break + } + } + } + + public func traverse(visitor: inout V) throws { + if self.id != 0 { + try visitor.visitSingularInt64Field(value: self.id, fieldNumber: 1) + } + if self.type != .ok { + try visitor.visitSingularEnumField(value: self.type, fieldNumber: 2) + } + if !self.kv.isEmpty { + try visitor.visitMapField(fieldType: SwiftProtobuf._ProtobufMap.self, value: self.kv, fieldNumber: 3) + } + try unknownFields.traverse(visitor: &visitor) + } + + public static func ==(lhs: Hello_TalkResult, rhs: Hello_TalkResult) -> Bool { + if lhs.id != rhs.id {return false} + if lhs.type != rhs.type {return false} + if lhs.kv != rhs.kv {return false} + if lhs.unknownFields != rhs.unknownFields {return false} + return true + } } diff --git a/hello-grpc-swift/Sources/Server/HelloServer.swift b/hello-grpc-swift/Sources/Server/HelloServer.swift index bc6a8ed..9fea208 100644 --- a/hello-grpc-swift/Sources/Server/HelloServer.swift +++ b/hello-grpc-swift/Sources/Server/HelloServer.swift @@ -1,45 +1,50 @@ -import ArgumentParser - -import GRPC - -import HelloCommon - -import Logging - -import NIOCore - -import NIOPosix - -import struct Foundation.Data - -import struct Foundation.URL - -struct HelloServer: AsyncParsableCommand { - func run() async throws { - let logger = Logger(label: "HelloServer") - - // Create an event loop group for the server to run on. - let group: EventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount) - defer { - try! group.syncShutdownGracefully() +#if compiler(>=5.6) + import ArgumentParser + import struct Foundation.Data + import struct Foundation.URL + import GRPC + import HelloCommon + import Logging + import NIOCore + import NIOPosix + + @main + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + struct HelloServer: AsyncParsableCommand { + func run() async throws { + let logger = Logger(label: "HelloServer") + + // Create an event loop group for the server to run on. + let group: EventLoopGroup = MultiThreadedEventLoopGroup( + numberOfThreads: System.coreCount) + defer { + try! group.syncShutdownGracefully() + } + + // Create a provider using the features we read. + let provider = HelloServiceProvider() + let conn: Connection = HelloConn() + // Start the server and print its address once it has started. + let server = try await Server.insecure(group: group) + .withServiceProviders([provider]) + .bind(host: "0.0.0.0", port: conn.port) + .get() + + logger.info("server started on port \(server.channel.localAddress!.port!)") + + // Wait on the server's `onClose` future to stop the program from exiting. + try await server.onClose.get() } - // Create a provider using the features we read. - let provider = HelloServiceProvider() - let conn: Connection = HelloConn() - // Start the server and print its address once it has started. - let server = try await Server.insecure(group: group) - .withServiceProviders([provider]) - .bind(host: "0.0.0.0", port: conn.port) - .get() + init() {} - logger.info("server started on port \(server.channel.localAddress!.port!)") - - // Wait on the server's `onClose` future to stop the program from exiting. - try await server.onClose.get() + init(from _: Decoder) throws {} } - - init() {} - - init(from _: Decoder) throws {} -} +#else + @main + enum RouteGuide { + static func main() { + print("This example requires Swift >= 5.6") + } + } +#endif // compiler(>=5.6) diff --git a/hello-grpc-swift/Sources/Server/HelloServiceProvider.swift b/hello-grpc-swift/Sources/Server/HelloServiceProvider.swift index 9ed5aa8..0d9650b 100644 --- a/hello-grpc-swift/Sources/Server/HelloServiceProvider.swift +++ b/hello-grpc-swift/Sources/Server/HelloServiceProvider.swift @@ -1,107 +1,106 @@ import Foundation - import GRPC - import HelloCommon - import Logging - import NIOConcurrencyHelpers - import NIOCore -final class HelloServiceProvider: Hello_LandingServiceAsyncProvider { - let logger = Logger(label: "HelloService") - - init() {} +#if compiler(>=5.6) - // 1 - func talk( - request: Hello_TalkRequest, - context: GRPCAsyncServerCallContext - ) async throws -> Hello_TalkResponse { - let headers = context.request.headers - logger.info("talk headers: \(headers)") + @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) + final class HelloServiceProvider: Hello_LandingServiceAsyncProvider { + let logger = Logger(label: "HelloService") - return .with { - $0.status = 200 - $0.results = [buildResult(rid: request.data)] - } - } + init() {} - // 2 - func talkOneAnswerMore( - request: Hello_TalkRequest, - responseStream: GRPCAsyncResponseStreamWriter, - context: GRPCAsyncServerCallContext - ) async throws { - let headers = context.request.headers - logger.info("talkOneAnswerMore headers: \(headers)") + // 1 + func talk( + request: Hello_TalkRequest, + context: GRPCAsyncServerCallContext + ) async throws -> Hello_TalkResponse { + let headers = context.request.headers + logger.info("talk headers: \(headers)") - let datas: [String] = request.data.components(separatedBy: ",") - for d in datas { - try await responseStream.send( - .with { - $0.status = 200 - $0.results = [buildResult(rid: d)] - }) + return .with { + $0.status = 200 + $0.results = [buildResult(rid: request.data)] + } } - } - - // 3 - func talkMoreAnswerOne( - requestStream requests: GRPCAsyncRequestStream, - context: GRPCAsyncServerCallContext - ) async throws -> Hello_TalkResponse { - let headers = context.request.headers - logger.info("talkMoreAnswerOne headers: \(headers)") - var results: [Hello_TalkResult] = [] - for try await request in requests { - results.append(buildResult(rid: request.data)) + // 2 + func talkOneAnswerMore( + request: Hello_TalkRequest, + responseStream: GRPCAsyncResponseStreamWriter, + context: GRPCAsyncServerCallContext + ) async throws { + let headers = context.request.headers + logger.info("talkOneAnswerMore headers: \(headers)") + + let datas: [String] = request.data.components(separatedBy: ",") + for d in datas { + try await responseStream.send( + .with { + $0.status = 200 + $0.results = [buildResult(rid: d)] + }) + } } - return .with { - $0.status = 200 - $0.results = results - } - } - // 4 - func talkBidirectional( - requestStream: GRPCAsyncRequestStream, - responseStream: GRPCAsyncResponseStreamWriter, - context: GRPCAsyncServerCallContext - ) async throws { - let headers = context.request.headers - logger.info("talkBidirectional headers: \(headers)") + // 3 + func talkMoreAnswerOne( + requestStream requests: GRPCAsyncRequestStream, + context: GRPCAsyncServerCallContext + ) async throws -> Hello_TalkResponse { + let headers = context.request.headers + logger.info("talkMoreAnswerOne headers: \(headers)") + + var results: [Hello_TalkResult] = [] + for try await request in requests { + results.append(buildResult(rid: request.data)) + } + return .with { + $0.status = 200 + $0.results = results + } + } - for try await request in requestStream { - logger.info("received: \(request)") - let result = buildResult(rid: request.data) - // var results : [Hello_TalkResult]=[] - // results.append(result) - try await responseStream.send( - .with { - $0.status = 200 - $0.results = [result] // results - }) + // 4 + func talkBidirectional( + requestStream: GRPCAsyncRequestStream, + responseStream: GRPCAsyncResponseStreamWriter, + context: GRPCAsyncServerCallContext + ) async throws { + let headers = context.request.headers + logger.info("talkBidirectional headers: \(headers)") + + for try await request in requestStream { + logger.info("received: \(request)") + let result = buildResult(rid: request.data) + // var results : [Hello_TalkResult]=[] + // results.append(result) + try await responseStream.send( + .with { + $0.status = 200 + $0.results = [result] // results + }) + } } - } - func buildResult(rid: String) -> Hello_TalkResult { - let index = Int(rid) ?? 0 - var kv: [String: String] = [:] - kv["id"] = "" - kv["idx"] = rid - let hello: String = Utils.helloList[index] - kv["data"] = hello + "," + Utils.ansMap[hello]! - kv["meta"] = "SWIFT" - var result = Hello_TalkResult() - let now = Date() - let timeInterval: TimeInterval = now.timeIntervalSince1970 - result.id = Int64(timeInterval) - result.type = .ok - result.kv = kv - return result + func buildResult(rid: String) -> Hello_TalkResult { + let index = Int(rid) ?? 0 + var kv: [String: String] = [:] + kv["id"] = "" + kv["idx"] = rid + let hello: String = Utils.helloList[index] + kv["data"] = hello + "," + Utils.ansMap[hello]! + kv["meta"] = "SWIFT" + var result = Hello_TalkResult() + let now = Date() + let timeInterval: TimeInterval = now.timeIntervalSince1970 + result.id = Int64(timeInterval) + result.type = .ok + result.kv = kv + return result + } } -} +#endif // compiler(>=5.6) diff --git a/hello-grpc-swift/doc/create_symlink.md b/hello-grpc-swift/doc/create_symlink.md new file mode 100644 index 0000000..ac32638 --- /dev/null +++ b/hello-grpc-swift/doc/create_symlink.md @@ -0,0 +1,8 @@ +# unable to create symlink + +```sh +error: unable to create symlink Tests/NIOFileSystemIntegrationTests/Test Data/Foo.symlink: Permission denied +``` + +1. +2. Run PowerShell As adminstrator diff --git a/hello-grpc-swift/fmt.sh b/hello-grpc-swift/fmt.sh index 46e6a2e..a4cc373 100755 --- a/hello-grpc-swift/fmt.sh +++ b/hello-grpc-swift/fmt.sh @@ -6,4 +6,4 @@ cd "$( set -e # swiftformat --indent 4 --swiftversion 5.10 --exclude "**/*.grpc.swift,**/*.pb.swift" . -swift-format --indent 4 --swiftversion 6.0.1 --exclude "**/*.grpc.swift,**/*.pb.swift" . +swift-format --indent 2 --swiftversion 6.0.1 --exclude "**/*.grpc.swift,**/*.pb.swift" . diff --git a/hello-grpc-swift/proto2swift.sh b/hello-grpc-swift/proto2swift.sh index 5cfc25b..04e03c0 100755 --- a/hello-grpc-swift/proto2swift.sh +++ b/hello-grpc-swift/proto2swift.sh @@ -7,8 +7,13 @@ cd "$( cd Sources/Common || exit protoc landing.proto \ + --plugin="${protoc_generate_grpc_swift}" \ --proto_path=. \ - --swift_opt=Visibility=Public \ - --swift_out=. \ --grpc-swift_opt=Visibility=Public \ --grpc-swift_out=. + +protoc landing.proto \ + --plugin=${protoc_gen_swift} \ + --proto_path=. \ + --swift_opt=Visibility=Public \ + --swift_out=.