Repository: rouzwawi/grpc-kotlin
Branch: master
Commit: a8cac5b44414
Files: 43
Total size: 151.9 KB
Directory structure:
gitextract_swzgl8ap/
├── .circleci/
│ └── config.yml
├── .gitignore
├── .mvn/
│ └── wrapper/
│ ├── MavenWrapperDownloader.java
│ ├── maven-wrapper.jar
│ └── maven-wrapper.properties
├── LICENSE
├── NOTICE
├── README.md
├── grpc-kotlin-example-chatserver/
│ ├── README.md
│ ├── pom.xml
│ └── src/
│ └── main/
│ ├── kotlin/
│ │ └── io/
│ │ └── rouz/
│ │ └── grpc/
│ │ └── examples/
│ │ └── chat/
│ │ ├── ChatClient.kt
│ │ ├── ChatService.kt
│ │ ├── Entrypoint.kt
│ │ ├── GrpcServer.kt
│ │ └── ServerStreaminChatClient.kt
│ └── proto/
│ └── chat.proto
├── grpc-kotlin-gen/
│ ├── pom.xml
│ └── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── io/
│ │ │ └── rouz/
│ │ │ └── grpc/
│ │ │ └── kotlin/
│ │ │ └── GrpcKotlinGenerator.java
│ │ └── resources/
│ │ ├── Adapters.mustache
│ │ ├── ImplBase.mustache
│ │ └── StubExtensions.mustache
│ └── test/
│ └── java/
│ └── io/
│ └── rouz/
│ └── grpc/
│ └── kotlin/
│ └── GrpcKotlinGeneratorTest.java
├── grpc-kotlin-test/
│ ├── pom.xml
│ └── src/
│ ├── main/
│ │ ├── kotlin/
│ │ │ └── io/
│ │ │ └── rouz/
│ │ │ └── greeter/
│ │ │ ├── GreeterImpl.kt
│ │ │ ├── GreeterMain.kt
│ │ │ └── InfiniteStreamGreeterImpl.kt
│ │ └── proto/
│ │ └── io/
│ │ └── rouz/
│ │ ├── greeter.proto
│ │ └── kvs.proto
│ └── test/
│ └── kotlin/
│ └── io/
│ └── rouz/
│ └── greeter/
│ ├── ClientAbandonTest.kt
│ ├── ClosingStatusExceptionTest.kt
│ ├── ContextBasedGreeterTest.kt
│ ├── DelayedClosingStatusExceptionTest.kt
│ ├── DelayedThrowingStatusExceptionTest.kt
│ ├── ExceptionPropagationTest.kt
│ ├── GrpcTestBase.kt
│ ├── NoStatusExceptionPropagationTest.kt
│ ├── ServiceCallsTest.kt
│ ├── StatusExceptionTestBase.kt
│ ├── ThrowingStatusExceptionTest.kt
│ └── UnimplementedStatusTest.kt
├── mvnw
├── mvnw.cmd
└── pom.xml
================================================
FILE CONTENTS
================================================
================================================
FILE: .circleci/config.yml
================================================
# Java Maven CircleCI 2.0 configuration file
#
# Check https://circleci.com/docs/2.0/language-java/ for more details
#
version: 2
jobs:
build:
docker:
# specify the version you desire here
- image: circleci/openjdk:8-jdk
# Specify service dependencies here if necessary
# CircleCI maintains a library of pre-built images
# documented at https://circleci.com/docs/2.0/circleci-images/
# - image: circleci/postgres:9.4
working_directory: ~/repo
environment:
# Customize the JVM maximum heap limit
MAVEN_OPTS: -Xmx3200m
steps:
- checkout
# Download and cache dependencies
- restore_cache:
keys:
- v1-dependencies-{{ checksum "pom.xml" }}-{{ checksum "grpc-kotlin-gen/pom.xml" }}-{{ checksum "grpc-kotlin-test/pom.xml" }}
# fallback to using the latest cache if no exact match is found
- v1-dependencies-
# run tests!
- run: mvn verify
- save_cache:
paths:
- ~/.m2
key: v1-dependencies-{{ checksum "pom.xml" }}-{{ checksum "grpc-kotlin-gen/pom.xml" }}-{{ checksum "grpc-kotlin-test/pom.xml" }}
================================================
FILE: .gitignore
================================================
# Build products and artifacts
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
# Stuff from various IDE's and editors
*.iml
*~
.idea/*
# Mac OS X Finder
.DS_Store
.classpath
.project
================================================
FILE: .mvn/wrapper/MavenWrapperDownloader.java
================================================
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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 java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL =
"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: : " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
================================================
FILE: .mvn/wrapper/maven-wrapper.properties
================================================
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
================================================
FILE: NOTICE
================================================
File grpc-kotlin-gen/src/main/java/io/rouz/grpc/kotlin/GrpcKotlinGenerator.java
Modified redistribution of ReactiveGrpcGenerator.java from https://github.com/salesforce/reactive-grpc
Licensed under the BSD 3-Clause license
================================================
FILE: README.md
================================================
# gRPC Kotlin - Coroutine based gRPC for Kotlin
[](https://circleci.com/gh/rouzwawi/grpc-kotlin)
[](https://search.maven.org/#search%7Cga%7C1%7Cg%3A%22io.rouz%22%20grpc-kotlin-gen)
gRPC Kotlin is a [protoc] plugin for generating native Kotlin bindings using [coroutine primitives] for [gRPC] services.
* [Why?](#why)
* [Quick start](#quick-start)
* [Server](#server)
* [Client](#client)
* [gRPC Context propagation](#grpc-context-propagation)
* [Exception handling](#exception-handling)
* [Maven configuration](#maven-configuration)
* [Gradle configuration](#gradle-configuration)
* [Examples](#examples)
* [RPC method type reference](#rpc-method-type-reference)
* [Unary call](#unary-call)
* [Service](#service)
* [Client](#client-1)
* [Client streaming call](#client-streaming-call)
* [Service](#service-1)
* [Client](#client-2)
* [Server streaming call](#server-streaming-call)
* [Service](#service-2)
* [Client](#client-3)
* [Full bidirectional streaming call](#full-bidirectional-streaming-call)
* [Service](#service-3)
* [Client](#client-4)
---
## Why?
The asynchronous nature of bidirectional streaming rpc calls in gRPC makes them a bit hard to implement
and read. Getting your head around the `StreamObserver<T>`'s can be a bit tricky at times. Specially
with the method argument being the response observer and the return value being the request observer, it all
feels a bit backwards to what a plain old synchronous version of the handler would look like.
In situations where you'd want to coordinate several request and response messages in one call, you'll and up
having to manage some tricky state and synchronization between the observers. There are [reactive bindings]
for gRPC which make this easier. But I think we can do better!
Enter Kotlin Coroutines! By generating native Kotlin stubs that allows us to use [`suspend`] functions and
[`Channel`], we can write our handler and client code in an idiomatic and easy to read Kotlin style.
## Quick start
Note: This has been tested with `gRPC 1.25.0`, `protobuf 3.10.0`, `kotlin 1.3.61` and `coroutines 1.3.3`.
Add a gRPC service definition to your project
`greeter.proto`
```proto
syntax = "proto3";
package org.example.greeter;
option java_package = "org.example.greeter";
option java_multiple_files = true;
message GreetRequest {
string greeting = 1;
}
message GreetReply {
string reply = 1;
}
service Greeter {
rpc Greet (GreetRequest) returns (GreetReply);
rpc GreetServerStream (GreetRequest) returns (stream GreetReply);
rpc GreetClientStream (stream GreetRequest) returns (GreetReply);
rpc GreetBidirectional (stream GreetRequest) returns (stream GreetReply);
}
```
Run the protoc plugin to get the generated code, see [build tool configuration](#maven-configuration)
### Server
After compilation, you'll find the generated Kotlin code in the same package as the generated Java
code. A service base class named `GreeterImplBase` and a file with extension functions for the
client stub named `GreeterStubExt.kt`. Both the service base class and client stub extensions will
use `suspend` and `Channel<T>` instead of the typical `StreamObserver<T>` interfaces.
All functions have the [`suspend`] modifier so they can call into any suspending code, including the
[core coroutine primitives] like `delay` and `async`.
All the server streaming calls return a `ReceiveChannel<TReply>` and can easily be implemented using
`produce<TReply>`.
All client streaming calls receive an argument of `ReceiveChannel<TRequest>` where they can `receive()`
messages from the caller.
Here's an example server that demonstrates how each type of endpoint is implemented.
```kotlin
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
import java.util.concurrent.Executors.newFixedThreadPool
class GreeterImpl : GreeterImplBase(
coroutineContext = newFixedThreadPool(4).asCoroutineDispatcher()
) {
// unary rpc
override suspend fun greet(request: GreetRequest): GreetReply {
return GreetReply.newBuilder()
.setReply("Hello " + request.greeting)
.build()
}
// server streaming rpc
override fun greetServerStream(request: GreetRequest) = produce<GreetReply> {
send(GreetReply.newBuilder()
.setReply("Hello ${request.greeting}!")
.build())
send(GreetReply.newBuilder()
.setReply("Greetings ${request.greeting}!")
.build())
}
// client streaming rpc
override suspend fun greetClientStream(requestChannel: ReceiveChannel<GreetRequest>): GreetReply {
val greetings = mutableListOf<String>()
for (request in requestChannel) {
greetings.add(request.greeting)
}
return GreetReply.newBuilder()
.setReply("Hi to all of $greetings!")
.build()
}
// bidirectional rpc
override fun greetBidirectional(requestChannel: ReceiveChannel<GreetRequest>) = produce<GreetReply> {
var count = 0
for (request in requestChannel) {
val n = count++
launch {
delay(1000)
send(GreetReply.newBuilder()
.setReply("Yo #$n ${request.greeting}")
.build())
}
}
}
}
```
### Client
Extensions functions for the original Java stubs are generated that use `suspend` functions, `Deferred<TReply>`
and `SendChannel<TRequest>`.
```kotlin
import io.grpc.ManagedChannelBuilder
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main(args: Array<String>) {
val localhost = ManagedChannelBuilder.forAddress("localhost", 8080)
.usePlaintext()
.build()
val greeter = GreeterGrpc.newStub(localhost)
runBlocking {
// === Unary call =============================================================================
val unaryResponse = greeter.greet(req("Alice"))
println("unary reply = ${unaryResponse.reply}")
// === Server streaming call ==================================================================
val serverResponses = greeter.greetServerStream(req("Bob"))
for (serverResponse in serverResponses) {
println("server response = ${serverResponse.reply}")
}
// === Client streaming call ==================================================================
val manyToOneCall = greeter.greetClientStream()
manyToOneCall.send(req("Caroline"))
manyToOneCall.send(req("David"))
manyToOneCall.close()
val oneReply = manyToOneCall.await()
println("single reply = ${oneReply.reply}")
// === Bidirectional call =====================================================================
val bidiCall = greeter.greetBidirectional()
launch {
var n = 0
for (greetReply in bidiCall) {
println("r$n = ${greetReply.reply}")
n++
}
println("no more replies")
}
delay(200)
bidiCall.send(req("Eve"))
delay(200)
bidiCall.send(req("Fred"))
delay(200)
bidiCall.send(req("Gina"))
bidiCall.close()
}
}
```
## gRPC Context propagation
gRPC has a thread-local [`Context`] which is used to carry scoped values across API boundaries. With Kotlin coroutines
possibly being dispatched on multiple threads, the thread-local nature of `Context` needs some special care. This is
solved by two details in the generated Kotlin code.
First, all the generated service `*ImplBase` classes implement `CoroutineScope`. This allows you to use any of
the top level coroutine primitives such as `launch`, `async` and `produce` in your service implementation while still
keeping them within the context of your service code. The actual `CoroutineContext` that is used can be set through the
base class constructor, but defaults to `Dispatchers.default`.
```kotlin
abstract class MyServiceImplBase(
coroutineContext: CoroutineContext = Dispatchers.Default
)
```
Second, in the getter for `CoroutineScope.coroutineContext`, an additional context key is added to the
`CoroutineContext` that manages the gRPC Context `attach()` and `detach()` calls when dispatching coroutine
continuations. This will ensure that the the gRPC context is always propagated across different coroutine boundaries,
and eliminates the need to manually carry it across in user code.
Here's a simple example that makes calls to other services concurrently and expects an authenticated user to be present
in the gRPC Context. The two accesses to the context key may execute on different threads in the `CoroutineContext` but
the accesses work as expected.
```kotlin
val authenticatedUser = Context.key<User>("authenticatedUser")
override suspend fun greet(request: GreetRequest): GreetReply {
val motd = async { messageOfTheDay.getMessage() }
val weatherReport = async { weather.getWeatherReport(authenticatedUser.get().location) }
val reply = buildString {
append("Hello ${authenticatedUser.get().fullName}")
append("---")
append("Today's weather report: ${weatherReport.await()}")
append("---")
append(motd.await())
}
return GreetReply.newBuilder()
.setReply(reply)
.build()
}
```
For another example of gRPC Context usage, see the code in [ContextBasedGreeterTest](grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/ContextBasedGreeterTest.kt)
Thanks to [`wfhartford`](https://github.com/wfhartford) for contributing!
## Exception handling
The generated server code follows the standard exception propagation for Kotlin coroutines as described
in the [Exception handling] documentation. This means that it's safe to throw exceptions from within
the server implementation code. These will propagate up the coroutine scope and be translated to
`responseObserver.onError(Throwable)` calls. The preferred way to respond with a status code is to
throw a `StatusException`.
Note that you should not call `close(Throwable)` or `close()` from within the `ProducerScope<T>`
blocks you get from `produce` as the producer will automatically be closed when all sub-contexts are
closed (or if an exception is thrown).
## Maven configuration
Add the `grpc-kotlin-gen` plugin to your `protobuf-maven-plugin` configuration (see [compile-custom goal](https://www.xolstice.org/protobuf-maven-plugin/compile-custom-mojo.html))
```xml
<properties>
<kotlin.version>1.3.61</kotlin.version>
<kotlinx-coroutines.version>1.3.3</kotlinx-coroutines.version>
<grpc.version>1.25.0</grpc.version>
<protobuf.version>3.10.0</protobuf.version>
<grpc-kotlin.version>0.1.4</grpc-kotlin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-core</artifactId>
<version>${kotlinx-coroutines.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>${grpc.version}</version>
</dependency>
</dependencies>
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.5.0.Final</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.6.1</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}</protocArtifact>
</configuration>
<executions>
<execution>
<goals><goal>compile</goal></goals>
</execution>
<execution>
<id>grpc-java</id>
<goals><goal>compile-custom</goal></goals>
<configuration>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
</execution>
<execution>
<id>grpc-kotlin</id>
<goals><goal>compile-custom</goal></goals>
<configuration>
<pluginId>grpc-kotlin</pluginId>
<pluginArtifact>io.rouz:grpc-kotlin-gen:${grpc-kotlin.version}:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
</execution>
</executions>
</plugin>
<!-- make sure to add the generated source directories to the kotlin-maven-plugin -->
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<goals><goal>compile</goal></goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
<sourceDir>${project.basedir}/target/generated-sources/protobuf/grpc-kotlin</sourceDir>
<sourceDir>${project.basedir}/target/generated-sources/protobuf/grpc-java</sourceDir>
<sourceDir>${project.basedir}/target/generated-sources/protobuf/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
```
## Gradle configuration
Add the `grpc-kotlin-gen` plugin to the plugins section of `protobuf-gradle-plugin`
```gradle
def protobufVersion = '3.10.0'
def grpcVersion = '1.25.0'
def grpcKotlinVersion = '0.1.4'
protobuf {
protoc {
// The artifact spec for the Protobuf Compiler
artifact = "com.google.protobuf:protoc:${protobufVersion}"
}
plugins {
grpc {
artifact = "io.grpc:protoc-gen-grpc-java:${grpcVersion}"
}
grpckotlin {
artifact = "io.rouz:grpc-kotlin-gen:${grpcKotlinVersion}"
}
}
generateProtoTasks {
all()*.plugins {
grpc {}
grpckotlin {}
}
}
}
```
Add the kotlin dependencies
```gradle
def kotlinVersion = '1.3.61'
def kotlinCoroutinesVersion = '1.3.3'
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion"
compile "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlinCoroutinesVersion"
}
```
## Examples
This is a list of example gRPC services and clients written using this project
- [`grpc-kotlin-example-chatserver`](grpc-kotlin-example-chatserver)
- [`kotlin-grpc-sample`](https://github.com/FlavioF/kotlin-grpc-sample)
- [`grpc-death-star`](https://github.com/leveretka/grpc-death-star)
## RPC method type reference
### Unary call
> `rpc Greet (GreetRequest) returns (GreetReply);`
#### Service
A suspendable function which returns a single message.
```kotlin
override suspend fun greet(request: GreetRequest): GreetReply {
// return GreetReply message
}
```
#### Client
Suspendable call returning a single message.
```kotlin
val response: GreetReply = stub.greet( /* GreetRequest */ )
```
### Client streaming call
> `rpc GreetClientStream (stream GreetRequest) returns (GreetReply);`
#### Service
A suspendable function which returns a single message, and receives messages from a `ReceiveChannel<T>`.
```kotlin
override suspend fun greetClientStream(requestChannel: ReceiveChannel<GreetRequest>): GreetReply {
// receive request messages
val firstRequest = requestChannel.receive()
// or iterate all request messages
for (request in requestChannel) {
// ...
}
// return GreetReply message
}
```
#### Client
Using `send()` and `close()` on `SendChannel<T>`.
```kotlin
val call: ManyToOneCall<GreetRequest, GreetReply> = stub.greetClientStream()
call.send( /* GreetRequest */ )
call.send( /* GreetRequest */ )
call.close() // don't forget to close the send channel
val responseMessage = call.await()
```
### Server streaming call
> `rpc GreetServerStream (GreetRequest) returns (stream GreetReply);`
#### Service
Using `produce` and `send()` to send a stream of messages.
```kotlin
override fun greetServerStream(request: GreetRequest) = produce<GreetReply> {
send( /* GreetReply message */ )
send( /* GreetReply message */ )
// ...
}
```
Note that `close()` or `close(Throwable)` should not be used, see [Exception handling](#exception-handling).
In `kotlinx-coroutines-core:1.0.0` `produce` is marked with `@ExperimentalCoroutinesApi`. In order
to use it, mark your server class with `@UseExperimental(ExperimentalCoroutinesApi::class)` and
add the `-Xuse-experimental=kotlin.Experimental` compiler flag.
#### Client
Using `receive()` on `ReceiveChannel<T>` or iterating with a `for` loop.
```kotlin
val responses: ReceiveChannel<GreetReply> = stub.greetServerStream( /* GreetRequest */ )
// await individual responses
val responseMessage = serverResponses.receive()
// or iterate all responses
for (responseMessage in responses) {
// ...
}
```
### Full bidirectional streaming call
> `rpc GreetBidirectional (stream GreetRequest) returns (stream GreetReply);`
#### Service
Using `produce` and `send()` to send a stream of messages. Receiving messages from a `ReceiveChannel<T>`.
```kotlin
override fun greetBidirectional(requestChannel: ReceiveChannel<GreetRequest>) = produce<GreetReply> {
// receive request messages
val firstRequest = requestChannel.receive()
send( /* GreetReply message */ )
val more = requestChannel.receive()
send( /* GreetReply message */ )
// ...
}
```
Note that `close()` or `close(Throwable)` should not be used, see [Exception handling](#exception-handling).
In `kotlinx-coroutines-core:1.0.0` `produce` is marked with `@ExperimentalCoroutinesApi`. In order
to use it, mark your server class with `@UseExperimental(ExperimentalCoroutinesApi::class)` and
add the `-Xuse-experimental=kotlin.Experimental` compiler flag.
#### Client
Using both a `SendChannel<T>` and a `ReceiveChannel<T>` to interact with the call.
```kotlin
val call: ManyToManyCall<GreetRequest, GreetReply> = stub.greetBidirectional()
launch {
for (responseMessage in call) {
log.info(responseMessage)
}
log.info("no more replies")
}
call.send( /* GreetRequest */ )
call.send( /* GreetRequest */ )
call.close() // don't forget to close the send channel
```
[protoc]: https://www.xolstice.org/protobuf-maven-plugin/examples/protoc-plugin.html
[`suspend`]: https://kotlinlang.org/docs/reference/coroutines-overview.html
[coroutine primitives]: https://github.com/Kotlin/kotlinx.coroutines
[core coroutine primitives]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/
[Exception handling]: https://kotlinlang.org/docs/reference/coroutines/exception-handling.html
[`Channel`]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/-channel/index.html
[`Deferred`]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/-deferred/index.html
[`async`]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental/async.html
[`produce`]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.experimental.channels/produce.html
[`Context`]: https://grpc.io/grpc-java/javadoc/io/grpc/Context.html
[gRPC]: https://grpc.io/
[reactive bindings]: https://github.com/salesforce/reactive-grpc
================================================
FILE: grpc-kotlin-example-chatserver/README.md
================================================
# grpc-kotlin-example-chatserver
A simple command line chat server written using both bidirectional & server streaming gRPC.
Build the parent project. From the repo root, run
```sh
./mvnw clean package
```
Start the server
```sh
java -jar grpc-kotlin-example-chatserver/target/grpc-kotlin-example-chatserver.jar server
```
From another shell, start a bidirectional streaming client
```sh
java -jar grpc-kotlin-example-chatserver/target/grpc-kotlin-example-chatserver.jar client
```
From the third shell, start a server streaming client
```sh
java -jar grpc-kotlin-example-chatserver/target/grpc-kotlin-example-chatserver.jar clientSS
```
---
Big thanks to [Björn Hegerfors](https://github.com/Bj0rnen) and [Emilio Del Tessandoro](https://github.com/emmmile)
for putting together this example!
================================================
FILE: grpc-kotlin-example-chatserver/pom.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.rouz</groupId>
<artifactId>grpc-kotlin-parent</artifactId>
<version>0.1.5-SNAPSHOT</version>
</parent>
<name>grpc-kotlin-example-chatserver</name>
<artifactId>grpc-kotlin-example-chatserver</artifactId>
<packaging>jar</packaging>
<properties>
<kotlin.version>1.3.61</kotlin.version>
<kotlinx-coroutines.version>1.3.3</kotlinx-coroutines.version>
<grpc.version>1.25.0</grpc.version>
<protobuf.version>3.10.0</protobuf.version>
</properties>
<dependencies>
<!-- scope : compile -->
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-core</artifactId>
<version>${kotlinx-coroutines.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-services</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.25</version>
</dependency>
<!-- scope : test -->
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-test-junit</artifactId>
<version>${kotlin.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.5.0.Final</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.6.1</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}</protocArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>grpc-java</id>
<goals>
<goal>compile-custom</goal>
</goals>
<configuration>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}
</pluginArtifact>
</configuration>
</execution>
<execution>
<id>grpc-kotlin</id>
<goals>
<goal>compile-custom</goal>
</goals>
<configuration>
<pluginId>grpc-kotlin</pluginId>
<pluginArtifact>io.rouz:grpc-kotlin-gen:${project.version}:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
<configuration>
<jvmTarget>1.8</jvmTarget>
<args>-Xuse-experimental=kotlin.Experimental</args>
</configuration>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals><goal>compile</goal></goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
<sourceDir>${project.basedir}/target/generated-sources/protobuf/grpc-kotlin</sourceDir>
<sourceDir>${project.basedir}/target/generated-sources/protobuf/grpc-java</sourceDir>
<sourceDir>${project.basedir}/target/generated-sources/protobuf/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>test-compile</id>
<goals>
<goal>test-compile</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/test/kotlin</sourceDir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<executions>
<!-- Replacing default-compile as it is treated specially by maven -->
<execution>
<id>default-compile</id>
<phase>none</phase>
</execution>
<!-- Replacing default-testCompile as it is treated specially by maven -->
<execution>
<id>default-testCompile</id>
<phase>none</phase>
</execution>
<execution>
<id>java-compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>java-test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.1.0.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>io.rouz.grpc.examples.chat.EntrypointKt</mainClass>
<layout>JAR</layout>
<finalName>${project.name}</finalName>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>
================================================
FILE: grpc-kotlin-example-chatserver/src/main/kotlin/io/rouz/grpc/examples/chat/ChatClient.kt
================================================
/*-
* -\-\-
* simple-kotlin-standalone-example
* --
* Copyright (C) 2016 - 2018 rouz.io
* --
* 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.
* -/-/-
*/
package io.rouz.grpc.examples.chat
import io.grpc.ManagedChannelBuilder
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.launch
fun main(args: Array<String>) {
chatClient()
}
fun chatClient() {
val channel = ManagedChannelBuilder.forAddress("localhost", 15001)
.usePlaintext()
.build()
val chatService = ChatServiceGrpc.newStub(channel)
val chat = chatService.chat()
println("type :q to quit")
print("Enter your name: ")
val from = readLine()
chat.send(
ChatMessage.newBuilder()
.setFrom(from)
.build()
)
startPrintLoop(chat)
try {
while (true) {
print("Message: ")
val message = readLine()
if (message == null || message == ":q") {
break
}
chat.send(
ChatMessage.newBuilder()
.setFrom(from)
.setMessage(message)
.build()
)
}
} finally {
println("closing")
chat.close()
}
}
private fun startPrintLoop(chat: ReceiveChannel<ChatMessageFromService>) = GlobalScope.launch {
try {
for (responseMessage in chat) {
val message = responseMessage.message
println("${message.from}: ${message.message}")
}
println("Server disconnected")
} catch (e: Throwable) {
println("Server disconnected badly: $e")
}
}
================================================
FILE: grpc-kotlin-example-chatserver/src/main/kotlin/io/rouz/grpc/examples/chat/ChatService.kt
================================================
/*-
* -\-\-
* simple-kotlin-standalone-example
* --
* Copyright (C) 2016 - 2019 rouz.io
* --
* 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.
* -/-/-
*/
package io.rouz.grpc.examples.chat
import com.google.protobuf.Empty
import com.google.protobuf.Timestamp
import io.grpc.Status
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.launch
import java.time.Instant
import java.util.concurrent.ConcurrentSkipListMap
@UseExperimental(ExperimentalCoroutinesApi::class)
class ChatService : ChatServiceImplBase() {
private val clientChannels = ConcurrentSkipListMap<String, SendChannel<ChatMessageFromService>>()
override suspend fun getNames(request: Empty): ChatRoom {
return ChatRoom.newBuilder()
.addAllNames(clientChannels.keys)
.build()
}
private fun createChannel() = Channel<ChatMessageFromService>(100).apply {
invokeOnClose {
it?.printStackTrace()
}
}
private fun subscribe(name: String, ch: SendChannel<ChatMessageFromService>) {
println("New client connected: $name")
clientChannels.put(name, ch)
?.apply {
println("Close duplicate channel of user: $name")
close()
}
}
private suspend fun broadcast(message: ChatMessage) = createMessage(message)
.let { broadcastMessage ->
println("Broadcast ${message.from}: ${message.message}")
clientChannels.asSequence()
.filterNot { (name, _) -> name == message.from }
.forEach { (other, ch) ->
launch {
try {
println("Sending to $other")
ch.send(broadcastMessage)
} catch (e: Throwable) {
println("$other hung up: ${e.message}. Removing client channel")
clientChannels.remove(other)?.close(e)
}
}
}
}
override fun chat(requests: ReceiveChannel<ChatMessage>): ReceiveChannel<ChatMessageFromService> =
createChannel().also {
GlobalScope.launch {
doChat(requests, it)
}
}
private suspend fun doChat(req: ReceiveChannel<ChatMessage>, resp: SendChannel<ChatMessageFromService>) {
val hello = req.receive()
subscribe(hello.from, resp)
broadcast(hello)
try {
for (chatMessage in req) {
println("Got request from $req:")
println(chatMessage)
broadcast(chatMessage)
}
} catch (t: Throwable) {
println("Threw $t")
if (Status.fromThrowable(t).code != Status.Code.CANCELLED) {
println("An actual error occurred")
t.printStackTrace()
}
} finally {
println("${hello.from} hung up. Removing client channel")
clientChannels.remove(hello.from)
if (!resp.isClosedForSend) {
resp.close()
}
}
}
override suspend fun say(request: ChatMessage): Empty = Empty.getDefaultInstance().also {
broadcast(request)
}
override fun listen(request: WhoAmI): ReceiveChannel<ChatMessageFromService> = createChannel().also {
subscribe(request.name, it)
}
fun shutdown() {
println("Shutting down Chat service")
clientChannels.forEach { (client, channel) ->
println("Closing client channel $client")
channel.close()
}
clientChannels.clear()
}
private fun createMessage(request: ChatMessage) = ChatMessageFromService.newBuilder()
.run {
timestamp = Instant.now().run {
Timestamp.newBuilder().run {
seconds = epochSecond
nanos = nano
build()
}
}
message = request
build()
}
}
================================================
FILE: grpc-kotlin-example-chatserver/src/main/kotlin/io/rouz/grpc/examples/chat/Entrypoint.kt
================================================
/*-
* -\-\-
* simple-kotlin-standalone-example
* --
* Copyright (C) 2016 - 2018 rouz.io
* --
* 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.
* -/-/-
*/
package io.rouz.grpc.examples.chat
fun main(args: Array<String>) {
when(args[0]) {
"server" -> grpcServer()
"client" -> chatClient()
"clientSS" -> serverStreamingChatClient()
}
}
================================================
FILE: grpc-kotlin-example-chatserver/src/main/kotlin/io/rouz/grpc/examples/chat/GrpcServer.kt
================================================
/*-
* -\-\-
* simple-kotlin-standalone-example
* --
* Copyright (C) 2016 - 2018 rouz.io
* --
* 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.
* -/-/-
*/
package io.rouz.grpc.examples.chat
import io.grpc.ServerBuilder
import io.grpc.protobuf.services.ProtoReflectionService
fun main(args: Array<String>) {
grpcServer()
}
fun grpcServer() {
val chatService = ChatService()
val server = ServerBuilder
.forPort(15001)
.addService(ProtoReflectionService.newInstance())
.addService(chatService)
.build()
Runtime.getRuntime().addShutdownHook(Thread {
println("Ups, JVM shutdown")
chatService.shutdown()
server.shutdown()
server.awaitTermination()
println("Chat service stopped")
})
server.start()
println("Chat service started")
server.awaitTermination()
}
================================================
FILE: grpc-kotlin-example-chatserver/src/main/kotlin/io/rouz/grpc/examples/chat/ServerStreaminChatClient.kt
================================================
/*-
* -\-\-
* simple-kotlin-standalone-example
* --
* Copyright (C) 2016 - 2019 rouz.io
* --
* 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.
* -/-/-
*/
package io.rouz.grpc.examples.chat
import io.grpc.ManagedChannelBuilder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.util.concurrent.TimeUnit
fun main() = serverStreamingChatClient()
fun serverStreamingChatClient() {
val channel = ManagedChannelBuilder.forAddress("localhost", 15001)
.usePlaintext()
.build()
val chatService = ChatServiceGrpc.newStub(channel)
println("type :q to quit")
print("Enter your name: ")
val from = readLine()
val listen = chatService.listen(WhoAmI.newBuilder().setName(from).build())
runBlocking(Dispatchers.IO) {
launch {
startPrintLoop(listen)
}
try {
while (true) {
print("Message: ")
val message = readLine()
if (message == null || message == ":q") {
break
}
chatService.say(
ChatMessage.newBuilder()
.setFrom(from)
.setMessage(message)
.build()
)
}
} finally {
println("closing")
channel.shutdownNow().awaitTermination(1, TimeUnit.SECONDS)
println("closed")
}
}
}
private suspend fun startPrintLoop(chat: ReceiveChannel<ChatMessageFromService>) =
try {
for (responseMessage in chat) {
val message = responseMessage.message
println("${message.from}: ${message.message}")
}
println("Server disconnected")
} catch (e: Throwable) {
println("Server disconnected badly: $e")
}
================================================
FILE: grpc-kotlin-example-chatserver/src/main/proto/chat.proto
================================================
syntax = "proto3";
package io.rouz.grpc.examples.chat;
import "google/protobuf/timestamp.proto";
import "google/protobuf/empty.proto";
option java_multiple_files = true;
option java_package = "io.rouz.grpc.examples.chat";
service ChatService {
rpc Chat (stream ChatMessage) returns (stream ChatMessageFromService);
rpc GetNames (google.protobuf.Empty) returns (ChatRoom);
rpc Say(ChatMessage) returns (google.protobuf.Empty);
rpc Listen(WhoAmI) returns (stream ChatMessageFromService);
}
message ChatRoom {
repeated string names = 1;
}
message WhoAmI {
string name = 1;
}
message ChatMessage {
string from = 1;
string message = 2;
}
message ChatMessageFromService {
google.protobuf.Timestamp timestamp = 1;
ChatMessage message = 2;
}
================================================
FILE: grpc-kotlin-gen/pom.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.rouz</groupId>
<artifactId>grpc-kotlin-parent</artifactId>
<version>0.1.5-SNAPSHOT</version>
</parent>
<artifactId>grpc-kotlin-gen</artifactId>
<packaging>jar</packaging>
<name>grpc-kotlin-gen</name>
<properties>
<grpc.version>1.25.0</grpc.version>
</properties>
<dependencies>
<!-- scope : compile -->
<dependency>
<groupId>com.salesforce.servicelibs</groupId>
<artifactId>jprotoc</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>${grpc.version}</version>
</dependency>
<!-- scope : test -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>1.5.8.RELEASE</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>io.rouz.grpc.kotlin.GrpcKotlinGenerator</mainClass>
<layout>JAR</layout>
</configuration>
</plugin>
<plugin>
<groupId>com.salesforce.servicelibs</groupId>
<artifactId>canteen-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<goals>
<goal>bootstrap</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
================================================
FILE: grpc-kotlin-gen/src/main/java/io/rouz/grpc/kotlin/GrpcKotlinGenerator.java
================================================
/*-
* -\-\-
* grpc-kotlin-gen
* --
* Copyright (C) 2016 - 2018 rouz.io
* --
* 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.
* -/-/-
*/
/*
* Copyright (c) 2017, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see https://opensource.org/licenses/BSD-3-Clause
*/
package io.rouz.grpc.kotlin;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.html.HtmlEscapers;
import com.google.protobuf.DescriptorProtos.FileDescriptorProto;
import com.google.protobuf.DescriptorProtos.FileOptions;
import com.google.protobuf.DescriptorProtos.MethodDescriptorProto;
import com.google.protobuf.DescriptorProtos.ServiceDescriptorProto;
import com.google.protobuf.DescriptorProtos.SourceCodeInfo.Location;
import com.google.protobuf.compiler.PluginProtos;
import com.salesforce.jprotoc.Generator;
import com.salesforce.jprotoc.GeneratorException;
import com.salesforce.jprotoc.ProtoTypeMap;
import com.salesforce.jprotoc.ProtocPlugin;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static com.google.protobuf.compiler.PluginProtos.CodeGeneratorRequest;
import static com.google.protobuf.compiler.PluginProtos.CodeGeneratorResponse;
public class GrpcKotlinGenerator extends Generator {
private static final int SERVICE_NUMBER_OF_PATHS = 2;
private static final int METHOD_NUMBER_OF_PATHS = 4;
private static final String CLASS_SUFFIX = "ImplBase";
private static final String STUB_SUFFIX = "StubExt";
private static final String ADAPTERS_FILE_PATH = "io/rouz/grpc/Adapters.kt";
private static final String SERVICE_JAVA_DOC_PREFIX = " ";
private static final String METHOD_JAVA_DOC_PREFIX = " ";
public static void main(String[] args) {
ProtocPlugin.generate(new GrpcKotlinGenerator());
}
@Override
public List<CodeGeneratorResponse.File> generateFiles(CodeGeneratorRequest request)
throws GeneratorException {
final ProtoTypeMap typeMap = ProtoTypeMap.of(request.getProtoFileList());
List<FileDescriptorProto> protosToGenerate = request.getProtoFileList().stream()
.filter(protoFile -> request.getFileToGenerateList().contains(protoFile.getName()))
.collect(Collectors.toList());
List<Context> services = findServices(protosToGenerate, typeMap);
return generateFiles(services);
}
private List<Context> findServices(List<FileDescriptorProto> protos, ProtoTypeMap typeMap) {
List<Context> contexts = new ArrayList<>();
protos.forEach(fileProto -> {
List<Location> locations = fileProto.getSourceCodeInfo().getLocationList();
locations.stream()
.filter(location -> location.getPathCount() == SERVICE_NUMBER_OF_PATHS
&& location.getPath(0) == FileDescriptorProto.SERVICE_FIELD_NUMBER)
.forEach(location -> {
int serviceNumber = location.getPath(SERVICE_NUMBER_OF_PATHS - 1);
Context context = context(
fileProto.getService(serviceNumber), typeMap, locations, serviceNumber);
context.javaDoc = getJavaDoc(getComments(location), SERVICE_JAVA_DOC_PREFIX);
context.protoName = fileProto.getName();
context.packageName = extractPackageName(fileProto);
contexts.add(context);
});
});
return contexts;
}
private String extractPackageName(FileDescriptorProto proto) {
FileOptions options = proto.getOptions();
if (options != null) {
String javaPackage = options.getJavaPackage();
if (!Strings.isNullOrEmpty(javaPackage)) {
return javaPackage;
}
}
return Strings.nullToEmpty(proto.getPackage());
}
private Context context(
ServiceDescriptorProto serviceProto,
ProtoTypeMap protoTypeMap,
List<Location> locations,
int serviceNumber) {
Context context = new Context();
context.serviceName = serviceProto.getName();
context.deprecated = serviceProto.getOptions() != null
&& serviceProto.getOptions().getDeprecated();
locations.stream()
.filter(location -> location.getPathCount() == METHOD_NUMBER_OF_PATHS
&& location.getPath(0) == FileDescriptorProto.SERVICE_FIELD_NUMBER
&& location.getPath(1) == serviceNumber
&& location.getPath(2) == ServiceDescriptorProto.METHOD_FIELD_NUMBER)
.forEach(location -> {
int methodNumber = location.getPath(METHOD_NUMBER_OF_PATHS - 1);
MethodContext methodContext = methodContext(
serviceProto.getMethod(methodNumber), protoTypeMap);
methodContext.methodNumber = methodNumber;
methodContext.javaDoc = getJavaDoc(getComments(location), METHOD_JAVA_DOC_PREFIX);
context.methods.add(methodContext);
});
return context;
}
private MethodContext methodContext(MethodDescriptorProto methodProto, ProtoTypeMap typeMap) {
MethodContext methodContext = new MethodContext();
methodContext.methodName = lowerCaseFirst(methodProto.getName());
methodContext.inputType = typeMap.toJavaTypeName(methodProto.getInputType());
methodContext.outputType = typeMap.toJavaTypeName(methodProto.getOutputType());
methodContext.deprecated = methodProto.getOptions() != null
&& methodProto.getOptions().getDeprecated();
methodContext.isManyInput = methodProto.getClientStreaming();
methodContext.isManyOutput = methodProto.getServerStreaming();
if (!methodProto.getClientStreaming() && !methodProto.getServerStreaming()) {
methodContext.grpcCallsMethodName = "asyncUnaryCall";
}
if (!methodProto.getClientStreaming() && methodProto.getServerStreaming()) {
methodContext.grpcCallsMethodName = "asyncServerStreamingCall";
}
if (methodProto.getClientStreaming() && !methodProto.getServerStreaming()) {
methodContext.grpcCallsMethodName = "asyncClientStreamingCall";
}
if (methodProto.getClientStreaming() && methodProto.getServerStreaming()) {
methodContext.grpcCallsMethodName = "asyncBidiStreamingCall";
}
return methodContext;
}
private String lowerCaseFirst(String s) {
return Character.toLowerCase(s.charAt(0)) + s.substring(1);
}
private List<PluginProtos.CodeGeneratorResponse.File> generateFiles(List<Context> services) {
List<PluginProtos.CodeGeneratorResponse.File> files = new ArrayList<>();
files.add(buildUtilFile());
for (Context service : services) {
files.add(buildServiceBaseImpl(service));
files.add(buildStubExtensions(service));
}
return files;
}
private PluginProtos.CodeGeneratorResponse.File buildUtilFile() {
UtilContext utilContext = new UtilContext();
String content = applyTemplate("Adapters.mustache", utilContext);
return PluginProtos.CodeGeneratorResponse.File
.newBuilder()
.setName(ADAPTERS_FILE_PATH)
.setContent(content)
.build();
}
private PluginProtos.CodeGeneratorResponse.File buildServiceBaseImpl(Context context) {
String content = applyTemplate("ImplBase.mustache", context);
String fileName = context.serviceName + CLASS_SUFFIX + ".kt";
return PluginProtos.CodeGeneratorResponse.File
.newBuilder()
.setName(absoluteFileName(context.packageName, fileName))
.setContent(content)
.build();
}
PluginProtos.CodeGeneratorResponse.File buildStubExtensions(Context context) {
String content = applyTemplate("StubExtensions.mustache", context);
String fileName = context.serviceName + STUB_SUFFIX + ".kt";
return PluginProtos.CodeGeneratorResponse.File
.newBuilder()
.setName(absoluteFileName(context.packageName, fileName))
.setContent(content)
.build();
}
private static String absoluteFileName(String packageName, String fileName) {
Preconditions.checkNotNull(packageName, "packageName");
String dir = packageName.replace('.', '/');
if (Strings.isNullOrEmpty(dir)) {
return fileName;
} else {
return dir + "/" + fileName;
}
}
private String getComments(Location location) {
return location.getLeadingComments().isEmpty()
? location.getTrailingComments()
: location.getLeadingComments();
}
private String getJavaDoc(String comments, String prefix) {
if (!comments.isEmpty()) {
StringBuilder builder = new StringBuilder("/**\n")
.append(prefix).append(" * <pre>\n");
Arrays.stream(HtmlEscapers.htmlEscaper().escape(comments).split("\n"))
// Kotlin allows nested block comments, so any occurrence of '/*' would begin
// a nested block, breaking the generated code.
.map(line -> line.replace("/*", "/*"))
.map(line -> line.replace("*/", "*/"))
.forEach(line -> builder.append(prefix).append(" * ").append(line).append("\n"));
builder
.append(prefix).append(" * <pre>\n")
.append(prefix).append(" */");
return builder.toString();
}
return null;
}
/**
* Template class for proto Service objects.
*/
protected final class Context {
// CHECKSTYLE DISABLE VisibilityModifier FOR 6 LINES
public String protoName;
public String packageName;
public String serviceName;
public boolean deprecated;
public String javaDoc;
public List<MethodContext> methods = new ArrayList<>();
}
/**
* Template class for proto RPC objects.
*/
private class MethodContext {
// CHECKSTYLE DISABLE VisibilityModifier FOR 10 LINES
public String methodName;
public String inputType;
public String outputType;
public boolean deprecated;
public boolean isManyInput;
public boolean isManyOutput;
public String grpcCallsMethodName;
public int methodNumber;
public String javaDoc;
// This method mimics the upper-casing method ogf gRPC to ensure compatibility
// See https://github.com/grpc/grpc-java/blob/v1.8.0/compiler/src/java_plugin/cpp/java_generator.cpp#L58
public String methodNameUpperUnderscore() {
StringBuilder s = new StringBuilder();
for (int i = 0; i < methodName.length(); i++) {
char c = methodName.charAt(i);
s.append(Character.toUpperCase(c));
if ((i < methodName.length() - 1)
&& Character.isLowerCase(c)
&& Character.isUpperCase(methodName.charAt(i + 1))) {
s.append('_');
}
}
return s.toString();
}
public String methodNamePascalCase() {
return String.valueOf(Character.toUpperCase(methodName.charAt(0))) + methodName.substring(1);
}
}
/**
* Template class for adapters file.
*/
private class UtilContext {
}
}
================================================
FILE: grpc-kotlin-gen/src/main/resources/Adapters.mustache
================================================
package io.rouz.grpc
import io.grpc.Context
import io.grpc.stub.StreamObserver
import kotlin.coroutines.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
class ManyToOneCall<in TRequest, out TResponse>(
private val request: StreamObserver<TRequest>,
private val response: Deferred<TResponse>
) : StreamObserverSendAdapter<TRequest>(request),
Deferred<TResponse> by response
class ManyToManyCall<in TRequest, out TResponse>(
private val request: StreamObserver<TRequest>,
private val response: ReceiveChannel<TResponse>
) : StreamObserverSendAdapter<TRequest>(request),
ReceiveChannel<TResponse> by response
open class StreamObserverSendAdapter<in E>(private val streamObserver: StreamObserver<E>) {
fun close(cause: Throwable? = null): Boolean {
if (cause != null) {
streamObserver.onError(cause)
} else {
streamObserver.onCompleted()
}
return true
}
fun send(element: E) {
streamObserver.onNext(element)
}
}
class ContinuationStreamObserver<E>(
private val continuation: Continuation<E>
) : StreamObserver<E> {
override fun onNext(value: E) {
continuation.resume(value)
}
override fun onError(t: Throwable) {
continuation.resumeWithException(t)
}
override fun onCompleted() {}
}
class StreamObserverDeferred<E>(
private val deferred: CompletableDeferred<E> = CompletableDeferred()
) : StreamObserver<E>, Deferred<E> by deferred {
override fun onNext(value: E) {
deferred.complete(value)
}
override fun onError(t: Throwable) {
deferred.completeExceptionally(t)
}
override fun onCompleted() { /* nothing */
}
}
class StreamObserverChannel<E>(
private val channel: Channel<E> = Channel<E>(Channel.UNLIMITED)
) : StreamObserver<E>, ReceiveChannel<E> by channel {
override fun onNext(value: E) {
channel.offer(value)
}
override fun onError(t: Throwable?) {
channel.close(cause = t)
}
override fun onCompleted() {
channel.close(cause = null)
}
}
class ContextCoroutineContextElement : ThreadContextElement<Context> {
companion object Key : CoroutineContext.Key<ContextCoroutineContextElement>
private val grpcContext: Context = Context.current()
override val key: CoroutineContext.Key<ContextCoroutineContextElement>
get() = Key
override fun updateThreadContext(context: CoroutineContext): Context =
grpcContext.attach()
override fun restoreThreadContext(context: CoroutineContext, oldState: Context) =
grpcContext.detach(oldState)
}
================================================
FILE: grpc-kotlin-gen/src/main/resources/ImplBase.mustache
================================================
{{#packageName}}
package {{packageName}}
{{/packageName}}
import {{packageName}}.{{serviceName}}Grpc.*
import io.grpc.*
import io.grpc.stub.*
import io.rouz.grpc.*
import kotlin.coroutines.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
{{#javaDoc}}{{{javaDoc}}}{{/javaDoc}}
{{#deprecated}}@Deprecated("deprecated"){{/deprecated}}
@javax.annotation.Generated(
value = ["by gRPC Kotlin generator"],
comments = "Source: {{protoName}}"
)
abstract class {{serviceName}}ImplBase(
coroutineContext: CoroutineContext = Dispatchers.Default
) : BindableService, CoroutineScope {
private val _coroutineContext: CoroutineContext = coroutineContext
override val coroutineContext: CoroutineContext
get() = ContextCoroutineContextElement() + _coroutineContext
{{#methods}}
{{#javaDoc}}{{{javaDoc}}}{{/javaDoc}}
{{#deprecated}}@Deprecated("deprecated"){{/deprecated}}
{{^isManyInput}}
{{^isManyOutput}}
{{! == unary req, unary resp == }}
open suspend fun {{methodName}}(request: {{inputType}}): {{outputType}} {
throw unimplemented(get{{methodNamePascalCase}}Method()).asRuntimeException()
}
internal fun {{methodName}}Internal(
request: {{inputType}},
responseObserver: StreamObserver<{{outputType}}>
) {
launch {
tryCatchingStatus(responseObserver) {
val response = {{methodName}}(request)
onNext(response)
}
}
}
{{/isManyOutput}}
{{#isManyOutput}}
{{! == unary req, streaming resp == }}
open fun {{methodName}}(request: {{inputType}}): ReceiveChannel<{{outputType}}> {
throw unimplemented(get{{methodNamePascalCase}}Method()).asRuntimeException()
}
internal fun {{methodName}}Internal(
request: {{inputType}},
responseObserver: StreamObserver<{{outputType}}>
) {
launch {
tryCatchingStatus(responseObserver) {
val responses = {{methodName}}(request)
for (response in responses) {
try {
onNext(response)
} catch (e: Throwable) {
responses.cancel()
throw e
}
}
}
}
}
{{/isManyOutput}}
{{/isManyInput}}
{{#isManyInput}}
{{^isManyOutput}}
{{! == streaming req, unary resp == }}
open suspend fun {{methodName}}(requests: ReceiveChannel<{{inputType}}>): {{outputType}} {
throw unimplemented(get{{methodNamePascalCase}}Method()).asRuntimeException()
}
internal fun {{methodName}}Internal(
responseObserver: StreamObserver<{{outputType}}>
): StreamObserver<{{inputType}}> {
val requests = StreamObserverChannel<{{inputType}}>()
launch {
tryCatchingStatus(responseObserver) {
val response = {{methodName}}(requests)
onNext(response)
}
}
return requests
}
{{/isManyOutput}}
{{#isManyOutput}}
{{! == streaming req, streaming resp == }}
open fun {{methodName}}(requests: ReceiveChannel<{{inputType}}>): ReceiveChannel<{{outputType}}> {
throw unimplemented(get{{methodNamePascalCase}}Method()).asRuntimeException()
}
internal fun {{methodName}}Internal(
responseObserver: StreamObserver<{{outputType}}>
): StreamObserver<{{inputType}}> {
val requests = StreamObserverChannel<{{inputType}}>()
launch {
tryCatchingStatus(responseObserver) {
val responses = {{methodName}}(requests)
for (response in responses) {
try {
onNext(response)
} catch (e: Throwable) {
responses.cancel()
throw e
}
}
}
}
return requests
}
{{/isManyOutput}}
{{/isManyInput}}
{{/methods}}
override fun bindService(): ServerServiceDefinition {
return ServerServiceDefinition.builder(getServiceDescriptor())
{{#methods}}
.addMethod(
get{{methodNamePascalCase}}Method(),
ServerCalls.{{grpcCallsMethodName}}(
MethodHandlers(METHODID_{{methodNameUpperUnderscore}})
)
)
{{/methods}}
.build()
}
private fun unimplemented(methodDescriptor: MethodDescriptor<*, *>): Status {
return Status.UNIMPLEMENTED
.withDescription("Method ${methodDescriptor.fullMethodName} is unimplemented")
}
private fun <E> handleException(t: Throwable?, responseObserver: StreamObserver<E>) {
when (t) {
null -> return
is CancellationException -> handleException(t.cause, responseObserver)
is StatusException, is StatusRuntimeException -> responseObserver.onError(t)
is RuntimeException -> {
responseObserver.onError(Status.UNKNOWN.asRuntimeException())
throw t
}
is Exception -> {
responseObserver.onError(Status.UNKNOWN.asException())
throw t
}
else -> {
responseObserver.onError(Status.INTERNAL.asException())
throw t
}
}
}
private suspend fun <E> tryCatchingStatus(responseObserver: StreamObserver<E>, body: suspend StreamObserver<E>.() -> Unit) {
try {
responseObserver.body()
responseObserver.onCompleted()
} catch (t: Throwable) {
handleException(t, responseObserver)
}
}
{{#methods}}
private val METHODID_{{methodNameUpperUnderscore}} = {{methodNumber}}
{{/methods}}
private inner class MethodHandlers<Req, Resp> internal constructor(
private val methodId: Int
) : ServerCalls.UnaryMethod<Req, Resp>,
ServerCalls.ServerStreamingMethod<Req, Resp>,
ServerCalls.ClientStreamingMethod<Req, Resp>,
ServerCalls.BidiStreamingMethod<Req, Resp> {
@Suppress("UNCHECKED_CAST")
override fun invoke(request: Req, responseObserver: StreamObserver<Resp>) {
when (methodId) {
{{#methods}}
{{^isManyInput}}
METHODID_{{methodNameUpperUnderscore}} ->
this@{{serviceName}}ImplBase.{{methodName}}Internal(
request as {{inputType}},
responseObserver as StreamObserver<{{outputType}}>
)
{{/isManyInput}}
{{/methods}}
else -> throw AssertionError()
}
}
@Suppress("UNCHECKED_CAST")
override fun invoke(responseObserver: StreamObserver<Resp>): StreamObserver<Req> {
when (methodId) {
{{#methods}}
{{#isManyInput}}
METHODID_{{methodNameUpperUnderscore}} ->
return this@{{serviceName}}ImplBase.{{methodName}}Internal(
responseObserver as StreamObserver<{{outputType}}>
) as StreamObserver<Req>
{{/isManyInput}}
{{/methods}}
else -> throw AssertionError()
}
}
}
}
================================================
FILE: grpc-kotlin-gen/src/main/resources/StubExtensions.mustache
================================================
{{#packageName}}
package {{packageName}}
{{/packageName}}
import io.rouz.grpc.*
import {{packageName}}.{{serviceName}}Grpc.{{serviceName}}Stub
import kotlinx.coroutines.channels.ReceiveChannel
import kotlin.coroutines.suspendCoroutine
import io.grpc.Metadata
import io.grpc.stub.MetadataUtils
/**
* Kotlin extension functions for [{{packageName}}.{{serviceName}}Grpc.{{serviceName}}Stub]
*
* Generated by gRPC Kotlin generator
* Source: {{protoName}}
*/
{{#methods}}
{{#javaDoc}}{{{javaDoc}}}{{/javaDoc}}
{{#deprecated}}@Deprecated("deprecated"){{/deprecated}}
{{^isManyInput}}
{{^isManyOutput}}
{{! == unary req, unary resp == }}
suspend inline fun {{serviceName}}Stub.{{methodName}}(request: {{inputType}}): {{outputType}} {
return suspendCoroutine {
{{methodName}}(request, ContinuationStreamObserver(it))
}
}
{{/isManyOutput}}
{{#isManyOutput}}
{{! == unary req, streaming resp == }}
fun {{serviceName}}Stub.{{methodName}}(request: {{inputType}}): ReceiveChannel<{{outputType}}> {
val responseChannel = StreamObserverChannel<{{outputType}}>()
{{methodName}}(request, responseChannel)
return responseChannel
}
{{/isManyOutput}}
{{/isManyInput}}
{{#isManyInput}}
{{^isManyOutput}}
{{! == streaming req, unary resp == }}
fun {{serviceName}}Stub.{{methodName}}(): ManyToOneCall<{{inputType}}, {{outputType}}> {
val responseDeferred = StreamObserverDeferred<{{outputType}}>()
val requestObserver = {{methodName}}(responseDeferred)
return ManyToOneCall(requestObserver, responseDeferred)
}
{{/isManyOutput}}
{{#isManyOutput}}
{{! == streaming req, streaming resp == }}
fun {{serviceName}}Stub.{{methodName}}(): ManyToManyCall<{{inputType}}, {{outputType}}> {
val responseChannel = StreamObserverChannel<{{outputType}}>()
val requestObserver = {{methodName}}(responseChannel)
return ManyToManyCall(requestObserver, responseChannel)
}
{{/isManyOutput}}
{{/isManyInput}}
{{/methods}}
/**
* Adds new binary header and returns the client
*/
fun {{serviceName}}Stub.addBinaryHeader(
header: String,
bytes: ByteArray
): {{serviceName}}Stub {
val headers = Metadata()
val key = Metadata.Key.of(header, Metadata.BINARY_BYTE_MARSHALLER)
headers.put(key, bytes)
return MetadataUtils.attachHeaders(this, headers)
}
================================================
FILE: grpc-kotlin-gen/src/test/java/io/rouz/grpc/kotlin/GrpcKotlinGeneratorTest.java
================================================
/*-
* -\-\-
* grpc-kotlin-gen
* --
* Copyright (C) 2016 - 2018 rouz.io
* --
* 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.
* -/-/-
*/
package io.rouz.grpc.kotlin;
import com.google.protobuf.compiler.PluginProtos;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class GrpcKotlinGeneratorTest extends GrpcKotlinGenerator {
@Test
public void buildStubExtensionsTest() {
Context ctx = new Context();
ctx.packageName = "some.package";
ctx.serviceName = "SomeService";
PluginProtos.CodeGeneratorResponse.File result = this.buildStubExtensions(ctx);
String expected = "fun SomeServiceStub.addBinaryHeader(\n" +
" header: String,\n" +
" bytes: ByteArray\n" +
"): SomeServiceStub {\n" +
" val headers = Metadata()\n" +
" val key = Metadata.Key.of(header, Metadata.BINARY_BYTE_MARSHALLER)\n" +
" headers.put(key, bytes)\n" +
"\n" +
" return MetadataUtils.attachHeaders(this, headers)\n" +
"}";
String resultContent = result.getContent().replaceAll("\\r", "");
assertTrue(resultContent.contains(expected));
}
}
================================================
FILE: grpc-kotlin-test/pom.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.rouz</groupId>
<artifactId>grpc-kotlin-parent</artifactId>
<version>0.1.5-SNAPSHOT</version>
</parent>
<name>grpc-kotlin-test</name>
<artifactId>grpc-kotlin-test</artifactId>
<packaging>jar</packaging>
<properties>
<kotlin.version>1.3.61</kotlin.version>
<kotlinx-coroutines.version>1.3.3</kotlinx-coroutines.version>
<grpc.version>1.25.0</grpc.version>
<protobuf.version>3.10.0</protobuf.version>
</properties>
<dependencies>
<!-- scope : compile -->
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
<version>${kotlin.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlinx</groupId>
<artifactId>kotlinx-coroutines-core</artifactId>
<version>${kotlinx-coroutines.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.github.microutils</groupId>
<artifactId>kotlin-logging</artifactId>
<version>1.4.9</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
<!-- scope : test -->
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-testing</artifactId>
<version>${grpc.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.5.0.Final</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.6.1</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:${protobuf.version}:exe:${os.detected.classifier}
</protocArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>grpc-java</id>
<goals>
<goal>compile-custom</goal>
</goals>
<configuration>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}
</pluginArtifact>
</configuration>
</execution>
<execution>
<id>grpc-kotlin</id>
<goals>
<goal>compile-custom</goal>
</goals>
<configuration>
<pluginId>grpc-kotlin</pluginId>
<pluginArtifact>io.rouz:grpc-kotlin-gen:${project.version}:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
<configuration>
<jvmTarget>1.8</jvmTarget>
<args>-Xuse-experimental=kotlin.Experimental</args>
</configuration>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
<sourceDir>${project.basedir}/target/generated-sources/protobuf/grpc-kotlin</sourceDir>
<sourceDir>${project.basedir}/target/generated-sources/protobuf/grpc-java</sourceDir>
<sourceDir>${project.basedir}/target/generated-sources/protobuf/java</sourceDir>
</sourceDirs>
</configuration>
</execution>
<execution>
<id>test-compile</id>
<goals>
<goal>test-compile</goal>
</goals>
<configuration>
<sourceDirs>
<sourceDir>${project.basedir}/src/test/kotlin</sourceDir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<executions>
<!-- Replacing default-compile as it is treated specially by maven -->
<execution>
<id>default-compile</id>
<phase>none</phase>
</execution>
<!-- Replacing default-testCompile as it is treated specially by maven -->
<execution>
<id>default-testCompile</id>
<phase>none</phase>
</execution>
<execution>
<id>java-compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>java-test-compile</id>
<phase>test-compile</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>
================================================
FILE: grpc-kotlin-test/src/main/kotlin/io/rouz/greeter/GreeterImpl.kt
================================================
/*-
* -\-\-
* grpc-kotlin-test
* --
* Copyright (C) 2016 - 2018 rouz.io
* --
* 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.
* -/-/-
*/
package io.rouz.greeter
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import mu.KotlinLogging
import java.util.concurrent.Executors.newFixedThreadPool
/**
* Implementation of coroutine-based gRPC service defined in greeter.proto
*/
@UseExperimental(ExperimentalCoroutinesApi::class)
open class GreeterImpl : GreeterImplBase(
coroutineContext = newFixedThreadPool(4, threadFactory("server-worker-%d")).asCoroutineDispatcher()
) {
protected val log = KotlinLogging.logger("server")
override suspend fun greet(request: GreetRequest): GreetReply {
log.info(request.greeting)
return GreetReply.newBuilder()
.setReply("Hello " + request.greeting)
.build()
}
override fun greetServerStream(request: GreetRequest) = produce<GreetReply> {
log.info(request.greeting)
send(
GreetReply.newBuilder()
.setReply("Hello ${request.greeting}!")
.build()
)
send(
GreetReply.newBuilder()
.setReply("Greetings ${request.greeting}!")
.build()
)
}
override suspend fun greetClientStream(requests: ReceiveChannel<GreetRequest>): GreetReply {
val greetings = mutableListOf<String>()
for (request in requests) {
log.info(request.greeting)
greetings.add(request.greeting)
}
return GreetReply.newBuilder()
.setReply("Hi to all of $greetings!")
.build()
}
override fun greetBidirectional(requests: ReceiveChannel<GreetRequest>) = produce<GreetReply> {
var count = 0
for (request in requests) {
val n = count++
log.info("$n ${request.greeting}")
launch {
delay(100)
send(
GreetReply.newBuilder()
.setReply("Yo #$n ${request.greeting}")
.build()
)
log.info("dispatched $n")
}
}
log.info("completing")
}
}
================================================
FILE: grpc-kotlin-test/src/main/kotlin/io/rouz/greeter/GreeterMain.kt
================================================
/*-
* -\-\-
* grpc-kotlin-test
* --
* Copyright (C) 2016 - 2018 rouz.io
* --
* 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.
* -/-/-
*/
package io.rouz.greeter
import com.google.common.util.concurrent.ThreadFactoryBuilder
import io.grpc.ManagedChannelBuilder
import io.grpc.ServerBuilder
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import mu.KotlinLogging
import java.util.concurrent.ThreadFactory
fun main(args: Array<String>) {
val log = KotlinLogging.logger("client")
ServerBuilder.forPort(8080)
.addService(GreeterImpl())
.build()
.start()
val localhost = ManagedChannelBuilder.forAddress("localhost", 8080)
.usePlaintext()
.build()
val greeter = GreeterGrpc.newStub(localhost)
runBlocking {
// === Unary call =============================================================================
val unaryResponse = greeter.greet(req("Alice"))
log.info("unary reply = ${unaryResponse.reply}")
// === Server streaming call ==================================================================
val serverResponses = greeter.greetServerStream(req("Bob"))
for (serverResponse in serverResponses) {
log.info("server response = ${serverResponse.reply}")
}
// === Client streaming call ==================================================================
val manyToOneCall = greeter.greetClientStream()
manyToOneCall.send(req("Caroline"))
manyToOneCall.send(req("David"))
manyToOneCall.close()
val oneReply = manyToOneCall.await()
log.info("single reply = ${oneReply.reply}")
// === Bidirectional call =====================================================================
val bidiCall = greeter.greetBidirectional()
launch {
var n = 0
for (greetReply in bidiCall) {
log.info("reply $n = ${greetReply.reply}")
n++
}
log.info("no more replies")
}
delay(200)
bidiCall.send(req("Eve"))
delay(200)
bidiCall.send(req("Fred"))
delay(200)
bidiCall.send(req("Gina"))
bidiCall.close()
}
}
fun req(greeting: String): GreetRequest {
return GreetRequest.newBuilder().setGreeting(greeting).build()
}
fun threadFactory(threadNameFormat: String): ThreadFactory = ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat(threadNameFormat)
.build()
================================================
FILE: grpc-kotlin-test/src/main/kotlin/io/rouz/greeter/InfiniteStreamGreeterImpl.kt
================================================
/*-
* -\-\-
* grpc-kotlin-test
* --
* Copyright (C) 2016 - 2019 rouz.io
* --
* 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.
* -/-/-
*/
package io.rouz.greeter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Semaphore
class InfiniteStreamGreeterImpl : GreeterImpl() {
val subscribers = ConcurrentHashMap<String, Channel<GreetReply>>()
val startupSync = Semaphore(0)
override fun greetServerStream(request: GreetRequest): ReceiveChannel<GreetReply> =
Channel<GreetReply>(100).also {
val name = request.greeting
subscribers[name] = it
log.info("Subscribed: {}", name)
startupSync.release()
}
suspend fun greetAllSubscribers(word: String) {
withContext(Dispatchers.IO) {
subscribers.forEach { (subs, ch) ->
GreetReply.newBuilder().run {
reply = "$word $subs"
build()
}.also {
launch {
try {
ch.send(it)
log.info("Message to client: {}", it.reply)
} catch (e: Throwable) {
log.info("Unsubscribe client: {}", subs)
subscribers.remove(subs)
ch.close()
}
}
}
}
}
}
}
================================================
FILE: grpc-kotlin-test/src/main/proto/io/rouz/greeter.proto
================================================
syntax = "proto3";
package io.rouz.greeter;
option java_package = "io.rouz.greeter";
option java_multiple_files = true;
message GreetRequest {
string greeting = 1;
}
message GreetReply {
string reply = 1;
}
service Greeter {
// Adding some comments to ensure correct parsing with respect to kotlin nested block comments
// /* That should get escaped so that it doesn't start a block comment
// */ That should also get escaped so that it doesn't terminate a javadoc comment block
rpc Greet (GreetRequest) returns (GreetReply);
rpc GreetServerStream (GreetRequest) returns (stream GreetReply);
rpc GreetClientStream (stream GreetRequest) returns (GreetReply);
rpc GreetBidirectional (stream GreetRequest) returns (stream GreetReply);
}
================================================
FILE: grpc-kotlin-test/src/main/proto/io/rouz/kvs.proto
================================================
syntax = "proto3";
package io.rouz.kvs;
import "io/rouz/greeter.proto";
option java_package = "io.rouz.kvs";
message KvsMessage {
string msg = 1;
}
service KeyValueStore {
rpc GetKeyForGreeting (io.rouz.greeter.GreetRequest) returns (io.rouz.greeter.GreetReply);
rpc Dummy (KvsMessage) returns (KvsMessage);
}
================================================
FILE: grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/ClientAbandonTest.kt
================================================
/*-
* -\-\-
* grpc-kotlin-test
* --
* Copyright (C) 2016 - 2019 rouz.io
* --
* 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.
* -/-/-
*/
package io.rouz.greeter
import io.grpc.ManagedChannel
import io.grpc.ManagedChannelBuilder
import io.grpc.netty.NettyServerBuilder
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.yield
import mu.KotlinLogging
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.util.concurrent.TimeUnit.SECONDS
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
@RunWith(JUnit4::class)
class ClientAbandonTest {
private val log = KotlinLogging.logger {}
private val svc = InfiniteStreamGreeterImpl()
private fun server() =
NettyServerBuilder.forPort(16565)
.addService(svc)
.build()
.start()
private fun getChannel() = ManagedChannelBuilder
.forAddress("localhost", 16565)
.usePlaintext()
.build().also {
channels.add(it)
}
private fun dumpSubscribers() =
log.info("Current subscribers: {}", svc.subscribers.keys)
private val serv = server()
private val channels: MutableList<ManagedChannel> = mutableListOf()
@After
fun tearDown() {
channels.forEach { ch ->
if (!ch.shutdownNow().awaitTermination(1, SECONDS)) {
error("Failed to shutdown channel")
}
}
if (!serv.shutdownNow().awaitTermination(1, SECONDS)) {
error("Failed to shutdown server")
}
}
@Test
fun infiniteServerStreamingToSubscribers() {
// Create two subscribers & subscribe them
val rouzStub = GreeterGrpc.newStub(getChannel())
val igorStub = GreeterGrpc.newStub(getChannel())
val rouzCh = rouzStub.greetServerStream(req("rouz"))
val igorCh = igorStub.greetServerStream(req("igor"))
svc.startupSync.acquire(2)
runBlocking {
dumpSubscribers()
assertEquals(setOf("rouz", "igor"), svc.subscribers.keys)
// Publish greeting to all
val rouzJob = launch {
rouzCh.receive().also {
assertEquals("Hello rouz", it.reply)
}
}
val igorJob = launch {
igorCh.receive().also {
assertEquals("Hello igor", it.reply)
}
}
val sendJob = launch {
svc.greetAllSubscribers("Hello")
}
joinAll(rouzJob, igorJob, sendJob)
assertEquals(setOf("rouz", "igor"), svc.subscribers.keys)
// One client disconnects
suspendCoroutine<Unit> {
val ch = igorStub.channel as ManagedChannel
ch.shutdownNow()
it.resume(assertTrue(ch.awaitTermination(1, SECONDS)))
}
// Continue publishing of new greetings
val rouzJob2 = launch {
repeat(4) {
assertEquals("Hola $it rouz", rouzCh.receive().reply)
}
}
// One of the first invocations should close the channel of Igor, the next one should remove subscription.
val senderJob2 = launch {
repeat(4) {
svc.greetAllSubscribers("Hola $it")
yield()
}
}
joinAll(rouzJob2, senderJob2)
// Check that subscription of Igor has gone
dumpSubscribers()
assertEquals(setOf("rouz"), svc.subscribers.keys)
}
}
}
================================================
FILE: grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/ClosingStatusExceptionTest.kt
================================================
/*-
* -\-\-
* grpc-kotlin-test
* --
* Copyright (C) 2016 - 2018 rouz.io
* --
* 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.
* -/-/-
*/
package io.rouz.greeter
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
class ClosingStatusExceptionTest : StatusExceptionTestBase() {
override val service: GreeterImplBase
get() = StatusThrowingGreeter()
@UseExperimental(ExperimentalCoroutinesApi::class)
private inner class StatusThrowingGreeter : GreeterImplBase(collectExceptions) {
override suspend fun greet(request: GreetRequest): GreetReply {
throw notFound("uni")
}
override fun greetServerStream(request: GreetRequest) = produce<GreetReply> {
close(notFound("sstream"))
}
override suspend fun greetClientStream(requests: ReceiveChannel<GreetRequest>): GreetReply {
throw notFound("cstream")
}
override fun greetBidirectional(requests: ReceiveChannel<GreetRequest>) = produce<GreetReply> {
close(notFound("bidi"))
}
}
}
================================================
FILE: grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/ContextBasedGreeterTest.kt
================================================
/*-
* -\-\-
* grpc-kotlin-test
* --
* Copyright (C) 2016 - 2018 rouz.io
* --
* 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.
* -/-/-
*/
package io.rouz.greeter
import io.grpc.Context
import io.grpc.Contexts
import io.grpc.Metadata
import io.grpc.ServerCall
import io.grpc.ServerCallHandler
import io.grpc.ServerInterceptor
import io.grpc.stub.MetadataUtils
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.channels.toList
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.junit.Assert
import org.junit.Test
class ContextBasedGreeterTest : GrpcTestBase() {
companion object {
private val userContextKey = Context.key<String>("user name")
private val userMetadataKey = Metadata.Key.of("User-Name", Metadata.ASCII_STRING_MARSHALLER)
}
@Test
fun contextValueMissing() {
val stub = startServer(ContextGreeter())
runBlocking {
val reply = stub.greet(req("rouz"))
Assert.assertEquals("Hello anonymous", reply.reply)
}
}
@Test
fun contextValuePresent() {
val stub = MetadataUtils.attachHeaders(
startServer(ContextGreeter()),
Metadata().apply { put(userMetadataKey, "Chad") }
)
runBlocking {
val reply = stub.greet(req("rouz"))
Assert.assertEquals("Hello Chad", reply.reply)
}
}
@Test
fun contextTransferredAcrossThreads() {
/*
* This test is intended to ensure that the context gets transferred as expected to child coroutines and multiple
* threads. We ensure this by having the service include the thread ID in the reply and verifying that more than
* one thread issued replies.
*/
val stub = MetadataUtils.attachHeaders(
startServer(ContextGreeter()),
Metadata().apply { put(userMetadataKey, "Jordan") }
)
runBlocking {
val replies = stub.greetServerStream(req("rouz")).toList()
val regex = Regex("Hi #\\d{1,3} Jordan from (\\d+)")
val threadIds = replies
.map { regex.matchEntire(it.reply) }
.onEach { Assert.assertNotNull("Reply did not match '${regex.pattern}'", it) }.filterNotNull()
.map { it.groups[1]?.value }
.onEach { Assert.assertNotNull(it) }.filterNotNull()
.toSet()
Assert.assertNotEquals("All messages were dispatched by a single thread", 1, threadIds.size)
}
}
override fun serverInterceptor(): ServerInterceptor = ServerNameInterceptor
inner class ContextGreeter : GreeterImplBase() {
override suspend fun greet(request: GreetRequest): GreetReply =
repl("Hello ${userContextKey.get() ?: "anonymous"}")
@ExperimentalCoroutinesApi
override fun greetServerStream(request: GreetRequest): ReceiveChannel<GreetReply> = produce {
for (i in 0..99) {
launch {
send(repl("Hi #$i ${userContextKey.get()} from ${Thread.currentThread().id}"))
}
}
}
}
object ServerNameInterceptor : ServerInterceptor {
override fun <ReqT : Any?, RespT : Any?> interceptCall(
call: ServerCall<ReqT, RespT>,
headers: Metadata,
next: ServerCallHandler<ReqT, RespT>
): ServerCall.Listener<ReqT> = headers[userMetadataKey]
?.let {
Contexts.interceptCall(
Context.current().withValue(userContextKey, it),
call,
headers,
next
)
} ?: next.startCall(call, headers)
}
}
================================================
FILE: grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/DelayedClosingStatusExceptionTest.kt
================================================
/*-
* -\-\-
* grpc-kotlin-test
* --
* Copyright (C) 2016 - 2018 rouz.io
* --
* 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.
* -/-/-
*/
package io.rouz.greeter
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.async
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class DelayedClosingStatusExceptionTest : StatusExceptionTestBase() {
override val service: GreeterImplBase
get() = StatusThrowingGreeter()
@UseExperimental(ExperimentalCoroutinesApi::class)
private inner class StatusThrowingGreeter : GreeterImplBase(collectExceptions) {
override suspend fun greet(request: GreetRequest): GreetReply {
async {
delay(10)
throw notFound("uni")
}.await()
}
override fun greetServerStream(request: GreetRequest) = produce<GreetReply> {
launch {
delay(10)
close(notFound("sstream"))
}
}
override suspend fun greetClientStream(requests: ReceiveChannel<GreetRequest>): GreetReply {
async {
delay(10)
throw notFound("cstream")
}.await()
}
override fun greetBidirectional(requests: ReceiveChannel<GreetRequest>) = produce<GreetReply> {
launch {
delay(10)
close(notFound("bidi"))
}
}
}
}
================================================
FILE: grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/DelayedThrowingStatusExceptionTest.kt
================================================
/*-
* -\-\-
* grpc-kotlin-test
* --
* Copyright (C) 2016 - 2018 rouz.io
* --
* 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.
* -/-/-
*/
package io.rouz.greeter
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.async
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@UseExperimental(ExperimentalCoroutinesApi::class)
class DelayedThrowingStatusExceptionTest : StatusExceptionTestBase() {
override val service: GreeterImplBase
get() = StatusThrowingGreeter()
@UseExperimental(ExperimentalCoroutinesApi::class)
private inner class StatusThrowingGreeter : GreeterImplBase(collectExceptions) {
override suspend fun greet(request: GreetRequest): GreetReply {
async {
delay(10)
throw notFound("uni")
}.await()
}
override fun greetServerStream(request: GreetRequest) = produce<GreetReply> {
launch {
delay(10)
throw notFound("sstream")
}
}
override suspend fun greetClientStream(requests: ReceiveChannel<GreetRequest>): GreetReply {
async {
delay(10)
throw notFound("cstream")
}.await()
}
override fun greetBidirectional(requests: ReceiveChannel<GreetRequest>) = produce<GreetReply> {
launch {
delay(10)
throw notFound("bidi")
}
}
}
}
================================================
FILE: grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/ExceptionPropagationTest.kt
================================================
/*-
* -\-\-
* grpc-kotlin-test
* --
* Copyright (C) 2016 - 2018 rouz.io
* --
* 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.
* -/-/-
*/
package io.rouz.greeter
import io.grpc.StatusRuntimeException
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.runBlocking
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.lang.Thread.sleep
@RunWith(JUnit4::class)
class ExceptionPropagationTest : GrpcTestBase() {
@Rule
@JvmField
val expect = ExpectedException.none()
@Test
fun unaryException() {
val stub = startServer(CustomThrowingGreeter())
expect.expect(StatusRuntimeException::class.java)
expect.expectMessage("UNKNOWN")
runBlocking {
stub.greet(req("joe"))
}
}
@Test
fun serverStreamingException() {
val stub = startServer(CustomThrowingGreeter())
expect.expect(StatusRuntimeException::class.java)
expect.expectMessage("UNKNOWN")
runBlocking {
stub.greetServerStream(req("joe")).receive()
}
}
@Test
fun clientStreamingException() {
val stub = startServer(CustomThrowingGreeter())
expect.expect(StatusRuntimeException::class.java)
expect.expectMessage("UNKNOWN")
runBlocking {
stub.greetClientStream().await()
}
}
@Test
fun bidirectionalException() {
val stub = startServer(CustomThrowingGreeter())
expect.expect(StatusRuntimeException::class.java)
expect.expectMessage("UNKNOWN")
runBlocking {
stub.greetBidirectional().receive()
}
}
@Test
fun unaryPropagateCustomException() {
val stub = startServer(CustomThrowingGreeter())
expect.expect(CustomThrowingGreeter.CustomException::class.java)
expect.expectMessage("my app broke uni")
try {
runBlocking {
stub.greet(req("joe"))
}
} catch (t: Throwable) { // silence
}
sleep(100) // wait for worker threads to invoke exception handler
throw seenExceptions[0]
}
@Test
fun serverStreamingPropagateCustomException() {
val stub = startServer(CustomThrowingGreeter())
expect.expect(CustomThrowingGreeter.CustomException::class.java)
expect.expectMessage("my app broke sstream")
try {
runBlocking {
stub.greetServerStream(req("jow")).receive()
}
} catch (t: Throwable) { // silence
}
sleep(100) // wait for worker threads to invoke exception handler
throw seenExceptions[0]
}
@Test
fun clientStreamingPropagateCustomException() {
val stub = startServer(CustomThrowingGreeter())
expect.expect(CustomThrowingGreeter.CustomException::class.java)
expect.expectMessage("my app broke cstream")
try {
runBlocking {
stub.greetClientStream().await()
}
} catch (t: Throwable) { // silence
}
sleep(100) // wait for worker threads to invoke exception handler
throw seenExceptions[0]
}
@Test
fun bidirectionalPropagateCustomException() {
val stub = startServer(CustomThrowingGreeter())
expect.expect(CustomThrowingGreeter.CustomException::class.java)
expect.expectMessage("my app broke bidi")
try {
runBlocking {
stub.greetBidirectional().receive()
}
} catch (t: Throwable) { // silence
}
sleep(100) // wait for worker threads to invoke exception handler
throw seenExceptions[0]
}
@UseExperimental(ExperimentalCoroutinesApi::class)
private inner class CustomThrowingGreeter : GreeterImplBase(collectExceptions) {
override suspend fun greet(request: GreetRequest): GreetReply {
throw broke("uni")
}
override fun greetServerStream(request: GreetRequest) = produce<GreetReply> {
throw broke("sstream")
}
override suspend fun greetClientStream(requests: ReceiveChannel<GreetRequest>): GreetReply {
throw broke("cstream")
}
override fun greetBidirectional(requests: ReceiveChannel<GreetRequest>) = produce<GreetReply> {
throw broke("bidi")
}
private fun broke(description: String): Exception {
return CustomException("my app broke $description")
}
inner class CustomException(message: String) : Exception(message)
}
}
================================================
FILE: grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/GrpcTestBase.kt
================================================
/*-
* -\-\-
* grpc-kotlin-test
* --
* Copyright (C) 2016 - 2018 rouz.io
* --
* 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.
* -/-/-
*/
package io.rouz.greeter
import io.grpc.ClientInterceptor
import io.grpc.ClientInterceptors
import io.grpc.ServerInterceptor
import io.grpc.ServerInterceptors
import io.grpc.testing.GrpcServerRule
import io.rouz.greeter.GreeterGrpc.GreeterStub
import kotlinx.coroutines.CoroutineExceptionHandler
import mu.KotlinLogging
import org.junit.Rule
open class GrpcTestBase {
val log = KotlinLogging.logger("GreeterImplBase")
@Rule
@JvmField
val grpcServer: GrpcServerRule = GrpcServerRule().directExecutor()
protected val seenExceptions = mutableListOf<Throwable>()
protected val collectExceptions = CoroutineExceptionHandler { _, t ->
seenExceptions += t
log.info("Caught exception in exception handler: $t")
}
protected fun startServer(service: GreeterImplBase): GreeterStub {
val serviceDefinition = serverInterceptor()?.let {
ServerInterceptors.intercept(service, it)
} ?: service.bindService()
grpcServer.serviceRegistry.addService(serviceDefinition)
val channel = clientInterceptor()?.let {
ClientInterceptors.intercept(grpcServer.channel, it)
} ?: grpcServer.channel
return GreeterGrpc.newStub(channel)
}
protected open fun serverInterceptor(): ServerInterceptor? = null
protected open fun clientInterceptor(): ClientInterceptor? = null
fun req(greeting: String): GreetRequest {
return GreetRequest.newBuilder().setGreeting(greeting).build()
}
fun repl(reply: String): GreetReply {
return GreetReply.newBuilder().setReply(reply).build()
}
}
================================================
FILE: grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/NoStatusExceptionPropagationTest.kt
================================================
/*-
* -\-\-
* grpc-kotlin-test
* --
* Copyright (C) 2016 - 2018 rouz.io
* --
* 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.
* -/-/-
*/
package io.rouz.greeter
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
import org.junit.After
class NoStatusExceptionPropagationTest : StatusExceptionTestBase() {
override val service: GreeterImplBase
get() = StatusThrowingGreeter()
@After
fun tearDown() {
assert(seenExceptions.isEmpty()) {
"Status exceptions should not reach context handler"
}
}
@UseExperimental(ExperimentalCoroutinesApi::class)
private inner class StatusThrowingGreeter : GreeterImplBase(collectExceptions) {
override suspend fun greet(request: GreetRequest): GreetReply {
throw notFound("uni")
}
override fun greetServerStream(request: GreetRequest) = produce<GreetReply> {
throw notFound("sstream")
}
override suspend fun greetClientStream(requests: ReceiveChannel<GreetRequest>): GreetReply {
throw notFound("cstream")
}
override fun greetBidirectional(requests: ReceiveChannel<GreetRequest>) = produce<GreetReply> {
throw notFound("bidi")
}
}
}
================================================
FILE: grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/ServiceCallsTest.kt
================================================
/*-
* -\-\-
* grpc-kotlin-test
* --
* Copyright (C) 2016 - 2018 rouz.io
* --
* 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.
* -/-/-
*/
package io.rouz.greeter
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class ServiceCallsTest : GrpcTestBase() {
@Test
fun unaryGreet() {
val stub = startServer(GreeterImpl())
runBlocking {
val reply = stub.greet(req("rouz"))
assertEquals("Hello rouz", reply.reply)
}
}
@Test
fun serverStreamingGreet() {
val stub = startServer(GreeterImpl())
runBlocking {
val replies = stub.greetServerStream(req("rouz"))
assertEquals("Hello rouz!", replies.receive().reply)
assertEquals("Greetings rouz!", replies.receive().reply)
}
}
@Test
fun clientStreamingGreet() {
val stub = startServer(GreeterImpl())
runBlocking {
val call = stub.greetClientStream()
call.send(req("rouz"))
call.send(req("delavari"))
call.close()
val reply = call.await()
assertEquals("Hi to all of [rouz, delavari]!", reply.reply)
}
}
@Test
fun bidirectionalGreet() {
val stub = startServer(GreeterImpl())
runBlocking {
val call = stub.greetBidirectional()
call.send(req("rouz"))
val reply1 = call.receive()
assertEquals("Yo #0 rouz", reply1.reply)
call.send(req("delavari"))
val reply2 = call.receive()
assertEquals("Yo #1 delavari", reply2.reply)
call.close()
}
}
}
================================================
FILE: grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/StatusExceptionTestBase.kt
================================================
/*-
* -\-\-
* grpc-kotlin-test
* --
* Copyright (C) 2016 - 2018 rouz.io
* --
* 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.
* -/-/-
*/
package io.rouz.greeter
import io.grpc.Status
import io.grpc.StatusRuntimeException
import kotlinx.coroutines.runBlocking
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
abstract class StatusExceptionTestBase : GrpcTestBase() {
@Rule
@JvmField
val expect = ExpectedException.none()
abstract val service: GreeterImplBase
@Test
fun unaryStatus() {
val stub = startServer(service)
expect.expect(StatusRuntimeException::class.java)
expect.expectMessage("NOT_FOUND: uni")
runBlocking {
stub.greet(req("joe"))
}
}
@Test
fun serverStreamingStatus() {
val stub = startServer(service)
expect.expect(StatusRuntimeException::class.java)
expect.expectMessage("NOT_FOUND: sstream")
runBlocking {
stub.greetServerStream(req("joe")).receive()
}
}
@Test
fun clientStreamingStatus() {
val stub = startServer(service)
expect.expect(StatusRuntimeException::class.java)
expect.expectMessage("NOT_FOUND: cstream")
runBlocking {
stub.greetClientStream().await()
}
}
@Test
fun bidirectionalStatus() {
val stub = startServer(service)
expect.expect(StatusRuntimeException::class.java)
expect.expectMessage("NOT_FOUND: bidi")
runBlocking {
stub.greetBidirectional().receive()
}
}
protected fun notFound(description: String): StatusRuntimeException {
return Status.NOT_FOUND.withDescription(description).asRuntimeException()
}
}
================================================
FILE: grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/ThrowingStatusExceptionTest.kt
================================================
/*-
* -\-\-
* grpc-kotlin-test
* --
* Copyright (C) 2016 - 2018 rouz.io
* --
* 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.
* -/-/-
*/
package io.rouz.greeter
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.produce
class ThrowingStatusExceptionTest : StatusExceptionTestBase() {
override val service: GreeterImplBase
get() = StatusThrowingGreeter()
@UseExperimental(ExperimentalCoroutinesApi::class)
private inner class StatusThrowingGreeter : GreeterImplBase(collectExceptions) {
override suspend fun greet(request: GreetRequest): GreetReply {
throw notFound("uni")
}
override fun greetServerStream(request: GreetRequest) = produce<GreetReply> {
throw notFound("sstream")
}
override suspend fun greetClientStream(requests: ReceiveChannel<GreetRequest>): GreetReply {
throw notFound("cstream")
}
override fun greetBidirectional(requests: ReceiveChannel<GreetRequest>) = produce<GreetReply> {
throw notFound("bidi")
}
}
}
================================================
FILE: grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/UnimplementedStatusTest.kt
================================================
/*-
* -\-\-
* grpc-kotlin-test
* --
* Copyright (C) 2016 - 2018 rouz.io
* --
* 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.
* -/-/-
*/
package io.rouz.greeter
import io.grpc.StatusRuntimeException
import kotlinx.coroutines.runBlocking
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
class UnimplementedStatusTest : GrpcTestBase() {
@Rule
@JvmField
val expect = ExpectedException.none()
@Test
fun unaryUnimplemented() {
val stub = startServer(UnimplementedGreeter())
expect.expect(StatusRuntimeException::class.java)
expect.expectMessage("UNIMPLEMENTED: Method io.rouz.greeter.Greeter/Greet is unimplemented")
runBlocking {
stub.greet(req("anyone there?"))
}
}
@Test
fun clientStreamingUnimplemented() {
val stub = startServer(UnimplementedGreeter())
expect.expect(StatusRuntimeException::class.java)
expect.expectMessage("UNIMPLEMENTED: Method io.rouz.greeter.Greeter/GreetClientStream is unimplemented")
runBlocking {
stub.greetClientStream().await()
}
}
@Test
fun serverStreamingUnimplemented() {
val stub = startServer(UnimplementedGreeter())
expect.expect(StatusRuntimeException::class.java)
expect.expectMessage("UNIMPLEMENTED: Method io.rouz.greeter.Greeter/GreetServerStream is unimplemented")
runBlocking {
stub.greetServerStream(req("anyone there?")).receive()
}
}
@Test
fun bidirectionalUnimplemented() {
val stub = startServer(UnimplementedGreeter())
expect.expect(StatusRuntimeException::class.java)
expect.expectMessage("UNIMPLEMENTED: Method io.rouz.greeter.Greeter/GreetBidirectional is unimplemented")
runBlocking {
stub.greetBidirectional().receive()
}
}
inner class UnimplementedGreeter : GreeterImplBase(collectExceptions)
}
================================================
FILE: mvnw
================================================
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
# TODO classpath?
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
wget "$jarUrl" -O "$wrapperJarPath"
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
curl -o "$wrapperJarPath" "$jarUrl"
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"
================================================
FILE: mvnw.cmd
================================================
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"
FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
echo Found %WRAPPER_JAR%
) else (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"
echo Finished downloading %WRAPPER_JAR%
)
@REM End of extension
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
================================================
FILE: pom.xml
================================================
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.rouz</groupId>
<artifactId>root</artifactId>
<version>2</version>
</parent>
<artifactId>grpc-kotlin-parent</artifactId>
<version>0.1.5-SNAPSHOT</version>
<packaging>pom</packaging>
<name>grpc-kotlin</name>
<url>https://github.com/rouzwawi/grpc-kotlin</url>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<id>rouz</id>
<email>me@rouz.io</email>
<name>Rouzbeh Delavari</name>
</developer>
</developers>
<scm>
<url>https://github.com/rouzwawi/grpc-kotlin</url>
<connection>scm:git:git@github.com:rouzwawi/grpc-kotlin.git</connection>
<developerConnection>scm:git:git@github.com:rouzwawi/grpc-kotlin.git</developerConnection>
<tag>HEAD</tag>
</scm>
<properties>
</properties>
<modules>
<module>grpc-kotlin-gen</module>
<module>grpc-kotlin-test</module>
<module>grpc-kotlin-example-chatserver</module>
</modules>
<dependencies>
<!-- scope : compile -->
<!-- scope : test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-enforcer-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<forkCount>0</forkCount>
</configuration>
</plugin>
</plugins>
</build>
</project>
gitextract_swzgl8ap/ ├── .circleci/ │ └── config.yml ├── .gitignore ├── .mvn/ │ └── wrapper/ │ ├── MavenWrapperDownloader.java │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── LICENSE ├── NOTICE ├── README.md ├── grpc-kotlin-example-chatserver/ │ ├── README.md │ ├── pom.xml │ └── src/ │ └── main/ │ ├── kotlin/ │ │ └── io/ │ │ └── rouz/ │ │ └── grpc/ │ │ └── examples/ │ │ └── chat/ │ │ ├── ChatClient.kt │ │ ├── ChatService.kt │ │ ├── Entrypoint.kt │ │ ├── GrpcServer.kt │ │ └── ServerStreaminChatClient.kt │ └── proto/ │ └── chat.proto ├── grpc-kotlin-gen/ │ ├── pom.xml │ └── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── io/ │ │ │ └── rouz/ │ │ │ └── grpc/ │ │ │ └── kotlin/ │ │ │ └── GrpcKotlinGenerator.java │ │ └── resources/ │ │ ├── Adapters.mustache │ │ ├── ImplBase.mustache │ │ └── StubExtensions.mustache │ └── test/ │ └── java/ │ └── io/ │ └── rouz/ │ └── grpc/ │ └── kotlin/ │ └── GrpcKotlinGeneratorTest.java ├── grpc-kotlin-test/ │ ├── pom.xml │ └── src/ │ ├── main/ │ │ ├── kotlin/ │ │ │ └── io/ │ │ │ └── rouz/ │ │ │ └── greeter/ │ │ │ ├── GreeterImpl.kt │ │ │ ├── GreeterMain.kt │ │ │ └── InfiniteStreamGreeterImpl.kt │ │ └── proto/ │ │ └── io/ │ │ └── rouz/ │ │ ├── greeter.proto │ │ └── kvs.proto │ └── test/ │ └── kotlin/ │ └── io/ │ └── rouz/ │ └── greeter/ │ ├── ClientAbandonTest.kt │ ├── ClosingStatusExceptionTest.kt │ ├── ContextBasedGreeterTest.kt │ ├── DelayedClosingStatusExceptionTest.kt │ ├── DelayedThrowingStatusExceptionTest.kt │ ├── ExceptionPropagationTest.kt │ ├── GrpcTestBase.kt │ ├── NoStatusExceptionPropagationTest.kt │ ├── ServiceCallsTest.kt │ ├── StatusExceptionTestBase.kt │ ├── ThrowingStatusExceptionTest.kt │ └── UnimplementedStatusTest.kt ├── mvnw ├── mvnw.cmd └── pom.xml
SYMBOL INDEX (25 symbols across 3 files)
FILE: .mvn/wrapper/MavenWrapperDownloader.java
class MavenWrapperDownloader (line 25) | public class MavenWrapperDownloader {
method main (line 51) | public static void main(String args[]) {
method downloadFileFromURL (line 100) | private static void downloadFileFromURL(String urlString, File destina...
FILE: grpc-kotlin-gen/src/main/java/io/rouz/grpc/kotlin/GrpcKotlinGenerator.java
class GrpcKotlinGenerator (line 52) | public class GrpcKotlinGenerator extends Generator {
method main (line 62) | public static void main(String[] args) {
method generateFiles (line 66) | @Override
method findServices (line 79) | private List<Context> findServices(List<FileDescriptorProto> protos, P...
method extractPackageName (line 101) | private String extractPackageName(FileDescriptorProto proto) {
method context (line 113) | private Context context(
method methodContext (line 140) | private MethodContext methodContext(MethodDescriptorProto methodProto,...
method lowerCaseFirst (line 164) | private String lowerCaseFirst(String s) {
method generateFiles (line 168) | private List<PluginProtos.CodeGeneratorResponse.File> generateFiles(Li...
method buildUtilFile (line 180) | private PluginProtos.CodeGeneratorResponse.File buildUtilFile() {
method buildServiceBaseImpl (line 191) | private PluginProtos.CodeGeneratorResponse.File buildServiceBaseImpl(C...
method buildStubExtensions (line 201) | PluginProtos.CodeGeneratorResponse.File buildStubExtensions(Context co...
method absoluteFileName (line 211) | private static String absoluteFileName(String packageName, String file...
method getComments (line 221) | private String getComments(Location location) {
method getJavaDoc (line 227) | private String getJavaDoc(String comments, String prefix) {
class Context (line 248) | protected final class Context {
class MethodContext (line 261) | private class MethodContext {
method methodNameUpperUnderscore (line 275) | public String methodNameUpperUnderscore() {
method methodNamePascalCase (line 289) | public String methodNamePascalCase() {
class UtilContext (line 297) | private class UtilContext {
FILE: grpc-kotlin-gen/src/test/java/io/rouz/grpc/kotlin/GrpcKotlinGeneratorTest.java
class GrpcKotlinGeneratorTest (line 29) | public class GrpcKotlinGeneratorTest extends GrpcKotlinGenerator {
method buildStubExtensionsTest (line 31) | @Test
Condensed preview — 43 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (165K chars).
[
{
"path": ".circleci/config.yml",
"chars": 1171,
"preview": "# Java Maven CircleCI 2.0 configuration file\n#\n# Check https://circleci.com/docs/2.0/language-java/ for more details\n#\nv"
},
{
"path": ".gitignore",
"chars": 235,
"preview": "# Build products and artifacts\ntarget/\npom.xml.tag\npom.xml.releaseBackup\npom.xml.versionsBackup\npom.xml.next\nrelease.pro"
},
{
"path": ".mvn/wrapper/MavenWrapperDownloader.java",
"chars": 4473,
"preview": "/*\nLicensed to the Apache Software Foundation (ASF) under one\nor more contributor license agreements. See the NOTICE fi"
},
{
"path": ".mvn/wrapper/maven-wrapper.properties",
"chars": 115,
"preview": "distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.5.4/apache-maven-3.5.4-bin.zip"
},
{
"path": "LICENSE",
"chars": 11357,
"preview": " Apache License\n Version 2.0, January 2004\n "
},
{
"path": "NOTICE",
"chars": 223,
"preview": "File grpc-kotlin-gen/src/main/java/io/rouz/grpc/kotlin/GrpcKotlinGenerator.java\nModified redistribution of ReactiveGrpcG"
},
{
"path": "README.md",
"chars": 19956,
"preview": "# gRPC Kotlin - Coroutine based gRPC for Kotlin\n\n[ 2016 - 2018 rouz.io\n * --\n * Licensed under the "
},
{
"path": "grpc-kotlin-example-chatserver/src/main/kotlin/io/rouz/grpc/examples/chat/ChatService.kt",
"chars": 4977,
"preview": "/*-\n * -\\-\\-\n * simple-kotlin-standalone-example\n * --\n * Copyright (C) 2016 - 2019 rouz.io\n * --\n * Licensed under the "
},
{
"path": "grpc-kotlin-example-chatserver/src/main/kotlin/io/rouz/grpc/examples/chat/Entrypoint.kt",
"chars": 882,
"preview": "/*-\n * -\\-\\-\n * simple-kotlin-standalone-example\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the "
},
{
"path": "grpc-kotlin-example-chatserver/src/main/kotlin/io/rouz/grpc/examples/chat/GrpcServer.kt",
"chars": 1378,
"preview": "/*-\n * -\\-\\-\n * simple-kotlin-standalone-example\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the "
},
{
"path": "grpc-kotlin-example-chatserver/src/main/kotlin/io/rouz/grpc/examples/chat/ServerStreaminChatClient.kt",
"chars": 2475,
"preview": "/*-\n * -\\-\\-\n * simple-kotlin-standalone-example\n * --\n * Copyright (C) 2016 - 2019 rouz.io\n * --\n * Licensed under the "
},
{
"path": "grpc-kotlin-example-chatserver/src/main/proto/chat.proto",
"chars": 784,
"preview": "syntax = \"proto3\";\n\npackage io.rouz.grpc.examples.chat;\n\nimport \"google/protobuf/timestamp.proto\";\nimport \"google/protob"
},
{
"path": "grpc-kotlin-gen/pom.xml",
"chars": 2264,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2"
},
{
"path": "grpc-kotlin-gen/src/main/java/io/rouz/grpc/kotlin/GrpcKotlinGenerator.java",
"chars": 11373,
"preview": "/*-\n * -\\-\\-\n * grpc-kotlin-gen\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, V"
},
{
"path": "grpc-kotlin-gen/src/main/resources/Adapters.mustache",
"chars": 2655,
"preview": "package io.rouz.grpc\n\nimport io.grpc.Context\nimport io.grpc.stub.StreamObserver\nimport kotlin.coroutines.*\nimport kotlin"
},
{
"path": "grpc-kotlin-gen/src/main/resources/ImplBase.mustache",
"chars": 7442,
"preview": "{{#packageName}}\npackage {{packageName}}\n{{/packageName}}\n\nimport {{packageName}}.{{serviceName}}Grpc.*\n\nimport io.grpc."
},
{
"path": "grpc-kotlin-gen/src/main/resources/StubExtensions.mustache",
"chars": 2289,
"preview": "{{#packageName}}\npackage {{packageName}}\n{{/packageName}}\n\nimport io.rouz.grpc.*\nimport {{packageName}}.{{serviceName}}G"
},
{
"path": "grpc-kotlin-gen/src/test/java/io/rouz/grpc/kotlin/GrpcKotlinGeneratorTest.java",
"chars": 1711,
"preview": "/*-\n * -\\-\\-\n * grpc-kotlin-gen\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, V"
},
{
"path": "grpc-kotlin-test/pom.xml",
"chars": 8043,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2"
},
{
"path": "grpc-kotlin-test/src/main/kotlin/io/rouz/greeter/GreeterImpl.kt",
"chars": 2955,
"preview": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, "
},
{
"path": "grpc-kotlin-test/src/main/kotlin/io/rouz/greeter/GreeterMain.kt",
"chars": 3078,
"preview": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, "
},
{
"path": "grpc-kotlin-test/src/main/kotlin/io/rouz/greeter/InfiniteStreamGreeterImpl.kt",
"chars": 2200,
"preview": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2019 rouz.io\n * --\n * Licensed under the Apache License, "
},
{
"path": "grpc-kotlin-test/src/main/proto/io/rouz/greeter.proto",
"chars": 774,
"preview": "syntax = \"proto3\";\npackage io.rouz.greeter;\n\noption java_package = \"io.rouz.greeter\";\noption java_multiple_files = true;"
},
{
"path": "grpc-kotlin-test/src/main/proto/io/rouz/kvs.proto",
"chars": 326,
"preview": "syntax = \"proto3\";\npackage io.rouz.kvs;\n\nimport \"io/rouz/greeter.proto\";\n\noption java_package = \"io.rouz.kvs\";\n\nmessage "
},
{
"path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/ClientAbandonTest.kt",
"chars": 4395,
"preview": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2019 rouz.io\n * --\n * Licensed under the Apache License, "
},
{
"path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/ClosingStatusExceptionTest.kt",
"chars": 1674,
"preview": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, "
},
{
"path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/ContextBasedGreeterTest.kt",
"chars": 4374,
"preview": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, "
},
{
"path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/DelayedClosingStatusExceptionTest.kt",
"chars": 2099,
"preview": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, "
},
{
"path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/DelayedThrowingStatusExceptionTest.kt",
"chars": 2102,
"preview": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, "
},
{
"path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/ExceptionPropagationTest.kt",
"chars": 5315,
"preview": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, "
},
{
"path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/GrpcTestBase.kt",
"chars": 2270,
"preview": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, "
},
{
"path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/NoStatusExceptionPropagationTest.kt",
"chars": 1858,
"preview": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, "
},
{
"path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/ServiceCallsTest.kt",
"chars": 2311,
"preview": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, "
},
{
"path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/StatusExceptionTestBase.kt",
"chars": 2298,
"preview": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, "
},
{
"path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/ThrowingStatusExceptionTest.kt",
"chars": 1673,
"preview": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, "
},
{
"path": "grpc-kotlin-test/src/test/kotlin/io/rouz/greeter/UnimplementedStatusTest.kt",
"chars": 2488,
"preview": "/*-\n * -\\-\\-\n * grpc-kotlin-test\n * --\n * Copyright (C) 2016 - 2018 rouz.io\n * --\n * Licensed under the Apache License, "
},
{
"path": "mvnw",
"chars": 9113,
"preview": "#!/bin/sh\n# ----------------------------------------------------------------------------\n# Licensed to the Apache Softwa"
},
{
"path": "mvnw.cmd",
"chars": 5971,
"preview": "@REM ----------------------------------------------------------------------------\r\n@REM Licensed to the Apache Software "
},
{
"path": "pom.xml",
"chars": 2539,
"preview": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2"
}
]
// ... and 1 more files (download for full content)
About this extraction
This page contains the full source code of the rouzwawi/grpc-kotlin GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 43 files (151.9 KB), approximately 36.5k tokens, and a symbol index with 25 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.