diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + 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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..937effe --- /dev/null +++ b/README.md @@ -0,0 +1,79 @@ +# spring-cloud-gateway-grpc-status-bug + +This repository is an example that describes a bug in spring-cloud-gateway when using grpc and a service returns grpc errors. +Whenever gRPC responses return a status that is results in an error (grpc-status != 0) then gateway does not reply properly. + + +## Project structure +This project contains three main modules: +- Root: spring-cloud-gateway +- grpc-server +- grpc-client + +### spring-cloud-gateway +This is an implementation of gateway to reproduce the buggy behaviour. +The gateway is configured to route traffic for GRPC requests based on the header to localhost:8082 + +### gRPC server +Simple gRPC server that servers one endpoint to pong a request + +### gRPC client +Simple gRPC client with two configs: +- `direct` this profile will directly do calls to the gRPC server +- `gateway` this profile will call the gRPC server via the gateway. + +The client has two command line runners +- One that runs an OK request, this will result in an OK "Pong" response from the gRPC service. +- One that runs a request which will result in an error being returned by the server + +## How to reproduce the bug + +1. Build the project + `./gradlew clean build` + +2. Start the gateway and the grpc server + `./gradlew :bootRun` + `./gradlew :grpc-server:bootRun` + +3. Run the client with direct OK profile to validate grpc server running: + `./gradlew :grpc-client:bootRunDirectOk`. You should see a log with `message: "Pong"` + +4. Run the client with direct Error profile to validate grpc server running and returning an error result: + `./gradlew :grpc-client:bootRunDirectError`. The runner should throw an exception with root cause `io.grpc.StatusRuntimeException: INTERNAL` + +5. Run the client with gateway OK to display correct behaviour + `./gradlew :grpc-client:bootRunGatewayOk`. You should see a log with `message: "Pong"` + +6. Run the client with gateway Error to display the buggy behaviour + `./gradlew :grpc-client:bootRunGatewayError`. The runner will hang because gateway returns a "grpc-status" with value "0" while it should've returned the correct status. + + + +## How to reproduce potential fix +1. Build the project + `./gradlew clean build` + +2. Start the gateway and the grpc server + `./gradlew :bootRun` + `./gradlew :grpc-server:bootRunWithPatchedFilter` +This will run the gateway with a patched filter that properly returns the "grpc-status" as a trailing header. + +3. Run the client with direct OK profile to validate grpc server running: + `./gradlew :grpc-client:bootRunDirectOk`. You should see a log with `message: "Pong"` + +4. Run the client with direct Error profile to validate grpc server running and returning an error result: + `./gradlew :grpc-client:bootRunDirectError`. The runner should throw an exception + +5. Run the client with gateway OK to display correct behaviour + `./gradlew :grpc-client:bootRunGatewayOk`. You should see a log with `message: "Pong"` + +6. Run the client with gateway Error to display the buggy behaviour + `./gradlew :grpc-client:bootRunGatewayError`. the runner will return a correct value + +The fix here is a `PatchedGRPCResponseHeaderFilter` that is run after the default `GRPCResponseHeadersFilter` which returns the `grpc-stats` properly. + +## Bug Explanation +The current `GRPCResponseHeadersFilter` **always** returns the `grpc-status` trailing header with a value "0". +This is an `OK` result according to the gRPC protocol see: [grpc-status-codes](https://grpc.github.io/grpc/core/md_doc_statuscodes.html) + +The `GRPCResponseHeadersFilter` should return a proper `grpc-status` which is copied from the request to properly handle requests that result in an error. \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..7a54550 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,72 @@ +plugins { + `kotlin-dsl` + id("org.springframework.boot") version "2.7.3" + id("io.spring.dependency-management") version "1.0.14.RELEASE" + id("java") +} + +repositories { + mavenCentral() +} + +allprojects { + group = "com.gateway.bugreport" + version = "0.0.1-SNAPSHOT" + + tasks.withType { + sourceCompatibility = "17" + targetCompatibility = "17" + } +} + +subprojects { + repositories { + mavenCentral() + } + + apply { + plugin("io.spring.dependency-management") + } +} + +buildscript { + extra["springCloudVersion"] = "2021.0.4" +} + +dependencies { + implementation("org.springframework.cloud:spring-cloud-starter-gateway") { + exclude(module = "logback-classic") + } + + testImplementation("org.springframework.boot:spring-boot-starter-test"){ + exclude(module = "logback-classic") + } + testImplementation("io.projectreactor:reactor-test") +} + +dependencyManagement { + val springCloudVersion: String by extra + + imports { + mavenBom("org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}") + } +} + +tasks.withType { + useJUnitPlatform() +} + +sourceSets.configureEach { + resources.srcDirs( + layout.projectDirectory.dir("certificate") + ) +} + +tasks.register("bootRunWithPatchedFilter") { + doFirst { + tasks.bootRun.configure { + systemProperty("spring.profiles.active", "patchedFilter") + } + } + finalizedBy("bootRun") +} \ No newline at end of file diff --git a/certificate/localhost.crt b/certificate/localhost.crt new file mode 100644 index 0000000..357261f --- /dev/null +++ b/certificate/localhost.crt @@ -0,0 +1,18 @@ +-----BEGIN CERTIFICATE----- +MIIC5TCCAc2gAwIBAgIJAOmxvWCzR9LoMA0GCSqGSIb3DQEBCwUAMBQxEjAQBgNV +BAMMCWxvY2FsaG9zdDAeFw0yMjA5MjgxNDM4MzFaFw0yMjEwMjgxNDM4MzFaMBQx +EjAQBgNVBAMMCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC +ggEBAKWMK0EHTz+yRFp2/YmwqLKuU6MEfu2KoJdzRp4ruysYtkbACztMRAfqmZM3 +W1GFnBq3G3vZ/5D3pdHkh8F85/VhO9VSP6mDgp33AZz/XTecTM6pltypWPNCQdmF +njjxnCdjSeADmxK5fJtWA4TgYTw4y7AqAPTpJ24718eD4bYCzn9j0nmXYGzW+Cdl +aIBO8HZCSTo55NUJVkBqobEbI1uNLKjy6V+AkyTEgH4xmY2cP5iMoztfWc8hFAuk +bpDUIPWcusL2IOOgql4AQG1TM742L5nlxE5qNrR/g6ODg9v/BZXSFypaAnokayJ5 +Wrja1iBuwgvZkrJgpyru0Ex8fVcCAwEAAaM6MDgwFAYDVR0RBA0wC4IJbG9jYWxo +b3N0MAsGA1UdDwQEAwIHgDATBgNVHSUEDDAKBggrBgEFBQcDATANBgkqhkiG9w0B +AQsFAAOCAQEAJsUC/qN8VyskgZxKHG1tPVYtUzX7CohxIoQX0s89mX4ROLh1Fd3Y +NT/mZ2CcBiM3JqTsjV/rhILrakaYUjBcL1NoMNkDsTY6ZIzVg5iBLlcFgdWAqIau +S7RJsV4kdDbj8ZE6hMx3EyqDNyPmKA1PtxE8eqPEZa9TU7GMYhdG20jMLGD0viwb +3Tn+W9ZKbWgCPM1wpAjrqjUotHJhpWnVsIKIq4bWTHo7RpVR8x4tzys7/SgQ54uW +giWcJrGg7L3ale1ab/k4gcWj7excVmvH5Ka9jCW7gMZQut+rfsyHDnvqnf3rkjVW +PFFEkkDTSl0VstyKbluQJTPQam4mWA/i4Q== +-----END CERTIFICATE----- diff --git a/certificate/localhost.key b/certificate/localhost.key new file mode 100644 index 0000000..b1ef733 --- /dev/null +++ b/certificate/localhost.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCljCtBB08/skRa +dv2JsKiyrlOjBH7tiqCXc0aeK7srGLZGwAs7TEQH6pmTN1tRhZwatxt72f+Q96XR +5IfBfOf1YTvVUj+pg4Kd9wGc/103nEzOqZbcqVjzQkHZhZ448ZwnY0ngA5sSuXyb +VgOE4GE8OMuwKgD06SduO9fHg+G2As5/Y9J5l2Bs1vgnZWiATvB2Qkk6OeTVCVZA +aqGxGyNbjSyo8ulfgJMkxIB+MZmNnD+YjKM7X1nPIRQLpG6Q1CD1nLrC9iDjoKpe +AEBtUzO+Ni+Z5cROaja0f4Ojg4Pb/wWV0hcqWgJ6JGsieVq42tYgbsIL2ZKyYKcq +7tBMfH1XAgMBAAECggEAbFfm+wEYqXw25enYFqPqVD5o+Fh55WaDoXrNLbk7HoJm +0Ljg4OcR4whzh/iDqD/EIWvS7eSHMM4S1OI2wrfHaz0+lmbkyUELW+yLPr+Vt05w +qhQtaq7eSx4C0KR1H5lodBK0B4r0k3WXimXpma3rlSkqjVmAFMj+iFNb7fRu5Nm1 +1aJxZ7Y5pxqu2kiwfc7esNch/1jrOV1BzWznZuQf8IAPrK8xL+8AaZWTVQeDlyEg +WxuloE5wi2ZcTQqcMvXK4I4iYfxACbOcWReibvHdVWt1iMz/OSN8FBfEXk3/Sdgm +w9zDXB3i1xFemfO7FYI2z/OSJJjV5N+plTs3lPPZcQKBgQDTFLf3Ko5lIXOJLQaB +sQEiNxs4lFJbRpoGPVIpHSJ8tbLG0t77McaMRe2mnYUeC7oww4L+cAF1DpmLP2wX +ylWVbL6XR12eusa2Q1uZfHMEWAxWoksz20yMIHokpVzrtrNbNwcM34s0RArb/Jx2 +DaTA/mRjpbHicqrI8Js3wzbuGQKBgQDIxuD7rPWfivztwGyTuUDyPsJ9IwNdlwC8 +p59PII8XS7uibmE/pkYSiqVgsXNy19ImD4YuN1UsnwQmIlLqcQkjKMpy0SPhqem0 +VMcR60Hp5I/nu2UoK8+AACfFfEcErhNlTSWQnd8iyvrUJ7eVS/NJLCAL1AN3zKZp +oCPzETRU7wKBgCe/bgkAHYJTs0LwlJoVb8Y2pEyaOYvwlo54O6F8WAMt3/VqvgyF +SgMeI+tNHEUVJkGKf39ULiIR1r4O+lbchhM2QAmSqcF7IHIv6u7TLYFy5xflRc4F +DLwSXY3LCd1lMQ8LJKu66Ka17WmRfxEH7q9c+CB/kii3OQvPqxrsCsr5AoGAecef +mSfsh8ve5DqN4QBBs217vDkrhm3b5ZHqYC1IfYHTGo/G7rtkz0RHUSHw+5yKe8l4 +wrmPMRR2iMbS8h6Dw06vlPrjv7G27klpwaWngj2/R3hzv+zq3CG7/d4GmYEYhJ5J +hbEsMcdaYqqAgM7jjuNzwJjlTZnU6kZW58zsqAMCgYEAxZ4G4ehBPpn6Qve28q4z +X+1Xg1AQ1Psi/pVVTAGzQg+7N6ecJCn07Co1fObaZ6cF+B0KK8QvTlJX/PzxPIBC +HDafiBtGz5+LVYReJWsE85hUFeB1bluOHdn+8CzUeU95kTTDSMumbkfUhHu2bFXx +hnfOGCE8A9CAevQS3vUwZR4= +-----END PRIVATE KEY----- diff --git a/certificate/localhostP12Keystore.p12 b/certificate/localhostP12Keystore.p12 new file mode 100644 index 0000000..f0e0754 Binary files /dev/null and b/certificate/localhostP12Keystore.p12 differ diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..8049c68 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..a69d9cb --- /dev/null +++ b/gradlew @@ -0,0 +1,240 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# 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 +# +# https://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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +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 + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..f127cfd --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,91 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/grpc-client/build.gradle.kts b/grpc-client/build.gradle.kts new file mode 100644 index 0000000..a10e06b --- /dev/null +++ b/grpc-client/build.gradle.kts @@ -0,0 +1,119 @@ +import com.google.protobuf.gradle.* + +plugins { + id("org.springframework.boot") + id("com.google.protobuf") version "0.8.19" + id("java") +} + + +dependencies { + val versions = object { + val protobuf = "3.19.2" + val grpc = "1.49.0" + val reactorGrpc = "1.2.3" + } + + implementation("org.springframework.boot:spring-boot-starter-webflux") + + implementation("com.google.protobuf:protobuf-java:${versions.protobuf}") + implementation("com.google.protobuf:protobuf-java-util:${versions.protobuf}") + implementation("io.grpc:grpc-stub:${versions.grpc}") + implementation("io.grpc:grpc-protobuf:${versions.grpc}") + implementation("io.grpc:grpc-netty:${versions.grpc}") + implementation("com.salesforce.servicelibs:reactor-grpc:${versions.reactorGrpc}") + implementation("com.salesforce.servicelibs:reactor-grpc-stub:${versions.reactorGrpc}") + + testImplementation("org.junit.jupiter:junit-jupiter-api:5.8.1") + testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.8.1") +} + +tasks.withType { + useJUnitPlatform() +} + +protobuf { + val versions = object { + val protobuf = "3.19.2" + val grpc = "1.49.0" + val reactorGrpc = "1.2.3" + } + protoc { + artifact = "com.google.protobuf:protoc:${versions.protobuf}" + } + plugins { + id("grpc") { + artifact = "io.grpc:protoc-gen-grpc-java:${versions.grpc}" + } + id("reactor") { + artifact = "com.salesforce.servicelibs:reactor-grpc:${versions.reactorGrpc}" + } + } + generateProtoTasks { + ofSourceSet("main").forEach { + it.plugins { + // Apply the "grpc" plugin whose spec is defined above, without + // options. Note the braces cannot be omitted, otherwise the + // plugin will not be added. This is because of the implicit way + // NamedDomainObjectContainer binds the methods. + id("grpc") { } + id("reactor") {} + } + } + } + + generatedFilesBaseDir = "${project.buildDir}/protoGen" +} +sourceSets.configureEach { + val protoGenDir = project.buildDir.toPath() + .resolve("protoGen") + .resolve(this.name) + + java.srcDirs( + protoGenDir.resolve("java") + .toFile(), + protoGenDir.resolve("grpc") + .toFile(), + protoGenDir.resolve("reactor") + .toFile() + ) + resources.srcDirs( + layout.projectDirectory.dir("../certificate").asFile + ) +} + +tasks.register("bootRunDirectOk") { + doFirst { + tasks.bootRun.configure { + systemProperty("spring.profiles.active", "direct,okRequest") + } + } + finalizedBy("bootRun") +} + +tasks.register("bootRunDirectError") { + doFirst { + tasks.bootRun.configure { + systemProperty("spring.profiles.active", "direct,errorRequest") + } + } + finalizedBy("bootRun") +} + +tasks.register("bootRunGatewayOk") { + doFirst { + tasks.bootRun.configure { + systemProperty("spring.profiles.active", "gateway,okRequest") + } + } + finalizedBy("bootRun") +} + +tasks.register("bootRunGatewayError") { + doFirst { + tasks.bootRun.configure { + systemProperty("spring.profiles.active", "gateway,errorRequest") + } + } + finalizedBy("bootRun") +} \ No newline at end of file diff --git a/grpc-client/src/main/java/com/gateway/bugreport/buggrpcstatus/BugCloudGatewayGrpcClient.java b/grpc-client/src/main/java/com/gateway/bugreport/buggrpcstatus/BugCloudGatewayGrpcClient.java new file mode 100644 index 0000000..8ed36ea --- /dev/null +++ b/grpc-client/src/main/java/com/gateway/bugreport/buggrpcstatus/BugCloudGatewayGrpcClient.java @@ -0,0 +1,13 @@ +package com.gateway.bugreport.buggrpcstatus; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class BugCloudGatewayGrpcClient { + + public static void main(String[] args) { + SpringApplication.run(BugCloudGatewayGrpcClient.class); + } + +} diff --git a/grpc-client/src/main/java/com/gateway/bugreport/buggrpcstatus/client/BaseGrpcClientRunner.java b/grpc-client/src/main/java/com/gateway/bugreport/buggrpcstatus/client/BaseGrpcClientRunner.java new file mode 100644 index 0000000..c090cc2 --- /dev/null +++ b/grpc-client/src/main/java/com/gateway/bugreport/buggrpcstatus/client/BaseGrpcClientRunner.java @@ -0,0 +1,51 @@ +package com.gateway.bugreport.buggrpcstatus.client; + +import com.gateway.bugreport.ReactorSimpleGrpcServiceGrpc; +import com.gateway.bugreport.buggrpcstatus.BugCloudGatewayGrpcClient; +import io.grpc.ManagedChannelBuilder; +import io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.NettyChannelBuilder; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.CommandLineRunner; +import org.springframework.core.io.Resource; + +public abstract class BaseGrpcClientRunner implements CommandLineRunner { + + protected static final Logger LOG = LogManager.getLogger(BugCloudGatewayGrpcClient.class); + + private final GrpcClientProperties properties; + + private final Resource certChain; + + private final Resource privateKey; + + public BaseGrpcClientRunner(GrpcClientProperties properties, + @Value("${classpath:localhost.crt}") Resource certChain, + @Value("${classpath:localhost.key}") Resource privateKey) { + this.properties = properties; + this.certChain = certChain; + this.privateKey = privateKey; + } + + @Override + public void run(String... args) throws Exception { + LOG.info("Making request to host {} and port {}", properties.host(), properties.port()); + + final var channelBuilder = ManagedChannelBuilder.forAddress(properties.host(), properties.port()); + final var channel = ((NettyChannelBuilder) channelBuilder) + .useTransportSecurity() + .sslContext(GrpcSslContexts.forClient() + .trustManager(certChain.getFile()) + .keyManager(certChain.getFile(), privateKey.getFile()) + .build()) + .build(); + + final var client = ReactorSimpleGrpcServiceGrpc.newReactorStub(channel); + + runRequest(client); + } + + protected abstract void runRequest(ReactorSimpleGrpcServiceGrpc.ReactorSimpleGrpcServiceStub client); +} diff --git a/grpc-client/src/main/java/com/gateway/bugreport/buggrpcstatus/client/GrpcClientProperties.java b/grpc-client/src/main/java/com/gateway/bugreport/buggrpcstatus/client/GrpcClientProperties.java new file mode 100644 index 0000000..bbd801f --- /dev/null +++ b/grpc-client/src/main/java/com/gateway/bugreport/buggrpcstatus/client/GrpcClientProperties.java @@ -0,0 +1,7 @@ +package com.gateway.bugreport.buggrpcstatus.client; + +import org.springframework.boot.context.properties.ConfigurationProperties; + +@ConfigurationProperties(prefix = "grpc.client") +public record GrpcClientProperties(String host, int port) { +} diff --git a/grpc-client/src/main/java/com/gateway/bugreport/buggrpcstatus/client/GrpcErrorRequestClientRunner.java b/grpc-client/src/main/java/com/gateway/bugreport/buggrpcstatus/client/GrpcErrorRequestClientRunner.java new file mode 100644 index 0000000..53cfc49 --- /dev/null +++ b/grpc-client/src/main/java/com/gateway/bugreport/buggrpcstatus/client/GrpcErrorRequestClientRunner.java @@ -0,0 +1,33 @@ +package com.gateway.bugreport.buggrpcstatus.client; + +import com.gateway.bugreport.ReactorSimpleGrpcServiceGrpc; +import com.gateway.bugreport.SimpleRequestMessage; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Profile; +import org.springframework.core.io.Resource; +import org.springframework.stereotype.Component; + +import static java.util.UUID.randomUUID; + +@Component +@EnableConfigurationProperties(GrpcClientProperties.class) +@Profile("errorRequest") +public class GrpcErrorRequestClientRunner extends BaseGrpcClientRunner { + + public GrpcErrorRequestClientRunner(GrpcClientProperties properties, + @Value("${classpath:localhost.crt}") Resource certChain, + @Value("${classpath:localhost.key}") Resource privateKey) { + super(properties, certChain, privateKey); + } + + @Override + protected void runRequest(ReactorSimpleGrpcServiceGrpc.ReactorSimpleGrpcServiceStub client) { + final var response = client.errorProducingGrpcRequest(SimpleRequestMessage.newBuilder() + .setId(randomUUID().toString()) + .setMessage("Ping") + .build()).block(); + + LOG.info("Response: {}", response); + } +} diff --git a/grpc-client/src/main/java/com/gateway/bugreport/buggrpcstatus/client/GrpcOkRequestClientRunner.java b/grpc-client/src/main/java/com/gateway/bugreport/buggrpcstatus/client/GrpcOkRequestClientRunner.java new file mode 100644 index 0000000..c209f28 --- /dev/null +++ b/grpc-client/src/main/java/com/gateway/bugreport/buggrpcstatus/client/GrpcOkRequestClientRunner.java @@ -0,0 +1,33 @@ +package com.gateway.bugreport.buggrpcstatus.client; + +import com.gateway.bugreport.ReactorSimpleGrpcServiceGrpc; +import com.gateway.bugreport.SimpleRequestMessage; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Profile; +import org.springframework.core.io.Resource; +import org.springframework.stereotype.Component; + +import static java.util.UUID.randomUUID; + +@Component +@EnableConfigurationProperties(GrpcClientProperties.class) +@Profile("okRequest") +public class GrpcOkRequestClientRunner extends BaseGrpcClientRunner { + + public GrpcOkRequestClientRunner(GrpcClientProperties properties, + @Value("${classpath:localhost.crt}") Resource certChain, + @Value("${classpath:localhost.key}") Resource privateKey) { + super(properties, certChain, privateKey); + } + + @Override + protected void runRequest(ReactorSimpleGrpcServiceGrpc.ReactorSimpleGrpcServiceStub client) { + final var response = client.simpleGrpcRequest(SimpleRequestMessage.newBuilder() + .setId(randomUUID().toString()) + .setMessage("Ping") + .build()).block(); + + LOG.info("Response: {}", response); + } +} diff --git a/grpc-client/src/main/proto/SImpleGrpc.proto b/grpc-client/src/main/proto/SImpleGrpc.proto new file mode 100644 index 0000000..0a81ca2 --- /dev/null +++ b/grpc-client/src/main/proto/SImpleGrpc.proto @@ -0,0 +1,21 @@ +syntax = "proto3"; + +option java_multiple_files = true; +option java_package = "com.gateway.bugreport"; +option java_outer_classname = "SimpleGrpcServerProto"; + +message SimpleRequestMessage { + string id = 1; + string message = 2; +} + +message SimpleResponseMessage { + string id = 1; + string message = 2; +} + +service SimpleGrpcService { + rpc SimpleGrpcRequest(SimpleRequestMessage) returns (SimpleResponseMessage) {} + + rpc ErrorProducingGrpcRequest(SimpleRequestMessage) returns (SimpleResponseMessage) {} +} \ No newline at end of file diff --git a/grpc-client/src/main/resources/application-direct.yaml b/grpc-client/src/main/resources/application-direct.yaml new file mode 100644 index 0000000..41c0a05 --- /dev/null +++ b/grpc-client/src/main/resources/application-direct.yaml @@ -0,0 +1,4 @@ +grpc: + client: + host: localhost + port: 8082 diff --git a/grpc-client/src/main/resources/application-gateway.yaml b/grpc-client/src/main/resources/application-gateway.yaml new file mode 100644 index 0000000..0d311a0 --- /dev/null +++ b/grpc-client/src/main/resources/application-gateway.yaml @@ -0,0 +1,4 @@ +grpc: + client: + host: localhost + port: 8080 diff --git a/grpc-client/src/main/resources/application.yaml b/grpc-client/src/main/resources/application.yaml new file mode 100644 index 0000000..c594d75 --- /dev/null +++ b/grpc-client/src/main/resources/application.yaml @@ -0,0 +1,3 @@ +spring: + main: + web-application-type: none diff --git a/grpc-server/build.gradle.kts b/grpc-server/build.gradle.kts new file mode 100644 index 0000000..9fad08a --- /dev/null +++ b/grpc-server/build.gradle.kts @@ -0,0 +1,79 @@ +import com.google.protobuf.gradle.* + +plugins { + id("org.springframework.boot") + id("com.google.protobuf") version "0.8.19" + id("java") +} + +dependencies { + val versions = object { + // NOTE: keep this in sync with Spring boot version, see: https://github.com/LogNet/grpc-spring-boot-starter/blob/master/ReleaseNotes.md + val grpcStarter = "4.8.1" + val reactorGrpc = "1.2.3" + } + + implementation("org.springframework.boot:spring-boot-starter-webflux") + + implementation("io.github.lognet:grpc-spring-boot-starter:${versions.grpcStarter}") + implementation("com.salesforce.servicelibs:reactor-grpc:${versions.reactorGrpc}") + implementation("com.salesforce.servicelibs:reactor-grpc-stub:${versions.reactorGrpc}") + + testImplementation("org.junit.jupiter:junit-jupiter-api:5.8.1") + testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.8.1") +} + +tasks.withType { + useJUnitPlatform() +} + +protobuf { + val versions = object { + val protobuf = "3.19.2" + val grpc = "1.49.0" + val reactorGrpc = "1.2.3" + } + protoc { + artifact = "com.google.protobuf:protoc:${versions.protobuf}" + } + plugins { + id("grpc") { + artifact = "io.grpc:protoc-gen-grpc-java:${versions.grpc}" + } + id("reactor") { + artifact = "com.salesforce.servicelibs:reactor-grpc:${versions.reactorGrpc}" + } + } + generateProtoTasks { + ofSourceSet("main").forEach { + it.plugins { + // Apply the "grpc" plugin whose spec is defined above, without + // options. Note the braces cannot be omitted, otherwise the + // plugin will not be added. This is because of the implicit way + // NamedDomainObjectContainer binds the methods. + id("grpc") { } + id("reactor") {} + } + } + } + + generatedFilesBaseDir = "${project.buildDir}/protoGen" +} + +sourceSets.configureEach { + val protoGenDir = project.buildDir.toPath() + .resolve("protoGen") + .resolve(this.name) + + java.srcDirs( + protoGenDir.resolve("java") + .toFile(), + protoGenDir.resolve("grpc") + .toFile(), + protoGenDir.resolve("reactor") + .toFile() + ) + resources.srcDirs( + layout.projectDirectory.dir("../certificate").asFile + ) +} \ No newline at end of file diff --git a/grpc-server/src/main/java/com/gateway/bugreport/buggrpcstatus/BugCloudGatewayGrpcServer.java b/grpc-server/src/main/java/com/gateway/bugreport/buggrpcstatus/BugCloudGatewayGrpcServer.java new file mode 100644 index 0000000..32001da --- /dev/null +++ b/grpc-server/src/main/java/com/gateway/bugreport/buggrpcstatus/BugCloudGatewayGrpcServer.java @@ -0,0 +1,13 @@ +package com.gateway.bugreport.buggrpcstatus; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class BugCloudGatewayGrpcServer { + + public static void main(String[] args) { + SpringApplication.run(BugCloudGatewayGrpcServer.class, args); + } + +} diff --git a/grpc-server/src/main/java/com/gateway/bugreport/buggrpcstatus/grpc/SimpleGrpcService.java b/grpc-server/src/main/java/com/gateway/bugreport/buggrpcstatus/grpc/SimpleGrpcService.java new file mode 100644 index 0000000..cb0f579 --- /dev/null +++ b/grpc-server/src/main/java/com/gateway/bugreport/buggrpcstatus/grpc/SimpleGrpcService.java @@ -0,0 +1,29 @@ +package com.gateway.bugreport.buggrpcstatus.grpc; + + +import com.gateway.bugreport.ReactorSimpleGrpcServiceGrpc; +import com.gateway.bugreport.SimpleRequestMessage; +import com.gateway.bugreport.SimpleResponseMessage; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import org.lognet.springboot.grpc.GRpcService; +import reactor.core.publisher.Mono; + +import static java.util.UUID.randomUUID; + +@GRpcService +public class SimpleGrpcService extends ReactorSimpleGrpcServiceGrpc.SimpleGrpcServiceImplBase { + + @Override + public Mono simpleGrpcRequest(Mono request) { + return Mono.just(SimpleResponseMessage.newBuilder() + .setId(randomUUID().toString()) + .setMessage("Pong") + .build()); + } + + @Override + public Mono errorProducingGrpcRequest(Mono request) { + return Mono.error(new StatusRuntimeException(Status.INTERNAL)); + } +} diff --git a/grpc-server/src/main/proto/SImpleGrpc.proto b/grpc-server/src/main/proto/SImpleGrpc.proto new file mode 100644 index 0000000..0a81ca2 --- /dev/null +++ b/grpc-server/src/main/proto/SImpleGrpc.proto @@ -0,0 +1,21 @@ +syntax = "proto3"; + +option java_multiple_files = true; +option java_package = "com.gateway.bugreport"; +option java_outer_classname = "SimpleGrpcServerProto"; + +message SimpleRequestMessage { + string id = 1; + string message = 2; +} + +message SimpleResponseMessage { + string id = 1; + string message = 2; +} + +service SimpleGrpcService { + rpc SimpleGrpcRequest(SimpleRequestMessage) returns (SimpleResponseMessage) {} + + rpc ErrorProducingGrpcRequest(SimpleRequestMessage) returns (SimpleResponseMessage) {} +} \ No newline at end of file diff --git a/grpc-server/src/main/resources/application.yaml b/grpc-server/src/main/resources/application.yaml new file mode 100644 index 0000000..27d0d28 --- /dev/null +++ b/grpc-server/src/main/resources/application.yaml @@ -0,0 +1,12 @@ +spring: + main: + web-application-type: none + +grpc: + enabled: true + port: 8082 + security: + auth: + enabled: false + cert-chain: classpath:localhost.crt + private-key: classpath:localhost.key \ No newline at end of file diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..8b7f212 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,4 @@ +rootProject.name = "bug-cloud-gateway-grpc-status" + +include("grpc-server") +include("grpc-client") diff --git a/src/main/java/com/gateway/bugreport/buggrpcstatus/BugCloudGatewayGRpcStatus.java b/src/main/java/com/gateway/bugreport/buggrpcstatus/BugCloudGatewayGRpcStatus.java new file mode 100644 index 0000000..67102e1 --- /dev/null +++ b/src/main/java/com/gateway/bugreport/buggrpcstatus/BugCloudGatewayGRpcStatus.java @@ -0,0 +1,23 @@ +package com.gateway.bugreport.buggrpcstatus; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.gateway.filter.headers.GRPCResponseHeadersFilter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Primary; +import org.springframework.context.annotation.Profile; + +@SpringBootApplication +public class BugCloudGatewayGRpcStatus { + + public static void main(String[] args) { + SpringApplication.run(BugCloudGatewayGRpcStatus.class, args); + } + + @Bean + @Primary + @Profile("patchedFilter") + public GRPCResponseHeadersFilter patchedResponseFilter() { + return new PatchedGRPCResponseHeaderFilter(); + } +} diff --git a/src/main/java/com/gateway/bugreport/buggrpcstatus/PatchedGRPCResponseHeaderFilter.java b/src/main/java/com/gateway/bugreport/buggrpcstatus/PatchedGRPCResponseHeaderFilter.java new file mode 100644 index 0000000..fe07d7b --- /dev/null +++ b/src/main/java/com/gateway/bugreport/buggrpcstatus/PatchedGRPCResponseHeaderFilter.java @@ -0,0 +1,66 @@ +package com.gateway.bugreport.buggrpcstatus; + + +import org.springframework.cloud.gateway.filter.headers.GRPCResponseHeadersFilter; +import org.springframework.http.HttpHeaders; +import org.springframework.http.server.reactive.AbstractServerHttpResponse; +import org.springframework.http.server.reactive.ServerHttpResponse; +import org.springframework.util.StringUtils; +import org.springframework.web.server.ServerWebExchange; +import reactor.netty.http.server.HttpServerResponse; + +public class PatchedGRPCResponseHeaderFilter extends GRPCResponseHeadersFilter { + + private static final String GRPC_STATUS_HEADER = "grpc-status"; + + @Override + public HttpHeaders filter(HttpHeaders headers, ServerWebExchange exchange) { + if (isGRPC(exchange)) { + ServerHttpResponse response = exchange.getResponse(); + HttpHeaders responseHeaders = response.getHeaders(); + + String trailerHeaderValue = getTrailerHeaderValue(responseHeaders); + responseHeaders.set(HttpHeaders.TRAILER, trailerHeaderValue); + + String grpcStatus = getGrpcStatus(headers); + + // DEVELOPERS NOTE: + // "grpc-status" needs to be set in trailers: https://github.com/spring-cloud/spring-cloud-gateway/issues/2679 + ((HttpServerResponse) ((AbstractServerHttpResponse) response).getNativeResponse()) + .trailerHeaders(h -> h.set(GRPC_STATUS_HEADER, grpcStatus)); + } + + return headers; + } + + private static String getTrailerHeaderValue(HttpHeaders responseHeaders) { + String trailerHeaderValue = GRPC_STATUS_HEADER; + String originalTrailerHeaderValue = responseHeaders.getFirst(HttpHeaders.TRAILER); + + if (originalTrailerHeaderValue != null) { + trailerHeaderValue += "," + originalTrailerHeaderValue; + } + + return trailerHeaderValue; + } + + private String getGrpcStatus(HttpHeaders headers) { + final var grpcStatusValue = headers.getFirst(GRPC_STATUS_HEADER); + + return StringUtils.hasText(grpcStatusValue) ? grpcStatusValue : "0"; + } + + @SuppressWarnings("checkstyle:AbbreviationAsWordInName") + private boolean isGRPC(ServerWebExchange exchange) { + String contentTypeValue = exchange.getRequest() + .getHeaders() + .getFirst(HttpHeaders.CONTENT_TYPE); + + return StringUtils.startsWithIgnoreCase(contentTypeValue, "application/grpc"); + } + + @Override + public int getOrder() { + return 1; + } +} diff --git a/src/main/resources/application-patchedFilter.yml b/src/main/resources/application-patchedFilter.yml new file mode 100644 index 0000000..24b56f6 --- /dev/null +++ b/src/main/resources/application-patchedFilter.yml @@ -0,0 +1,3 @@ +server: + http2: + enabled: true \ No newline at end of file diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml new file mode 100644 index 0000000..58e7231 --- /dev/null +++ b/src/main/resources/application.yaml @@ -0,0 +1,25 @@ +server: + http2: + enabled: true + ssl: + key-store-type: PKCS12 + key-store: classpath:localhostP12Keystore.p12 + key-store-password: buggateway + certificate-private-key: classpath:localhost.key + enabled: true + +spring: + cloud: + gateway: + httpclient: + ssl: + use-insecure-trust-manager: true + routes: + - id: grpc-route + uri: https://localhost:8082 + predicates: + - Header=Content-Type, application/grpc + +logging: + level: + root: info \ No newline at end of file diff --git a/src/test/java/com/gateway/bugreport/buggrpcstatus/BugCloudGatewayGRpcStatusTests.java b/src/test/java/com/gateway/bugreport/buggrpcstatus/BugCloudGatewayGRpcStatusTests.java new file mode 100644 index 0000000..ab54da1 --- /dev/null +++ b/src/test/java/com/gateway/bugreport/buggrpcstatus/BugCloudGatewayGRpcStatusTests.java @@ -0,0 +1,13 @@ +package com.gateway.bugreport.buggrpcstatus; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class BugCloudGatewayGRpcStatusTests { + + @Test + void contextLoads() { + } + +}