Skip to content

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 5 commits into from
Jan 31, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Examples/echo-metadata/.gitignore
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
43 changes: 43 additions & 0 deletions Examples/echo-metadata/Package.swift
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")
]
)
]
)
58 changes: 58 additions & 0 deletions Examples/echo-metadata/README.md
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)]
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
33 changes: 33 additions & 0 deletions Examples/echo-metadata/Sources/EchoMetadata.swift
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-") }))
}
}
1 change: 1 addition & 0 deletions Examples/echo-metadata/Sources/Protos/echo
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 Examples/echo-metadata/Sources/Subcommands/ClientArguments.swift
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)
}
}
82 changes: 82 additions & 0 deletions Examples/echo-metadata/Sources/Subcommands/Echo.swift
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)
}
}

print("unary → \(requestMetadata)")
try await echo.get(
Echo_EchoRequest(),
metadata: requestMetadata
) { response in
print("unary ← Initial metadata: \(response.metadata.echoPairs)")
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 {
switch part {
case .trailingMetadata(let trailingMetadata):
print("bidirectional ← Trailing metadata: \(trailingMetadata.echoPairs)")

case .message:
()
}
}
}
}
}
}
75 changes: 75 additions & 0 deletions Examples/echo-metadata/Sources/Subcommands/EchoService.swift
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 {
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
}

let responseMetadata = request.metadata.echoPairs
return StreamingServerResponse(
single: ServerResponse(
message: .init(),
metadata: responseMetadata,
trailingMetadata: responseMetadata
)
)
}
}
43 changes: 43 additions & 0 deletions Examples/echo-metadata/Sources/Subcommands/Serve.swift
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)")
}
}
}
}
Loading