-
Notifications
You must be signed in to change notification settings - Fork 434
Add echo-metadata
example
#2182
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
.DS_Store | ||
/.build | ||
/Packages | ||
xcuserdata/ | ||
DerivedData/ | ||
.swiftpm/configuration/registries.json | ||
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata | ||
.netrc |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
// swift-tools-version:6.0 | ||
/* | ||
* 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. | ||
*/ | ||
|
||
import PackageDescription | ||
|
||
let package = Package( | ||
name: "echo-metadata", | ||
platforms: [.macOS("15.0")], | ||
dependencies: [ | ||
.package(url: "https://github.com/grpc/grpc-swift.git", exact: "2.0.0-rc.1"), | ||
.package(url: "https://github.com/grpc/grpc-swift-protobuf.git", exact: "1.0.0-rc.1"), | ||
.package(url: "https://github.com/grpc/grpc-swift-nio-transport.git", exact: "1.0.0-rc.1"), | ||
.package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.5.0"), | ||
], | ||
targets: [ | ||
.executableTarget( | ||
name: "echo-metadata", | ||
dependencies: [ | ||
.product(name: "GRPCCore", package: "grpc-swift"), | ||
.product(name: "GRPCNIOTransportHTTP2", package: "grpc-swift-nio-transport"), | ||
.product(name: "GRPCProtobuf", package: "grpc-swift-protobuf"), | ||
.product(name: "ArgumentParser", package: "swift-argument-parser"), | ||
], | ||
plugins: [ | ||
.plugin(name: "GRPCProtobufGenerator", package: "grpc-swift-protobuf") | ||
] | ||
) | ||
] | ||
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
# Echo-Metadata | ||
|
||
This example demonstrates how to interact with `Metadata` on RPCs: how to set and read it on unary | ||
and streaming requests, as well as how to set and read both initial and trailing metadata on unary | ||
and streaming responses. This is done using a simple 'echo' server and client and the Swift NIO | ||
based HTTP/2 transport. | ||
|
||
## Overview | ||
|
||
An `echo-metadata` command line tool that uses generated stubs for an 'echo' service | ||
which allows you to start a server and to make requests against it. The client will automatically | ||
run a unary request followed by a bidirectional streaming request. In both cases, no message will | ||
be sent as part of the request: only the metadata provided as arguments to the executable will be | ||
included. | ||
The server will then echo back all metadata key-value pairs that begin with "echo-". No message | ||
will be included in the responses, and the echoed values will be included in both the initial and | ||
the trailing metadata. | ||
|
||
The tool uses the [SwiftNIO](https://github.com/grpc/grpc-swift-nio-transport) HTTP/2 transport. | ||
|
||
## Prerequisites | ||
|
||
You must have the Protocol Buffers compiler (`protoc`) installed. You can find | ||
the instructions for doing this in the [gRPC Swift Protobuf documentation][0]. | ||
The `swift` commands below are all prefixed with `PROTOC_PATH=$(which protoc)`, | ||
this is to let the build system know where `protoc` is located so that it can | ||
generate stubs for you. You can read more about it in the [gRPC Swift Protobuf | ||
documentation][1]. | ||
|
||
## Usage | ||
|
||
Build and run the server using the CLI: | ||
|
||
```console | ||
$ PROTOC_PATH=$(which protoc) swift run echo-metadata serve | ||
Echo-Metadata listening on [ipv4]127.0.0.1:1234 | ||
``` | ||
|
||
Use the CLI to run the client and make a unary request followed by a bidirectional streaming one: | ||
|
||
```console | ||
$ PROTOC_PATH=$(which protoc) swift run echo-metadata echo --metadata "echo-key=value" --metadata "another-key=value" | ||
unary → [("echo-key", value)] | ||
gjcairo marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
unary ← Initial metadata: [("echo-key", value)] | ||
unary ← Trailing metadata: [("echo-key", value)] | ||
bidirectional → [("echo-key", value)] | ||
bidirectional ← Initial metadata: [("echo-key", value)] | ||
bidirectional ← Trailing metadata: [("echo-key", value)] | ||
``` | ||
|
||
Get help with the CLI by running: | ||
|
||
```console | ||
$ PROTOC_PATH=$(which protoc) swift run echo-metadata --help | ||
``` | ||
|
||
[0]: https://swiftpackageindex.com/grpc/grpc-swift-protobuf/documentation/grpcprotobuf/installing-protoc | ||
[1]: https://swiftpackageindex.com/grpc/grpc-swift-protobuf/documentation/grpcprotobuf/generating-stubs |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
/* | ||
* Copyright 2025, 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. | ||
*/ | ||
|
||
import ArgumentParser | ||
import GRPCCore | ||
|
||
@main | ||
struct EchoMetadata: AsyncParsableCommand { | ||
static let configuration = CommandConfiguration( | ||
commandName: "echo-metadata", | ||
abstract: "A multi-tool to run an echo-metadata server and execute RPCs against it.", | ||
subcommands: [Serve.self, Echo.self] | ||
) | ||
} | ||
|
||
extension Metadata { | ||
var echoPairs: Self { | ||
Metadata(self.filter({ $0.key.starts(with: "echo-") })) | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
../../../../dev/protos/examples/echo/ |
7 changes: 7 additions & 0 deletions
7
Examples/echo-metadata/Sources/Protos/grpc-swift-proto-generator-config.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
{ | ||
"generate": { | ||
"clients": true, | ||
"servers": true, | ||
"messages": true | ||
} | ||
} |
35 changes: 35 additions & 0 deletions
35
Examples/echo-metadata/Sources/Subcommands/ClientArguments.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
/* | ||
* Copyright 2025, 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. | ||
*/ | ||
|
||
import ArgumentParser | ||
import GRPCNIOTransportHTTP2 | ||
|
||
struct ClientArguments: ParsableArguments { | ||
@Option(help: "The server's listening port") | ||
var port: Int = 1234 | ||
|
||
@Option( | ||
help: | ||
"Metadata 'key=value' pair to send to the server. Key must begin with 'echo-' to be echoed back." | ||
) | ||
var metadata: [String] | ||
} | ||
|
||
extension ClientArguments { | ||
var target: any ResolvableTarget { | ||
return .ipv4(host: "127.0.0.1", port: self.port) | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
/* | ||
* Copyright 2025, 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. | ||
*/ | ||
|
||
import ArgumentParser | ||
import GRPCCore | ||
import GRPCNIOTransportHTTP2 | ||
|
||
struct Echo: AsyncParsableCommand { | ||
static let configuration = CommandConfiguration( | ||
abstract: | ||
"Makes a unary RPC to the echo-metadata server, followed by a bidirectional-streaming request." | ||
) | ||
|
||
@OptionGroup | ||
var arguments: ClientArguments | ||
|
||
func run() async throws { | ||
try await withGRPCClient( | ||
transport: .http2NIOPosix( | ||
target: self.arguments.target, | ||
transportSecurity: .plaintext | ||
) | ||
) { client in | ||
let echo = Echo_Echo.Client(wrapping: client) | ||
|
||
var requestMetadata: Metadata = [:] | ||
for metadataPair in arguments.metadata { | ||
guard metadataPair.starts(with: "echo-") else { | ||
continue | ||
} | ||
|
||
let pair = metadataPair.split(separator: "=") | ||
if pair.count == 2, let key = pair.first.map(String.init), | ||
let value = pair.last.map(String.init) | ||
{ | ||
requestMetadata.addString(value, forKey: key) | ||
} | ||
} | ||
gjcairo marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
print("unary → \(requestMetadata)") | ||
gjcairo marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
try await echo.get( | ||
Echo_EchoRequest(), | ||
metadata: requestMetadata | ||
) { response in | ||
print("unary ← Initial metadata: \(response.metadata.echoPairs)") | ||
gjcairo marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
print("unary ← Trailing metadata: \(response.trailingMetadata)") | ||
} | ||
|
||
print("bidirectional → \(requestMetadata)") | ||
try await echo.update( | ||
request: .init( | ||
metadata: requestMetadata, | ||
producer: { _ in } | ||
) | ||
) { response in | ||
print("bidirectional ← Initial metadata: \(response.metadata.echoPairs)") | ||
for try await part in try response.accepted.get().bodyParts { | ||
gjcairo marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
switch part { | ||
case .trailingMetadata(let trailingMetadata): | ||
print("bidirectional ← Trailing metadata: \(trailingMetadata.echoPairs)") | ||
|
||
case .message: | ||
() | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} |
75 changes: 75 additions & 0 deletions
75
Examples/echo-metadata/Sources/Subcommands/EchoService.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
/* | ||
* Copyright 2025, 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. | ||
*/ | ||
|
||
import GRPCCore | ||
|
||
struct EchoService: Echo_Echo.ServiceProtocol { | ||
gjcairo marked this conversation as resolved.
Show resolved
Hide resolved
|
||
func get( | ||
request: ServerRequest<Echo_EchoRequest>, | ||
context: ServerContext | ||
) async throws -> ServerResponse<Echo_EchoResponse> { | ||
let responseMetadata = request.metadata.echoPairs | ||
return ServerResponse( | ||
message: .init(), | ||
metadata: responseMetadata, | ||
trailingMetadata: responseMetadata | ||
) | ||
} | ||
|
||
func collect( | ||
request: StreamingServerRequest<Echo_EchoRequest>, | ||
context: ServerContext | ||
) async throws -> ServerResponse<Echo_EchoResponse> { | ||
let responseMetadata = request.metadata.echoPairs | ||
return ServerResponse( | ||
message: .init(), | ||
metadata: responseMetadata, | ||
trailingMetadata: responseMetadata | ||
) | ||
} | ||
|
||
func expand( | ||
request: ServerRequest<Echo_EchoRequest>, | ||
context: ServerContext | ||
) async throws -> StreamingServerResponse<Echo_EchoResponse> { | ||
let responseMetadata = request.metadata.echoPairs | ||
return StreamingServerResponse( | ||
single: ServerResponse( | ||
message: .init(), | ||
metadata: responseMetadata, | ||
trailingMetadata: responseMetadata | ||
) | ||
) | ||
} | ||
|
||
func update( | ||
request: StreamingServerRequest<Echo_EchoRequest>, | ||
context: ServerContext | ||
) async throws -> StreamingServerResponse<Echo_EchoResponse> { | ||
for try await _ in request.messages { | ||
// Wait for request to be done | ||
} | ||
gjcairo marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
let responseMetadata = request.metadata.echoPairs | ||
return StreamingServerResponse( | ||
single: ServerResponse( | ||
message: .init(), | ||
metadata: responseMetadata, | ||
trailingMetadata: responseMetadata | ||
) | ||
) | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
/* | ||
* Copyright 2025, 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. | ||
*/ | ||
|
||
import ArgumentParser | ||
import GRPCCore | ||
import GRPCNIOTransportHTTP2 | ||
|
||
struct Serve: AsyncParsableCommand { | ||
static let configuration = CommandConfiguration(abstract: "Starts an echo-metadata server.") | ||
|
||
@Option(help: "The port to listen on") | ||
var port: Int = 1234 | ||
|
||
func run() async throws { | ||
let server = GRPCServer( | ||
transport: .http2NIOPosix( | ||
address: .ipv4(host: "127.0.0.1", port: self.port), | ||
transportSecurity: .plaintext | ||
), | ||
services: [EchoService()] | ||
) | ||
|
||
try await withThrowingDiscardingTaskGroup { group in | ||
group.addTask { try await server.serve() } | ||
if let address = try await server.listeningAddress { | ||
print("Echo-Metadata listening on \(address)") | ||
} | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.