| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832 |
- /*
- * Copyright 2024, gRPC Authors All rights reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- extension ClosureInvocationDescription {
- /// ```
- /// { response in
- /// try response.message
- /// }
- /// ```
- static var defaultClientUnaryResponseHandler: Self {
- ClosureInvocationDescription(
- argumentNames: ["response"],
- body: [.expression(.try(.identifierPattern("response").dot("message")))]
- )
- }
- }
- extension FunctionSignatureDescription {
- /// ```
- /// func <Name><Result>(
- /// request: GRPCCore.ClientRequest<Input>,
- /// serializer: some GRPCCore.MessageSerializer<Input>,
- /// deserializer: some GRPCCore.MessageDeserializer<Output>,
- /// options: GRPCCore.CallOptions,
- /// onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse<Input>) async throws -> Result
- /// ) async throws -> Result where Result: Sendable
- /// ```
- static func clientMethod(
- accessLevel: AccessModifier? = nil,
- name: String,
- input: String,
- output: String,
- streamingInput: Bool,
- streamingOutput: Bool,
- includeDefaults: Bool,
- includeSerializers: Bool,
- namer: Namer = Namer()
- ) -> Self {
- var signature = FunctionSignatureDescription(
- accessModifier: accessLevel,
- kind: .function(name: name, isStatic: false),
- generics: [.member("Result")],
- parameters: [], // Populated below.
- keywords: [.async, .throws],
- returnType: .identifierPattern("Result"),
- whereClause: WhereClause(requirements: [.conformance("Result", "Sendable")])
- )
- signature.parameters.append(
- ParameterDescription(
- label: "request",
- type: namer.clientRequest(forType: input, isStreaming: streamingInput)
- )
- )
- if includeSerializers {
- signature.parameters.append(
- ParameterDescription(
- label: "serializer",
- // Type is optional, so be explicit about which 'some' to use
- type: ExistingTypeDescription.some(namer.serializer(forType: input))
- )
- )
- signature.parameters.append(
- ParameterDescription(
- label: "deserializer",
- // Type is optional, so be explicit about which 'some' to use
- type: ExistingTypeDescription.some(namer.deserializer(forType: output))
- )
- )
- }
- signature.parameters.append(
- ParameterDescription(
- label: "options",
- type: namer.callOptions,
- defaultValue: includeDefaults ? .memberAccess(.dot("defaults")) : nil
- )
- )
- signature.parameters.append(
- ParameterDescription(
- label: "onResponse",
- name: "handleResponse",
- type: .closure(
- ClosureSignatureDescription(
- parameters: [
- ParameterDescription(
- type: namer.clientResponse(forType: output, isStreaming: streamingOutput)
- )
- ],
- keywords: [.async, .throws],
- returnType: .identifierPattern("Result"),
- sendable: true,
- escaping: true
- )
- ),
- defaultValue: includeDefaults && !streamingOutput
- ? .closureInvocation(.defaultClientUnaryResponseHandler)
- : nil
- )
- )
- return signature
- }
- }
- extension FunctionDescription {
- /// ```
- /// func <Name><Result>(
- /// request: GRPCCore.ClientRequest<Input>,
- /// options: GRPCCore.CallOptions = .defaults,
- /// onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse<Input>) async throws -> Result
- /// ) async throws -> Result where Result: Sendable {
- /// try await self.<Name>(
- /// request: request,
- /// serializer: <Serializer>,
- /// deserializer: <Deserializer>,
- /// options: options
- /// onResponse: handleResponse,
- /// )
- /// }
- /// ```
- static func clientMethodWithDefaults(
- accessLevel: AccessModifier? = nil,
- name: String,
- input: String,
- output: String,
- streamingInput: Bool,
- streamingOutput: Bool,
- serializer: Expression,
- deserializer: Expression,
- namer: Namer = Namer()
- ) -> Self {
- FunctionDescription(
- signature: .clientMethod(
- accessLevel: accessLevel,
- name: name,
- input: input,
- output: output,
- streamingInput: streamingInput,
- streamingOutput: streamingOutput,
- includeDefaults: true,
- includeSerializers: false,
- namer: namer
- ),
- body: [
- .expression(
- .try(
- .await(
- .functionCall(
- calledExpression: .identifierPattern("self").dot(name),
- arguments: [
- FunctionArgumentDescription(
- label: "request",
- expression: .identifierPattern("request")
- ),
- FunctionArgumentDescription(
- label: "serializer",
- expression: serializer
- ),
- FunctionArgumentDescription(
- label: "deserializer",
- expression: deserializer
- ),
- FunctionArgumentDescription(
- label: "options",
- expression: .identifierPattern("options")
- ),
- FunctionArgumentDescription(
- label: "onResponse",
- expression: .identifierPattern("handleResponse")
- ),
- ]
- )
- )
- )
- )
- ]
- )
- }
- }
- extension ProtocolDescription {
- /// ```
- /// protocol <Name>: Sendable {
- /// func foo<Result: Sendable>(
- /// ...
- /// ) async throws -> Result
- /// }
- /// ```
- static func clientProtocol(
- accessLevel: AccessModifier? = nil,
- name: String,
- methods: [MethodDescriptor],
- namer: Namer = Namer()
- ) -> Self {
- ProtocolDescription(
- accessModifier: accessLevel,
- name: name,
- conformances: ["Sendable"],
- members: methods.map { method in
- .commentable(
- .preFormatted(docs(for: method)),
- .function(
- signature: .clientMethod(
- name: method.name.functionName,
- input: method.inputType,
- output: method.outputType,
- streamingInput: method.isInputStreaming,
- streamingOutput: method.isOutputStreaming,
- includeDefaults: false,
- includeSerializers: true,
- namer: namer
- )
- )
- )
- }
- )
- }
- }
- extension ExtensionDescription {
- /// ```
- /// extension <Name> {
- /// func foo<Result: Sendable>(
- /// request: GRPCCore.ClientRequest<Input>,
- /// options: GRPCCore.CallOptions = .defaults,
- /// onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse<Input>) async throws -> Result
- /// ) async throws -> Result where Result: Sendable {
- /// // ...
- /// }
- /// // ...
- /// }
- /// ```
- static func clientMethodSignatureWithDefaults(
- accessLevel: AccessModifier? = nil,
- name: String,
- methods: [MethodDescriptor],
- namer: Namer = Namer(),
- serializer: (String) -> String,
- deserializer: (String) -> String
- ) -> Self {
- ExtensionDescription(
- onType: name,
- declarations: methods.map { method in
- .commentable(
- .preFormatted(docs(for: method, serializers: false)),
- .function(
- .clientMethodWithDefaults(
- accessLevel: accessLevel,
- name: method.name.functionName,
- input: method.inputType,
- output: method.outputType,
- streamingInput: method.isInputStreaming,
- streamingOutput: method.isOutputStreaming,
- serializer: .identifierPattern(serializer(method.inputType)),
- deserializer: .identifierPattern(deserializer(method.outputType)),
- namer: namer
- )
- )
- )
- }
- )
- }
- }
- extension FunctionSignatureDescription {
- /// ```
- /// func foo<Result>(
- /// _ message: <Input>,
- /// metadata: GRPCCore.Metadata = [:],
- /// options: GRPCCore.CallOptions = .defaults,
- /// onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse<Output>) async throws -> Result = { response in
- /// try response.message
- /// }
- /// ) async throws -> Result where Result: Sendable
- /// ```
- static func clientMethodExploded(
- accessLevel: AccessModifier? = nil,
- name: String,
- input: String,
- output: String,
- streamingInput: Bool,
- streamingOutput: Bool,
- namer: Namer = Namer()
- ) -> Self {
- var signature = FunctionSignatureDescription(
- accessModifier: accessLevel,
- kind: .function(name: name),
- generics: [.member("Result")],
- parameters: [], // Populated below
- keywords: [.async, .throws],
- returnType: .identifierPattern("Result"),
- whereClause: WhereClause(requirements: [.conformance("Result", "Sendable")])
- )
- if !streamingInput {
- signature.parameters.append(
- ParameterDescription(label: "_", name: "message", type: .member(input))
- )
- }
- // metadata: GRPCCore.Metadata = [:]
- signature.parameters.append(
- ParameterDescription(
- label: "metadata",
- type: namer.metadata,
- defaultValue: .literal(.dictionary([]))
- )
- )
- // options: GRPCCore.CallOptions = .defaults
- signature.parameters.append(
- ParameterDescription(
- label: "options",
- type: namer.callOptions,
- defaultValue: .dot("defaults")
- )
- )
- if streamingInput {
- signature.parameters.append(
- ParameterDescription(
- label: "requestProducer",
- name: "producer",
- type: .closure(
- ClosureSignatureDescription(
- parameters: [ParameterDescription(type: namer.rpcWriter(forType: input))],
- keywords: [.async, .throws],
- returnType: .identifierPattern("Void"),
- sendable: true,
- escaping: true
- )
- )
- )
- )
- }
- signature.parameters.append(
- ParameterDescription(
- label: "onResponse",
- name: "handleResponse",
- type: .closure(
- ClosureSignatureDescription(
- parameters: [
- ParameterDescription(
- type: namer.clientResponse(forType: output, isStreaming: streamingOutput)
- )
- ],
- keywords: [.async, .throws],
- returnType: .identifierPattern("Result"),
- sendable: true,
- escaping: true
- )
- ),
- defaultValue: streamingOutput ? nil : .closureInvocation(.defaultClientUnaryResponseHandler)
- )
- )
- return signature
- }
- }
- extension [CodeBlock] {
- /// ```
- /// let request = GRPCCore.StreamingClientRequest<Input>(
- /// metadata: metadata,
- /// producer: producer
- /// )
- /// return try await self.foo(
- /// request: request,
- /// options: options,
- /// onResponse: handleResponse
- /// )
- /// ```
- static func clientMethodExploded(
- name: String,
- input: String,
- streamingInput: Bool,
- namer: Namer = Namer()
- ) -> Self {
- func arguments(streaming: Bool) -> [FunctionArgumentDescription] {
- let metadata = FunctionArgumentDescription(
- label: "metadata",
- expression: .identifierPattern("metadata")
- )
- if streaming {
- return [
- metadata,
- FunctionArgumentDescription(
- label: "producer",
- expression: .identifierPattern("producer")
- ),
- ]
- } else {
- return [
- FunctionArgumentDescription(label: "message", expression: .identifierPattern("message")),
- metadata,
- ]
- }
- }
- return [
- CodeBlock(
- item: .declaration(
- .variable(
- kind: .let,
- left: .identifierPattern("request"),
- right: .functionCall(
- calledExpression: .identifierType(
- namer.clientRequest(forType: input, isStreaming: streamingInput)
- ),
- arguments: arguments(streaming: streamingInput)
- )
- )
- )
- ),
- CodeBlock(
- item: .expression(
- .return(
- .try(
- .await(
- .functionCall(
- calledExpression: .identifierPattern("self").dot(name),
- arguments: [
- FunctionArgumentDescription(
- label: "request",
- expression: .identifierPattern("request")
- ),
- FunctionArgumentDescription(
- label: "options",
- expression: .identifierPattern("options")
- ),
- FunctionArgumentDescription(
- label: "onResponse",
- expression: .identifierPattern("handleResponse")
- ),
- ]
- )
- )
- )
- )
- )
- ),
- ]
- }
- }
- extension FunctionDescription {
- /// ```
- /// func foo<Result>(
- /// _ message: <Input>,
- /// metadata: GRPCCore.Metadata = [:],
- /// options: GRPCCore.CallOptions = .defaults,
- /// onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse<Output>) async throws -> Result = { response in
- /// try response.message
- /// }
- /// ) async throws -> Result where Result: Sendable {
- /// // ...
- /// }
- /// ```
- static func clientMethodExploded(
- accessLevel: AccessModifier? = nil,
- name: String,
- input: String,
- output: String,
- streamingInput: Bool,
- streamingOutput: Bool,
- namer: Namer = Namer()
- ) -> Self {
- FunctionDescription(
- signature: .clientMethodExploded(
- accessLevel: accessLevel,
- name: name,
- input: input,
- output: output,
- streamingInput: streamingInput,
- streamingOutput: streamingOutput,
- namer: namer
- ),
- body: .clientMethodExploded(
- name: name,
- input: input,
- streamingInput: streamingInput,
- namer: namer
- )
- )
- }
- }
- extension ExtensionDescription {
- /// ```
- /// extension <Name> {
- /// // (exploded client methods)
- /// }
- /// ```
- static func explodedClientMethods(
- accessLevel: AccessModifier? = nil,
- on extensionName: String,
- methods: [MethodDescriptor],
- namer: Namer = Namer()
- ) -> ExtensionDescription {
- return ExtensionDescription(
- onType: extensionName,
- declarations: methods.map { method in
- .commentable(
- .preFormatted(explodedDocs(for: method)),
- .function(
- .clientMethodExploded(
- accessLevel: accessLevel,
- name: method.name.functionName,
- input: method.inputType,
- output: method.outputType,
- streamingInput: method.isInputStreaming,
- streamingOutput: method.isOutputStreaming,
- namer: namer
- )
- )
- )
- }
- )
- }
- }
- extension FunctionDescription {
- /// ```
- /// func <Name><Result>(
- /// request: GRPCCore.ClientRequest<Input>,
- /// serializer: some GRPCCore.MessageSerializer<Input>,
- /// deserializer: some GRPCCore.MessageDeserializer<Output>,
- /// options: GRPCCore.CallOptions = .default,
- /// onResponse handleResponse: @Sendable @escaping (GRPCCore.ClientResponse<Output>) async throws -> Result
- /// ) async throws -> Result where Result: Sendable {
- /// try await self.<Name>(...)
- /// }
- /// ```
- static func clientMethod(
- accessLevel: AccessModifier,
- name: String,
- input: String,
- output: String,
- serviceEnum: String,
- methodEnum: String,
- streamingInput: Bool,
- streamingOutput: Bool,
- namer: Namer = Namer()
- ) -> Self {
- let underlyingMethod: String
- switch (streamingInput, streamingOutput) {
- case (false, false):
- underlyingMethod = "unary"
- case (true, false):
- underlyingMethod = "clientStreaming"
- case (false, true):
- underlyingMethod = "serverStreaming"
- case (true, true):
- underlyingMethod = "bidirectionalStreaming"
- }
- return FunctionDescription(
- accessModifier: accessLevel,
- kind: .function(name: name),
- generics: [.member("Result")],
- parameters: [
- ParameterDescription(
- label: "request",
- type: namer.clientRequest(forType: input, isStreaming: streamingInput)
- ),
- ParameterDescription(
- label: "serializer",
- // Be explicit: 'type' is optional and '.some' resolves to Optional.some by default.
- type: ExistingTypeDescription.some(namer.serializer(forType: input))
- ),
- ParameterDescription(
- label: "deserializer",
- // Be explicit: 'type' is optional and '.some' resolves to Optional.some by default.
- type: ExistingTypeDescription.some(namer.deserializer(forType: output))
- ),
- ParameterDescription(
- label: "options",
- type: namer.callOptions,
- defaultValue: .dot("defaults")
- ),
- ParameterDescription(
- label: "onResponse",
- name: "handleResponse",
- type: .closure(
- ClosureSignatureDescription(
- parameters: [
- ParameterDescription(
- type: namer.clientResponse(forType: output, isStreaming: streamingOutput)
- )
- ],
- keywords: [.async, .throws],
- returnType: .identifierPattern("Result"),
- sendable: true,
- escaping: true
- )
- ),
- defaultValue: streamingOutput
- ? nil
- : .closureInvocation(.defaultClientUnaryResponseHandler)
- ),
- ],
- keywords: [.async, .throws],
- returnType: .identifierPattern("Result"),
- whereClause: WhereClause(requirements: [.conformance("Result", "Sendable")]),
- body: [
- .try(
- .await(
- .functionCall(
- calledExpression: .identifierPattern("self").dot("client").dot(underlyingMethod),
- arguments: [
- FunctionArgumentDescription(
- label: "request",
- expression: .identifierPattern("request")
- ),
- FunctionArgumentDescription(
- label: "descriptor",
- expression: .identifierPattern(serviceEnum)
- .dot("Method")
- .dot(methodEnum)
- .dot("descriptor")
- ),
- FunctionArgumentDescription(
- label: "serializer",
- expression: .identifierPattern("serializer")
- ),
- FunctionArgumentDescription(
- label: "deserializer",
- expression: .identifierPattern("deserializer")
- ),
- FunctionArgumentDescription(
- label: "options",
- expression: .identifierPattern("options")
- ),
- FunctionArgumentDescription(
- label: "onResponse",
- expression: .identifierPattern("handleResponse")
- ),
- ]
- )
- )
- )
- ]
- )
- }
- }
- extension StructDescription {
- /// ```
- /// struct <Name><Transport>: <ClientProtocol> where Transport: GRPCCore.ClientTransport {
- /// private let client: GRPCCore.GRPCClient<Transport>
- ///
- /// init(wrapping client: GRPCCore.GRPCClient<Transport>) {
- /// self.client = client
- /// }
- ///
- /// // ...
- /// }
- /// ```
- static func client(
- accessLevel: AccessModifier,
- name: String,
- serviceEnum: String,
- clientProtocol: String,
- methods: [MethodDescriptor],
- namer: Namer = Namer()
- ) -> Self {
- return StructDescription(
- accessModifier: accessLevel,
- name: name,
- generics: [.member("Transport")],
- conformances: [clientProtocol],
- whereClause: WhereClause(
- requirements: [.conformance("Transport", namer.literalNamespacedType("ClientTransport"))]
- ),
- members: [
- .variable(
- accessModifier: .private,
- kind: .let,
- left: "client",
- type: namer.grpcClient(genericOver: "Transport")
- ),
- .commentable(
- .preFormatted(
- """
- /// Creates a new client wrapping the provided `\(namer.literalNamespacedType("GRPCClient"))`.
- ///
- /// - Parameters:
- /// - client: A `\(namer.literalNamespacedType("GRPCClient"))` providing a communication channel to the service.
- """
- ),
- .function(
- accessModifier: accessLevel,
- kind: .initializer,
- parameters: [
- ParameterDescription(
- label: "wrapping",
- name: "client",
- type: namer.grpcClient(
- genericOver: "Transport"
- )
- )
- ],
- whereClause: nil,
- body: [
- .expression(
- .assignment(
- left: .identifierPattern("self").dot("client"),
- right: .identifierPattern("client")
- )
- )
- ]
- )
- ),
- ]
- + methods.map { method in
- .commentable(
- .preFormatted(docs(for: method)),
- .function(
- .clientMethod(
- accessLevel: accessLevel,
- name: method.name.functionName,
- input: method.inputType,
- output: method.outputType,
- serviceEnum: serviceEnum,
- methodEnum: method.name.typeName,
- streamingInput: method.isInputStreaming,
- streamingOutput: method.isOutputStreaming,
- namer: namer
- )
- )
- )
- }
- )
- }
- }
- private func docs(
- for method: MethodDescriptor,
- serializers includeSerializers: Bool = true
- ) -> String {
- let summary = "/// Call the \"\(method.name.identifyingName)\" method."
- let request: String
- if method.isInputStreaming {
- request = "A streaming request producing `\(method.inputType)` messages."
- } else {
- request = "A request containing a single `\(method.inputType)` message."
- }
- let parameters = """
- /// - Parameters:
- /// - request: \(request)
- """
- let serializers = """
- /// - serializer: A serializer for `\(method.inputType)` messages.
- /// - deserializer: A deserializer for `\(method.outputType)` messages.
- """
- let otherParameters = """
- /// - options: Options to apply to this RPC.
- /// - handleResponse: A closure which handles the response, the result of which is
- /// returned to the caller. Returning from the closure will cancel the RPC if it
- /// hasn't already finished.
- /// - Returns: The result of `handleResponse`.
- """
- let allParameters: String
- if includeSerializers {
- allParameters = parameters + "\n" + serializers + "\n" + otherParameters
- } else {
- allParameters = parameters + "\n" + otherParameters
- }
- return Docs.interposeDocs(method.documentation, between: summary, and: allParameters)
- }
- private func explodedDocs(for method: MethodDescriptor) -> String {
- let summary = "/// Call the \"\(method.name.identifyingName)\" method."
- var parameters = """
- /// - Parameters:
- """
- if !method.isInputStreaming {
- parameters += "\n"
- parameters += """
- /// - message: request message to send.
- """
- }
- parameters += "\n"
- parameters += """
- /// - metadata: Additional metadata to send, defaults to empty.
- /// - options: Options to apply to this RPC, defaults to `.defaults`.
- """
- if method.isInputStreaming {
- parameters += "\n"
- parameters += """
- /// - producer: A closure producing request messages to send to the server. The request
- /// stream is closed when the closure returns.
- """
- }
- parameters += "\n"
- parameters += """
- /// - handleResponse: A closure which handles the response, the result of which is
- /// returned to the caller. Returning from the closure will cancel the RPC if it
- /// hasn't already finished.
- /// - Returns: The result of `handleResponse`.
- """
- return Docs.interposeDocs(method.documentation, between: summary, and: parameters)
- }
|