From c96771095eea35bf76e72ee016e89221e66302ee Mon Sep 17 00:00:00 2001 From: "Alex S. Glomsaas" Date: Mon, 29 Aug 2022 19:46:55 +0200 Subject: [PATCH 1/5] Add missing license file fixes #8 --- LICENSE.md | 201 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 201 insertions(+) create mode 100644 LICENSE.md diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..c319da3 --- /dev/null +++ b/LICENSE.md @@ -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. From 3243a5bd1f88d6238fbe78ec4b6ea4518c47177b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alex=20S=C3=B8rlie=20Glomsaas?= Date: Wed, 14 Sep 2022 01:28:07 +0200 Subject: [PATCH 2/5] Implement CloseError --- templates/client.templ | 12 ++++++++++++ templates/server.templ | 3 +++ 2 files changed, 15 insertions(+) diff --git a/templates/client.templ b/templates/client.templ index 8d22c62..17708df 100644 --- a/templates/client.templ +++ b/templates/client.templ @@ -60,6 +60,18 @@ func NewClient (tlsConfig *tls.Config, logger *zerolog.Logger) (*Client, error) } {{template "clientmethods" .services }} + +type CloseError struct { + err error +} + +func NewCloseError(err error) CloseError { + return CloseError{err: err} +} + +func (e CloseError) Error() string { + return e.err.Error() +} {{ end -}} {{define "clienthandlers"}} diff --git a/templates/server.templ b/templates/server.templ index 03a281d..7f8f803 100644 --- a/templates/server.templ +++ b/templates/server.templ @@ -48,6 +48,9 @@ func NewServer({{ GetServerFields .services }}, tlsConfig *tls.Config, logger *z outgoing.Content.Reset() res, err = {{ FirstLowerCase (CamelCaseName $service.Name) }}.{{ CamelCaseName $method.Name }}(ctx, req) if err != nil { + if _, ok := err.(CloseError); ok { + action = frisbee.CLOSE + } res.Error(outgoing.Content, err) } else { res.Encode(outgoing.Content) From 483c5c5b46101ec2fe66d74e6644eb26942fcb53 Mon Sep 17 00:00:00 2001 From: "Alex S. Glomsaas" Date: Wed, 21 Sep 2022 22:18:21 +0200 Subject: [PATCH 3/5] feat fRPC Streaming (#15) * Implement fRPC Streaming * Minor fix to the server template for setOnClosed Co-authored-by: Shivansh Vij --- .github/workflows/lint.yaml | 17 ++ .github/workflows/tests.yaml | 27 +++ examples/test/test.proto | 3 + go.mod | 17 ++ go.sum | 43 ++++ pkg/generator/generator.go | 47 ++-- pkg/generator/imports.go | 12 +- pkg/generator/test/generator_test.go | 156 ++++++++++++++ pkg/generator/test/server.go | 98 +++++++++ templates/base.templ | 1 + templates/client.templ | 205 +++++++++++++++++- templates/constants.templ | 16 ++ templates/customDecode.templ | 2 +- templates/customEncode.templ | 2 +- templates/customFields.templ | 2 +- templates/imports.templ | 5 + templates/interfaces.templ | 6 + templates/server.templ | 309 +++++++++++++++++++++++++-- 18 files changed, 919 insertions(+), 49 deletions(-) create mode 100644 pkg/generator/test/generator_test.go create mode 100644 pkg/generator/test/server.go create mode 100644 templates/constants.templ diff --git a/.github/workflows/lint.yaml b/.github/workflows/lint.yaml index 1a33ea6..cc5c17a 100644 --- a/.github/workflows/lint.yaml +++ b/.github/workflows/lint.yaml @@ -12,11 +12,28 @@ jobs: - name: Checkout uses: actions/checkout@v2 + - name: Set up Go + uses: actions/setup-go@v2 + with: + go-version: 1.18 + - name: Cache Linters/Formatters uses: actions/cache@v2 with: path: ~/.cache/trunk key: trunk-${{ runner.os }} + - name: Install Protoc + uses: arduino/setup-protoc@v1 + - name: Install protoc-gen plugin + working-directory: ./protoc-gen-go-frpc + run: go install google.golang.org/protobuf/cmd/protoc-gen-go@latest + - name: Install frpc plugin for protoc-gen + working-directory: ./ + run: go install ./protoc-gen-go-frpc + - name: Run generator + working-directory: ./examples/test + run: protoc --go-frpc_out=../../pkg/generator test.proto + - name: Trunk Check uses: trunk-io/trunk-action@v1 diff --git a/.github/workflows/tests.yaml b/.github/workflows/tests.yaml index 11885a3..6dad734 100644 --- a/.github/workflows/tests.yaml +++ b/.github/workflows/tests.yaml @@ -4,6 +4,9 @@ on: push: branches: - "*" + pull_request: + branches: + - "*" jobs: tests: @@ -34,6 +37,18 @@ jobs: path: ${{ steps.go-cache-paths.outputs.go-mod }} key: ${{ runner.os }}-go-mod-${{ hashFiles('**/go.sum') }} + - uses: actions/checkout@v3 + - name: Install Protoc + uses: arduino/setup-protoc@v1 + - name: Install protoc-gen plugin + working-directory: ./protoc-gen-go-frpc + run: go install google.golang.org/protobuf/cmd/protoc-gen-go@latest + - name: Install frpc plugin for protoc-gen + working-directory: ./ + run: go install ./protoc-gen-go-frpc + - name: Run generator + working-directory: ./examples/test + run: protoc --go-frpc_out=../../pkg/generator test.proto - name: Test run: go test -v ./... tests-race: @@ -64,6 +79,18 @@ jobs: path: ${{ steps.go-cache-paths.outputs.go-mod }} key: ${{ runner.os }}-go-mod-${{ hashFiles('**/go.sum') }} + - name: Install Protoc + uses: arduino/setup-protoc@v1 + - name: Install protoc-gen plugin + working-directory: ./protoc-gen-go-frpc + run: go install google.golang.org/protobuf/cmd/protoc-gen-go@latest + - name: Install frpc plugin for protoc-gen + working-directory: ./ + run: go install ./protoc-gen-go-frpc + - name: Run generator + working-directory: ./examples/test + run: protoc --go-frpc_out=../../pkg/generator test.proto + - name: Test with Race Conditions run: go test -race -v ./... timeout-minutes: 15 diff --git a/examples/test/test.proto b/examples/test/test.proto index 2918d00..e3a165d 100644 --- a/examples/test/test.proto +++ b/examples/test/test.proto @@ -4,7 +4,10 @@ option go_package = "/test"; service EchoService { rpc Echo(Request) returns (Response); + rpc EchoStream(stream Request) returns (stream Response); rpc Testy(SearchResponse) returns (StockPricesWrapper); + rpc Search(SearchResponse) returns (stream Response); + rpc Upload(stream Data) returns (Response); } message Request { diff --git a/go.mod b/go.mod index b932d63..9b3d146 100644 --- a/go.mod +++ b/go.mod @@ -4,5 +4,22 @@ go 1.18 require ( github.com/loopholelabs/polyglot-go v0.4.0 + github.com/loopholelabs/testing v0.2.3 + github.com/rs/zerolog v1.28.0 + github.com/stretchr/testify v1.8.0 google.golang.org/protobuf v1.28.0 ) + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/kr/text v0.2.0 // indirect + github.com/loopholelabs/common v0.4.4 // indirect + github.com/mattn/go-colorable v0.1.12 // indirect + github.com/mattn/go-isatty v0.0.14 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + go.uber.org/atomic v1.9.0 // indirect + golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + github.com/loopholelabs/frisbee-go v0.6.0 // indirect +) diff --git a/go.sum b/go.sum index ade1024..f74db80 100644 --- a/go.sum +++ b/go.sum @@ -1,10 +1,53 @@ +github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/loopholelabs/common v0.4.4 h1:Ge+1v1WiLYgR/4pziOQoJAwUqUm1c9j6nQvnkiFFBsk= +github.com/loopholelabs/common v0.4.4/go.mod h1:YKnljczr4jgxkHhhAwIHh3CJXaff89YBd8Vp3pwpG3k= +github.com/loopholelabs/frisbee-go v0.6.0 h1:4HM/o0Q5aPbGaEOvHf7PbYI/4vYT6K+hlW+R0Ic+SfE= +github.com/loopholelabs/frisbee-go v0.6.0/go.mod h1:DAb8ALrCXrdhDFv6mRJhmWljvOVQb8cZ9y24NiMNFC0= github.com/loopholelabs/polyglot-go v0.4.0 h1:HavI5O6lMKF7urRgnVk+8vM4WqCpJGkH81dxLnhFGAA= github.com/loopholelabs/polyglot-go v0.4.0/go.mod h1:Z0QiNv4KRuWjQWpUerMhmkvRh6ks1pYmEH4SGpG0EHQ= +github.com/loopholelabs/testing v0.2.3 h1:4nVuK5ctaE6ua5Z0dYk2l7xTFmcpCYLUeGjRBp8keOA= +github.com/loopholelabs/testing v0.2.3/go.mod h1:gqtGY91soYD1fQoKQt/6kP14OYpS7gcbcIgq5mc9m8Q= +github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40= +github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= +github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= +github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= +github.com/rs/zerolog v1.28.0 h1:MirSo27VyNi7RJYP3078AA1+Cyzd2GB66qy3aUHvsWY= +github.com/rs/zerolog v1.28.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= +go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/goleak v1.1.12 h1:gZAh5/EyT/HQwlpkCy6wTpqfH9H8Lz8zbm3dZh+OyzA= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6 h1:foEbQz/B0Oz6YIqu/69kfXPYeFQAuuMYFkjaqXzl5Wo= +golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw= google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/pkg/generator/generator.go b/pkg/generator/generator.go index 1672780..feef840 100644 --- a/pkg/generator/generator.go +++ b/pkg/generator/generator.go @@ -18,15 +18,15 @@ package generator import ( "bytes" - "text/template" - "github.com/loopholelabs/frpc-go/internal/version" "github.com/loopholelabs/frpc-go/templates" "github.com/loopholelabs/polyglot-go/pkg/generator" "github.com/loopholelabs/polyglot-go/pkg/utils" "google.golang.org/protobuf/compiler/protogen" "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/types/pluginpb" + "text/template" ) type Generator struct { @@ -34,6 +34,7 @@ type Generator struct { } var templ *template.Template +var streamMethods = make(map[protoreflect.FullName]bool) func init() { templ = template.Must(template.New("main").Funcs(template.FuncMap{ @@ -44,6 +45,9 @@ func init() { "FirstLowerCase": utils.FirstLowerCase, "FirstLowerCaseName": utils.FirstLowerCaseName, "GetServerFields": getServerFields, + "UsedForStreaming": func(typeName protoreflect.FullName) bool { + return streamMethods[typeName] + }, }).ParseFS(templates.FS, "*")) } @@ -114,20 +118,32 @@ func (g *Generator) Generate(req *pluginpb.CodeGeneratorRequest) (res *pluginpb. numServices := f.Desc.Services().Len() numMethods := 0 + streamMethods = make(map[protoreflect.FullName]bool) for i := 0; i < numServices; i++ { nM := f.Desc.Services().Get(i).Methods().Len() numMethods += nM + for m := 0; m < nM; m++ { + method := f.Desc.Services().Get(i).Methods().Get(m) + if method.IsStreamingClient() { + streamMethods[method.Input().FullName()] = true + } + if method.IsStreamingServer() { + streamMethods[method.Output().FullName()] = true + } + } } err = templ.ExecuteTemplate(genFile, "prebase.templ", map[string]interface{}{ - "pluginVersion": version.Version, - "sourcePath": f.Desc.Path(), - "package": packageName, - "requiredImports": requiredImports, - "serviceImports": serviceImports, - "methodImports": methodImports, - "numServices": numServices, - "numMethods": numMethods, + "pluginVersion": version.Version, + "sourcePath": f.Desc.Path(), + "package": packageName, + "requiredImports": requiredImports, + "serviceImports": serviceImports, + "methodImports": methodImports, + "streamMethodImports": streamMethodImports, + "numServices": numServices, + "numMethods": numMethods, + "numStreamMethods": len(streamMethods), }) if err != nil { return nil, err @@ -139,11 +155,12 @@ func (g *Generator) Generate(req *pluginpb.CodeGeneratorRequest) (res *pluginpb. } err = templ.ExecuteTemplate(genFile, "base.templ", map[string]interface{}{ - "enums": f.Desc.Enums(), - "messages": f.Desc.Messages(), - "services": f.Desc.Services(), - "numServices": numServices, - "numMethods": numMethods, + "enums": f.Desc.Enums(), + "messages": f.Desc.Messages(), + "services": f.Desc.Services(), + "numServices": numServices, + "numMethods": numMethods, + "numStreamMethods": len(streamMethods), }) if err != nil { return nil, err diff --git a/pkg/generator/imports.go b/pkg/generator/imports.go index ef8daff..561d7b0 100644 --- a/pkg/generator/imports.go +++ b/pkg/generator/imports.go @@ -18,16 +18,22 @@ package generator var ( requiredImports = []string{ - "github.com/loopholelabs/polyglot-go", "errors", + "github.com/loopholelabs/polyglot-go", } serviceImports = []string{ + "context", + "crypto/tls", "github.com/loopholelabs/frisbee-go", "github.com/loopholelabs/frisbee-go/pkg/packet", "github.com/rs/zerolog", - "crypto/tls", - "context", + } + + streamMethodImports = []string{ + "github.com/loopholelabs/common/pkg/queue", + "go.uber.org/atomic", + "io", } methodImports = []string{ diff --git a/pkg/generator/test/generator_test.go b/pkg/generator/test/generator_test.go new file mode 100644 index 0000000..90aa85d --- /dev/null +++ b/pkg/generator/test/generator_test.go @@ -0,0 +1,156 @@ +/* + Copyright 2022 Loophole Labs + + 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 test + +import ( + "context" + "github.com/loopholelabs/testing/conn/pair" + "github.com/stretchr/testify/assert" + "io" + "testing" +) + +func TestRPC(t *testing.T) { + cConn, sConn, err := pair.New() + assert.NoError(t, err, "Client server pair creation failed") + + client, err := NewClient(nil, nil) + assert.NoError(t, err, "Client creation failed") + + err = client.FromConn(cConn) + assert.NoError(t, err, "Client connection assignment failed") + + serverMethods := new(svc) + serverMethods.t = t + server, err := NewServer(serverMethods, nil, nil) + assert.NoError(t, err, "Server creation failed") + + go server.ServeConn(sConn) + + t.Run("Synchronous Request", func(t *testing.T) { + t.Parallel() + go func() { + testSynchronous(client, t) + }() + }) + + t.Run("Bi-directional Stream", func(t *testing.T) { + t.Parallel() + go func() { + testBidirectional(client, t) + }() + }) + + t.Run("Server Stream", func(t *testing.T) { + t.Parallel() + go func() { + testServerStreaming(client, t) + }() + }) + + t.Run("Client Stream", func(t *testing.T) { + t.Parallel() + go func() { + testClientStreaming(client, t) + }() + }) +} + +func testSynchronous(client *Client, t *testing.T) { + ctx := context.Background() + req := &Request{ + Message: "Hello World", + Corpus: RequestUNIVERSAL, + } + response, err := client.EchoService.Echo(ctx, req) + assert.NoError(t, err, "Request error") + assert.Equal(t, "Hello World", response.Message) + assert.Equal(t, "Hello World", response.Test.Message) + assert.Equal(t, Potato, response.Test.Checker) +} + +func testBidirectional(client *Client, t *testing.T) { + ctx := context.Background() + req := &Request{ + Message: "Hello World", + Corpus: RequestUNIVERSAL, + } + + stream, err := client.EchoService.EchoStream(ctx, req) + assert.NoError(t, err) + + roundtrips := 0 + for { + res, err := stream.Recv() + roundtrips += 1 + assert.NoError(t, err, "Request error") + assert.Equal(t, "Hello World", res.Message) + assert.Equal(t, "Hello World", res.Test.Message) + assert.Equal(t, Potato, res.Test.Checker) + if roundtrips == 100 { + err = stream.CloseSend() + assert.NoError(t, err) + break + } + + err = stream.Send(req) + assert.NoError(t, err) + } + assert.Equal(t, 100, roundtrips) +} + +func testServerStreaming(client *Client, t *testing.T) { + ctx := context.Background() + search := NewSearchResponse() + search.Results = []*SearchResponseResult{ + &SearchResponseResult{ + Url: "https://google.com", + Title: "Google", + Snippets: []string{}, + }, + } + stream, err := client.EchoService.Search(ctx, search) + assert.NoError(t, err) + + received := 0 + for { + res, err := stream.Recv() + if err == io.EOF { + assert.Equal(t, 10, received) + break + } + received += 1 + assert.NoError(t, err) + assert.Equal(t, "Hello World", res.Message) + assert.Equal(t, "Hello World", res.Test.Message) + assert.Equal(t, Potato, res.Test.Checker) + } +} + +func testClientStreaming(client *Client, t *testing.T) { + ctx := context.Background() + data := &Data{Message: "Hello World", Checker: Potato} + stream, err := client.EchoService.Upload(ctx, data) + assert.NoError(t, err) + + for i := 0; i < 10; i++ { + err := stream.Send(data) + assert.NoError(t, err) + } + err = stream.CloseSend() + assert.NoError(t, err) +} diff --git a/pkg/generator/test/server.go b/pkg/generator/test/server.go new file mode 100644 index 0000000..32bb60b --- /dev/null +++ b/pkg/generator/test/server.go @@ -0,0 +1,98 @@ +/* + Copyright 2022 Loophole Labs + + 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 test + +import ( + "context" + "github.com/stretchr/testify/assert" + "io" + "testing" +) + +type svc struct { + t *testing.T +} + +func (s svc) Echo(ctx context.Context, request *Request) (*Response, error) { + assert.Equal(s.t, "Hello World", request.Message) + assert.Equal(s.t, RequestUNIVERSAL, request.Corpus) + return &Response{Message: "Hello World", Test: &Data{ + Message: "Hello World", + Checker: Potato, + }}, nil +} + +func (s svc) EchoStream(srv *EchoStreamServer) error { + ctx := srv.Context() + for { + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + + request, err := srv.Recv() + if err == io.EOF { + err = srv.CloseSend() + assert.NoError(s.t, err) + break + } + + assert.NoError(s.t, err) + + assert.Equal(s.t, "Hello World", request.Message) + assert.Equal(s.t, RequestUNIVERSAL, request.Corpus) + + response := &Response{Message: "Hello World", Test: &Data{ + Message: "Hello World", + Checker: Potato, + }} + + err = srv.Send(response) + assert.NoError(s.t, err) + } + return nil +} + +func (s svc) Testy(ctx context.Context, response *SearchResponse) (*StockPricesWrapper, error) { + panic("not implemented") +} + +func (s svc) Search(req *SearchResponse, srv *SearchServer) error { + assert.Equal(s.t, 1, len(req.Results)) + for i := 0; i < 10; i++ { + err := srv.Send(&Response{Message: "Hello World", Test: &Data{ + Message: "Hello World", + Checker: Potato, + }}) + assert.NoError(s.t, err) + } + return srv.CloseSend() +} + +func (s svc) Upload(srv *UploadServer) error { + received := 0 + for { + res, err := srv.Recv() + if err == io.EOF { + assert.Equal(s.t, 10, received) + return srv.CloseSend() + } + assert.NoError(s.t, err) + assert.Equal(s.t, "Hello World", res.Message) + } +} diff --git a/templates/base.templ b/templates/base.templ index 1c841f6..f1f84a3 100644 --- a/templates/base.templ +++ b/templates/base.templ @@ -1,4 +1,5 @@ {{template "interfaces" .}} +{{template "constants" .}} {{ if .numServices }} {{template "server" .}} diff --git a/templates/client.templ b/templates/client.templ index 17708df..b3fcdbe 100644 --- a/templates/client.templ +++ b/templates/client.templ @@ -7,7 +7,11 @@ {{ $method := $service.Methods.Get $i -}} next{{ CamelCaseName $method.Name }} uint16 next{{ CamelCaseName $method.Name }}Mu sync.RWMutex + {{ if $method.IsStreamingServer -}} + inflight{{ CamelCaseName $method.Name }} map[uint16]*{{ CamelCaseName $method.Name }}Client + {{ else -}} inflight{{ CamelCaseName $method.Name }} map[uint16]chan *{{ CamelCase $method.Output.FullName }} + {{ end -}} inflight{{ CamelCaseName $method.Name }}Mu sync.RWMutex {{end -}} } @@ -44,16 +48,16 @@ func NewClient (tlsConfig *tls.Config, logger *zerolog.Logger) (*Client, error) {{ $service := $.services.Get $i -}} c.{{ CamelCaseName $service.Name }} = new(sub{{ CamelCaseName $service.Name }}Client) c.{{ CamelCaseName $service.Name }}.client = c.Client - {{ range $i, $v := (MakeIterable $service.Methods.Len) -}} - {{ $method := $service.Methods.Get $i -}} - c.{{ CamelCaseName $service.Name }}.inflight{{ CamelCaseName $method.Name }} = make(map[uint16]chan *{{ CamelCase $method.Output.FullName }}) - {{end -}} {{ range $i, $v := (MakeIterable $service.Methods.Len) -}} {{ $method := $service.Methods.Get $i -}} c.{{ CamelCaseName $service.Name }}.next{{ CamelCaseName $method.Name }}Mu.Lock() c.{{ CamelCaseName $service.Name }}.next{{ CamelCaseName $method.Name }} = 0 c.{{ CamelCaseName $service.Name }}.next{{ CamelCaseName $method.Name }}Mu.Unlock() + {{ if $method.IsStreamingServer -}} + c.{{ CamelCaseName $service.Name }}.inflight{{ CamelCaseName $method.Name }} = make(map[uint16]*{{ CamelCaseName $method.Name }}Client) + {{ else -}} c.{{ CamelCaseName $service.Name }}.inflight{{ CamelCaseName $method.Name }} = make(map[uint16]chan *{{ CamelCase $method.Output.FullName }}) + {{ end -}} {{end -}} {{end -}} return c, nil @@ -82,6 +86,25 @@ func (e CloseError) Error() string { {{ $method := $service.Methods.Get $i -}} {{ $count := call $counter -}} table[{{ $count }}] = func(ctx context.Context, incoming *packet.Packet) (outgoing *packet.Packet, action frisbee.Action) { + {{ if $method.IsStreamingServer -}} + res := New{{ CamelCase $method.Output.FullName }}() + err := res.Decode(*incoming.Content) + if err == nil { + c.{{ CamelCaseName $service.Name }}.inflight{{ CamelCaseName $method.Name }}Mu.RLock() + if stream, ok := c.{{ CamelCaseName $service.Name }}.inflight{{ CamelCaseName $method.Name }}[incoming.Metadata.Id]; ok { + c.{{ CamelCaseName $service.Name }}.inflight{{ CamelCaseName $method.Name }}Mu.RUnlock() + err := stream.received.Push(res) + if HasCloseFlag(res.flags) { + stream.close() + } + if err != nil { + return nil, 0 + } + } else { + c.{{ CamelCaseName $service.Name }}.inflight{{ CamelCaseName $method.Name }}Mu.RUnlock() + } + } + {{ else -}} c.{{ CamelCaseName $service.Name }}.inflight{{ CamelCaseName $method.Name }}Mu.RLock() if ch, ok := c.{{ CamelCaseName $service.Name }}.inflight{{ CamelCaseName $method.Name }}[incoming.Metadata.Id]; ok { c.{{ CamelCaseName $service.Name }}.inflight{{ CamelCaseName $method.Name }}Mu.RUnlock() @@ -91,6 +114,7 @@ func (e CloseError) Error() string { } else { c.{{ CamelCaseName $service.Name }}.inflight{{ CamelCaseName $method.Name }}Mu.RUnlock() } + {{ end -}} return } {{end -}} @@ -104,6 +128,174 @@ func (e CloseError) Error() string { {{ range $i, $v := (MakeIterable $service.Methods.Len) }} {{ $method := $service.Methods.Get $i -}} {{ $opIndex := call $counter -}} + {{if or $method.IsStreamingClient $method.IsStreamingServer -}} + func (c *sub{{ CamelCaseName $service.Name }}Client) {{ CamelCaseName $method.Name }}(ctx context.Context, req *{{ CamelCase $method.Input.FullName }}) (*{{ CamelCaseName $method.Name }}Client, error) { + p := packet.Get() + p.Metadata.Operation = {{ $opIndex }} + + c.next{{ CamelCaseName $method.Name }}Mu.Lock() + c.next{{ CamelCaseName $method.Name }} += 1 + id := c.next{{ CamelCaseName $method.Name }} + c.next{{ CamelCaseName $method.Name }}Mu.Unlock() + p.Metadata.Id = id + + req.Encode(p.Content) + p.Metadata.ContentLength = uint32(len(*p.Content)) + err := c.client.WritePacket(p) + + {{ if $method.IsStreamingServer -}} + q := queue.NewCircular[{{ CamelCase $method.Output.FullName }}, *{{ CamelCase $method.Output.FullName }}](100) + stale := make([]*{{ CamelCase $method.Output.FullName }}, 0) + staleMu := sync.Mutex{} + {{ end -}} + + if err != nil { + packet.Put(p) + return nil, err + } + packet.Put(p) + + stream := {{ CamelCaseName $method.Name }}Client{ + context: ctx, + closed: atomic.NewBool(false), + {{ if $method.IsStreamingServer -}} + received: q, + {{ end -}} + } + {{ if $method.IsStreamingServer -}} + c.inflight{{ CamelCaseName $method.Name }}Mu.Lock() + c.inflight{{ CamelCaseName $method.Name }}[id] = &stream + c.inflight{{ CamelCaseName $method.Name }}Mu.Unlock() + + stream.recv = func() (*{{ CamelCase $method.Output.FullName }}, error) { + if stream.closed.Load() { + staleMu.Lock() + if len(stale) > 0 { + var r *{{ $method.Output.FullName }} + r, stale = stale[0], stale[1:] + staleMu.Unlock() + return r, nil + } + staleMu.Unlock() + return nil, io.EOF + } else if c.client.Closed() { + stream.close() + } + + readPacket, err := q.Pop() + if err != nil { + if stream.closed.Load() { + staleMu.Lock() + if len(stale) > 0 { + var r *{{ $method.Output.FullName }} + r, stale = stale[0], stale[1:] + staleMu.Unlock() + if errors.Is(r.error, io.EOF) { + return nil, io.EOF + } + return r, nil + } + staleMu.Unlock() + } + return nil, io.EOF + } + if errors.Is(readPacket.error, io.EOF) { + return nil, io.EOF + } + return readPacket, nil + } + stream.close = func () { + if stream.closed.Load() { + return + } + staleMu.Lock() + stream.closed.Store(true) + stale = q.Drain() + staleMu.Unlock() + q.Close() + } + {{ else if $method.IsStreamingClient }} + ch := make(chan *{{ CamelCase $method.Output.FullName }}, 1) + c.inflight{{ CamelCaseName $method.Name }}Mu.Lock() + c.inflight{{ CamelCaseName $method.Name }}[id] = ch + c.inflight{{ CamelCaseName $method.Name }}Mu.Unlock() + + stream.recv = func () (res *{{ CamelCase $method.Output.FullName }}, err error) { + select { + case res = <- ch: + err = res.error + case <- ctx.Done(): + err = ctx.Err() + } + c.inflight{{ CamelCaseName $method.Name }}Mu.Lock() + delete(c.inflight{{ CamelCaseName $method.Name }}, id) + c.inflight{{ CamelCaseName $method.Name }}Mu.Unlock() + return + } + {{ end -}} + + {{ if $method.IsStreamingClient -}} + stream.send = func (m *{{ CamelCase $method.Input.FullName }}) error { + p := packet.Get() + p.Metadata.Operation = {{ $opIndex }} + + p.Metadata.Id = id + + m.Encode(p.Content) + p.Metadata.ContentLength = uint32(len(*p.Content)) + err := c.client.WritePacket(p) + if err != nil { + packet.Put(p) + return err + } + packet.Put(p) + return nil + } + {{ end -}} + go func () { + <-ctx.Done() + c.inflight{{ CamelCaseName $method.Name }}Mu.Lock() + delete(c.inflight{{ CamelCaseName $method.Name }}, id) + c.inflight{{ CamelCaseName $method.Name }}Mu.Unlock() + }() + return &stream, nil + } + + type {{ CamelCaseName $method.Name }}Client struct { + context context.Context + recv func() (*{{ CamelCase $method.Output.FullName }}, error) + close func() + closed *atomic.Bool + + {{ if $method.IsStreamingClient -}} + send func (*{{ CamelCase $method.Input.FullName }}) error + {{ end -}} + received *queue.Circular[{{ CamelCase $method.Output.FullName }}, *{{ CamelCase $method.Output.FullName }}] + } + + {{ if $method.IsStreamingServer -}} + func (x *{{ CamelCaseName $method.Name }}Client) Recv() (*{{ CamelCase $method.Output.FullName }}, error) { + return x.recv() + } + {{ end -}} + + {{ if $method.IsStreamingClient -}} + func (x *{{ CamelCaseName $method.Name }}Client) Send(m *{{ CamelCase $method.Input.FullName }}) error { + return x.send(m) + } + + func (x *{{ CamelCaseName $method.Name }}Client) CloseSend() error { + r := {{ CamelCase $method.Input.FullName }}{error: io.EOF, flags: SetCloseFlag(0, true) } + return x.Send(&r) + } + + func (x *{{ CamelCaseName $method.Name }}Client) CloseAndRecv() (*{{ CamelCase $method.Output.FullName }}, error) { + r := {{ CamelCase $method.Input.FullName }}{error: io.EOF, flags: SetCloseFlag(0, true) } + x.Send(&r) + return x.recv() + } + {{ end -}} + {{else -}} func (c *sub{{ CamelCaseName $service.Name }}Client) {{ CamelCaseName $method.Name }}(ctx context.Context, req *{{ CamelCase $method.Input.FullName }}) (res *{{ CamelCase $method.Output.FullName }}, err error) { ch := make(chan *{{ CamelCase $method.Output.FullName }}, 1) p := packet.Get() @@ -137,6 +329,7 @@ func (e CloseError) Error() string { packet.Put(p) return } + {{end -}} {{end -}} -{{end -}} -{{end}} \ No newline at end of file +{{ end -}} +{{end}} diff --git a/templates/constants.templ b/templates/constants.templ new file mode 100644 index 0000000..9e14ff7 --- /dev/null +++ b/templates/constants.templ @@ -0,0 +1,16 @@ +{{define "constants"}} + const connectionContextKey int = 1000 + + func SetCloseFlag(flags uint8, close bool) uint8 { + return flags | 0x1 + } + func HasCloseFlag(flags uint8) bool { + return flags & 1 == 1 + } + func SetErrorFlag(flags uint8, error bool) uint8 { + return flags | 0x2 + } + func HasErrorFlag(flags uint8) bool { + return flags & (1 << 1) == 1 + } +{{end}} \ No newline at end of file diff --git a/templates/customDecode.templ b/templates/customDecode.templ index 4f14573..185870f 100644 --- a/templates/customDecode.templ +++ b/templates/customDecode.templ @@ -2,7 +2,7 @@ x.error, err = d.Error() if err == nil { return nil } -x.ignore, err = d.Bool() +x.flags, err = d.Uint8() if err != nil { return err } \ No newline at end of file diff --git a/templates/customEncode.templ b/templates/customEncode.templ index 062b54b..429f23e 100644 --- a/templates/customEncode.templ +++ b/templates/customEncode.templ @@ -2,4 +2,4 @@ if x.error != nil { polyglot.Encoder(b).Error(x.error) return } -polyglot.Encoder(b).Bool(x.ignore) \ No newline at end of file +polyglot.Encoder(b).Uint8(x.flags) \ No newline at end of file diff --git a/templates/customFields.templ b/templates/customFields.templ index a37a725..027e539 100644 --- a/templates/customFields.templ +++ b/templates/customFields.templ @@ -1,2 +1,2 @@ error error -ignore bool \ No newline at end of file +flags uint8 \ No newline at end of file diff --git a/templates/imports.templ b/templates/imports.templ index eacc495..71cc312 100644 --- a/templates/imports.templ +++ b/templates/imports.templ @@ -13,5 +13,10 @@ import ( "{{$im}}" {{end -}} {{end}} +{{ if .numStreamMethods -}} + {{range $im := .streamMethodImports -}} + "{{$im}}" + {{end -}} +{{end -}} ) {{end}} \ No newline at end of file diff --git a/templates/interfaces.templ b/templates/interfaces.templ index 2194c80..cbefa37 100644 --- a/templates/interfaces.templ +++ b/templates/interfaces.templ @@ -10,7 +10,13 @@ type {{ CamelCaseName .Name }} interface { {{ range $i, $v := MakeIterable .Methods.Len -}} {{ $method := $.Methods.Get $i -}} + {{ if $method.IsStreamingClient }} + {{ CamelCaseName $method.Name }} (srv *{{ CamelCaseName $method.Name }}Server) error + {{ else if $method.IsStreamingServer }} + {{ CamelCaseName $method.Name }} (req *{{ CamelCase $method.Input.FullName }}, srv *{{ CamelCaseName $method.Name }}Server) error + {{else -}} {{ CamelCaseName $method.Name }} (context.Context, *{{ CamelCase $method.Input.FullName }}) (*{{ CamelCase $method.Output.FullName }}, error) + {{end -}} {{ end -}} } {{end}} \ No newline at end of file diff --git a/templates/server.templ b/templates/server.templ index 7f8f803..e0217ec 100644 --- a/templates/server.templ +++ b/templates/server.templ @@ -1,33 +1,166 @@ {{define "server"}} +type ServerMap[T any] struct { + servers map[uint16]*T + closed bool + mu sync.Mutex +} + +func NewServerMap[T any]() *ServerMap[T] { + return &ServerMap[T]{servers: make(map[uint16]*T)} +} + type Server struct { *frisbee.Server + onClosed func(*frisbee.Async, error) + + {{ range $i, $v := (MakeIterable .services.Len) -}} + {{ $service := $.services.Get $i -}} + {{ range $i, $v := (MakeIterable $service.Methods.Len) -}} + {{ $method := $service.Methods.Get $i -}} + {{ if $method.IsStreamingClient}} + next{{ CamelCaseName $method.Name }} uint16 + next{{ CamelCaseName $method.Name }}Mu sync.RWMutex + + streams{{ CamelCaseName $method.Name }} map[string]*ServerMap[{{ CamelCaseName $method.Name }}Server] + streams{{ CamelCaseName $method.Name }}Mu sync.RWMutex + {{end -}} + {{end -}} + {{end -}} } func NewServer({{ GetServerFields .services }}, tlsConfig *tls.Config, logger *zerolog.Logger) (*Server, error) { - var s *Server - table := make(frisbee.HandlerTable) - {{template "serverhandlers" .services -}} - var fsrv *frisbee.Server - var err error - if tlsConfig != nil { - fsrv, err = frisbee.NewServer(table, frisbee.WithTLS(tlsConfig), frisbee.WithLogger(logger)) - if err != nil { - return nil, err - } - } else { - fsrv, err = frisbee.NewServer(table, frisbee.WithLogger(logger)) - if err != nil { - return nil, err - } + var s *Server + table := make(frisbee.HandlerTable) + {{template "serverhandlers" .services -}} + var fsrv *frisbee.Server + var err error + if tlsConfig != nil { + fsrv, err = frisbee.NewServer(table, frisbee.WithTLS(tlsConfig), frisbee.WithLogger(logger)) + if err != nil { + return nil, err + } + } else { + fsrv, err = frisbee.NewServer(table, frisbee.WithLogger(logger)) + if err != nil { + return nil, err + } + } + + fsrv.ConnContext = func (ctx context.Context, conn *frisbee.Async) context.Context { + return context.WithValue(ctx, connectionContextKey, conn) + } + s, err = &Server{ + Server: fsrv, + }, nil + + fsrv.SetOnClosed(func(async *frisbee.Async, err error) { + {{ range $i, $v := (MakeIterable .services.Len) -}} + {{ $service := $.services.Get $i -}} + {{ range $i, $v := (MakeIterable $service.Methods.Len) -}} + {{ $method := $service.Methods.Get $i -}} + {{ if $method.IsStreamingClient -}} + s.streams{{ CamelCaseName $method.Name }}Mu.RLock() + if streamMap, ok := s.streams{{ CamelCaseName $method.Name }}[async.RemoteAddr().String()]; ok { + s.streams{{ CamelCaseName $method.Name }}Mu.RUnlock() + for _, stream := range streamMap.servers { + stream.close() + } + return + } + s.streams{{ CamelCaseName $method.Name }}Mu.RUnlock() + {{end -}} + {{end -}} + {{end -}} + if s.onClosed != nil { + s.onClosed(async, err) } + }) - s, err = &Server{ - Server: fsrv, - }, nil - return s, err + {{ range $i, $v := (MakeIterable .services.Len) -}} + {{ $service := $.services.Get $i -}} + {{ range $i, $v := (MakeIterable $service.Methods.Len) -}} + {{ $method := $service.Methods.Get $i -}} + {{ if $method.IsStreamingClient -}} + s.next{{ CamelCaseName $method.Name }} = 0 + s.streams{{ CamelCaseName $method.Name }} = make(map[string]*ServerMap[{{ CamelCaseName $method.Name }}Server]) + {{end -}} + {{end -}} + {{end -}} + return s, err +} + +func (s *Server) SetOnClosed(f func(*frisbee.Async, error)) error { + if f == nil { + return frisbee.OnClosedNil } + s.onClosed = f + return nil +} + +{{template "servermethods" .services }} {{ end -}} +{{define "servermethods"}} + {{ $counter := Counter 9 -}} + {{ range $i, $v := (MakeIterable .Len) -}} + {{ $service := $.Get $i -}} + {{ range $i, $v := (MakeIterable $service.Methods.Len) }} + {{ $method := $service.Methods.Get $i -}} + {{ $opIndex := call $counter -}} + {{if or $method.IsStreamingClient $method.IsStreamingServer -}} + type {{ CamelCaseName $method.Name }}Server struct { + context context.Context + recv func() (*{{ CamelCase $method.Input.FullName }}, error) + send func (*{{ CamelCase $method.Output.FullName }}) error + + {{ if $method.IsStreamingClient -}} + received *queue.Circular[{{ CamelCase $method.Input.FullName }}, *{{ CamelCase $method.Input.FullName }}] + stale []*{{ CamelCase $method.Input.FullName }} + staleMu sync.Mutex + {{ end -}} + closed *atomic.Bool + } + + func (x *{{ CamelCaseName $method.Name }}Server) Context() context.Context { + return x.context + } + + {{ if $method.IsStreamingClient -}} + func (x *{{ CamelCaseName $method.Name }}Server) Recv() (*{{ CamelCase $method.Input.FullName }}, error) { + return x.recv() + } + + func (x *{{ CamelCaseName $method.Name }}Server) close() { + x.staleMu.Lock() + x.closed.Store(true) + x.stale = x.received.Drain() + x.staleMu.Unlock() + x.received.Close() + } + {{ end -}} + + {{ if $method.IsStreamingServer -}} + func (x *{{ CamelCaseName $method.Name }}Server) Send(m *{{ CamelCase $method.Output.FullName }}) error { + return x.send(m) + } + {{ end -}} + + func (x *{{ CamelCaseName $method.Name }}Server) CloseSend() error { + r := {{ CamelCase $method.Output.FullName }}{error: io.EOF, flags: SetCloseFlag(0, true) } + return x.send(&r) + } + + {{ if or $method.IsStreamingClient $method.IsStreamingServer -}} + func (x *{{ CamelCaseName $method.Name }}Server) CloseAndSend(m *{{ CamelCase $method.Output.FullName }}) error { + m.flags = SetCloseFlag(m.flags, true) + return x.send(m) + } + {{ end -}} + {{end -}} + {{end -}} + {{end -}} +{{end}} + {{define "serverhandlers"}} {{ $counter := Counter 9 -}} {{ range $i, $v := (MakeIterable .Len) -}} @@ -39,10 +172,141 @@ func NewServer({{ GetServerFields .services }}, tlsConfig *tls.Config, logger *z req := New{{ CamelCase $method.Input.FullName }}() err := req.Decode((*incoming.Content)[:incoming.Metadata.ContentLength]) if err == nil { - if req.ignore { - {{ FirstLowerCaseName $service.Name }}.{{ CamelCaseName $method.Name }}(ctx, req) - return + {{ if or $method.IsStreamingClient $method.IsStreamingServer -}} + id := incoming.Metadata.Id + conn := ctx.Value(connectionContextKey).(*frisbee.Async) + + {{ if $method.IsStreamingClient -}} + s.streams{{ CamelCaseName $method.Name }}Mu.RLock() + if smap, ok := s.streams{{ CamelCaseName $method.Name }}[conn.RemoteAddr().String()]; ok { + s.streams{{ CamelCaseName $method.Name }}Mu.RUnlock() + smap.mu.Lock() + if srv, ok := smap.servers[id]; ok { + smap.mu.Unlock() + srv.received.Push(req) + if HasCloseFlag(req.flags) { + srv.close() + } + if _, ok := req.error.(CloseError); ok { + action = frisbee.CLOSE + } + return + } else { + smap.mu.Unlock() + } + } else { + s.streams{{ CamelCaseName $method.Name }}Mu.RUnlock() } + q := queue.NewCircular[{{ CamelCase $method.Input.FullName }}, *{{ CamelCase $method.Input.FullName }}](100) + q.Push(req) + {{ end -}} + + srv := &{{ CamelCaseName $method.Name }}Server{ + context: ctx, + {{ if $method.IsStreamingClient -}} + received: q, + stale: make([]*{{ CamelCase $method.Input.FullName }}, 0), + {{ end -}} + closed: atomic.NewBool(false), + } + + {{ if $method.IsStreamingClient -}} + s.streams{{ CamelCaseName $method.Name }}Mu.Lock() + if serverMap, ok := s.streams{{ CamelCaseName $method.Name }}[conn.RemoteAddr().String()]; ok { + s.streams{{ CamelCaseName $method.Name }}Mu.Unlock() + serverMap.mu.Lock() + serverMap.servers[id] = srv + serverMap.mu.Unlock() + } else { + s.streams{{ CamelCaseName $method.Name }}Mu.Unlock() + serverMap = NewServerMap[{{ CamelCaseName $method.Name }}Server]() + serverMap.servers[id] = srv + s.streams{{ CamelCaseName $method.Name }}Mu.Lock() + s.streams{{ CamelCaseName $method.Name }}[conn.RemoteAddr().String()] = serverMap + s.streams{{ CamelCaseName $method.Name }}Mu.Unlock() + } + + srv.recv = func() (*{{ CamelCase $method.Input.FullName }}, error) { + if srv.closed.Load() { + srv.staleMu.Lock() + if len(srv.stale) > 0 { + var r *{{ CamelCase $method.Input.FullName }} + r, srv.stale = srv.stale[0], srv.stale[1:] + srv.staleMu.Unlock() + if errors.Is(r.error, io.EOF) { + return nil, io.EOF + } + return r, nil + } + srv.staleMu.Unlock() + return nil, io.EOF + } + + readPacket, err := srv.received.Pop() + if err != nil { + if srv.closed.Load() { + srv.staleMu.Lock() + if len(srv.stale) > 0 { + var r *{{ CamelCase $method.Input.FullName }} + r, srv.stale = srv.stale[0], srv.stale[1:] + srv.staleMu.Unlock() + return r, nil + } + srv.staleMu.Unlock() + } + return nil, io.EOF + } + if errors.Is(readPacket.error, io.EOF) { + return nil, io.EOF + } + return readPacket, nil + } + {{ end -}} + + srv.send = func (m *{{ CamelCase $method.Output.FullName }}) error { + p := packet.Get() + p.Metadata.Operation = {{ $count }} + + p.Metadata.Id = id + + m.Encode(p.Content) + p.Metadata.ContentLength = uint32(len(*p.Content)) + err := conn.WritePacket(p) + if err != nil { + packet.Put(p) + return err + } + packet.Put(p) + return nil + } + + go func() { + {{ if $method.IsStreamingClient -}} + err := {{ FirstLowerCaseName $service.Name }}.{{ CamelCaseName $method.Name }}(srv) + {{ else }} + err := {{ FirstLowerCaseName $service.Name }}.{{ CamelCaseName $method.Name }}(req, srv) + {{ end -}} + if err != nil { + res := {{ CamelCase $method.Output.FullName }}{error: err} + res.flags = SetErrorFlag(res.flags, true) + srv.CloseAndSend(&res) + } else { + srv.CloseSend() + } + {{ if $method.IsStreamingClient -}} + s.streams{{ CamelCaseName $method.Name }}Mu.RLock() + if smap, ok := s.streams{{ CamelCaseName $method.Name }}[conn.RemoteAddr().String()]; ok { + s.streams{{ CamelCaseName $method.Name }}Mu.RUnlock() + smap.mu.Lock() + delete(smap.servers, incoming.Metadata.Id) + smap.mu.Unlock() + } else { + s.streams{{ CamelCaseName $method.Name }}Mu.RUnlock() + } + {{ end -}} + }() + {{ end -}} + {{ if not (or $method.IsStreamingServer $method.IsStreamingClient) -}} var res *{{ CamelCase $method.Output.FullName }} outgoing = incoming outgoing.Content.Reset() @@ -56,6 +320,7 @@ func NewServer({{ GetServerFields .services }}, tlsConfig *tls.Config, logger *z res.Encode(outgoing.Content) } outgoing.Metadata.ContentLength = uint32(len(*outgoing.Content)) + {{end -}} } return } From dc6ee007c4ed3c5a994be0f1ba98d9b16b418743 Mon Sep 17 00:00:00 2001 From: Shivansh Vij Date: Wed, 28 Sep 2022 16:51:29 -0400 Subject: [PATCH 4/5] Updating frisbee and polyglot versions --- go.mod | 8 ++++---- go.sum | 13 ++++++------- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/go.mod b/go.mod index 9b3d146..1d6ee2f 100644 --- a/go.mod +++ b/go.mod @@ -3,23 +3,23 @@ module github.com/loopholelabs/frpc-go go 1.18 require ( - github.com/loopholelabs/polyglot-go v0.4.0 + github.com/loopholelabs/common v0.4.4 + github.com/loopholelabs/frisbee-go v0.7.0 + github.com/loopholelabs/polyglot-go v0.5.0 github.com/loopholelabs/testing v0.2.3 github.com/rs/zerolog v1.28.0 github.com/stretchr/testify v1.8.0 + go.uber.org/atomic v1.10.0 google.golang.org/protobuf v1.28.0 ) require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/kr/text v0.2.0 // indirect - github.com/loopholelabs/common v0.4.4 // indirect github.com/mattn/go-colorable v0.1.12 // indirect github.com/mattn/go-isatty v0.0.14 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - go.uber.org/atomic v1.9.0 // indirect golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect - github.com/loopholelabs/frisbee-go v0.6.0 // indirect ) diff --git a/go.sum b/go.sum index f74db80..5075225 100644 --- a/go.sum +++ b/go.sum @@ -12,10 +12,10 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/loopholelabs/common v0.4.4 h1:Ge+1v1WiLYgR/4pziOQoJAwUqUm1c9j6nQvnkiFFBsk= github.com/loopholelabs/common v0.4.4/go.mod h1:YKnljczr4jgxkHhhAwIHh3CJXaff89YBd8Vp3pwpG3k= -github.com/loopholelabs/frisbee-go v0.6.0 h1:4HM/o0Q5aPbGaEOvHf7PbYI/4vYT6K+hlW+R0Ic+SfE= -github.com/loopholelabs/frisbee-go v0.6.0/go.mod h1:DAb8ALrCXrdhDFv6mRJhmWljvOVQb8cZ9y24NiMNFC0= -github.com/loopholelabs/polyglot-go v0.4.0 h1:HavI5O6lMKF7urRgnVk+8vM4WqCpJGkH81dxLnhFGAA= -github.com/loopholelabs/polyglot-go v0.4.0/go.mod h1:Z0QiNv4KRuWjQWpUerMhmkvRh6ks1pYmEH4SGpG0EHQ= +github.com/loopholelabs/frisbee-go v0.7.0 h1:LGzG/NYQBsRnmojfVoSBTC31PgfV9XutQA39IU9gzf8= +github.com/loopholelabs/frisbee-go v0.7.0/go.mod h1:XfDgwwOkgN/ktzaDAq3Zu0A9Dl0w5/xkZ2qfXAvRbjs= +github.com/loopholelabs/polyglot-go v0.5.0 h1:F65/d+65qgAu2F0GcWzP6UVIwd9897bNEgylNMr8FGk= +github.com/loopholelabs/polyglot-go v0.5.0/go.mod h1:Z0QiNv4KRuWjQWpUerMhmkvRh6ks1pYmEH4SGpG0EHQ= github.com/loopholelabs/testing v0.2.3 h1:4nVuK5ctaE6ua5Z0dYk2l7xTFmcpCYLUeGjRBp8keOA= github.com/loopholelabs/testing v0.2.3/go.mod h1:gqtGY91soYD1fQoKQt/6kP14OYpS7gcbcIgq5mc9m8Q= github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40= @@ -31,12 +31,11 @@ github.com/rs/zerolog v1.28.0 h1:MirSo27VyNi7RJYP3078AA1+Cyzd2GB66qy3aUHvsWY= github.com/rs/zerolog v1.28.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= -go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= +go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= go.uber.org/goleak v1.1.12 h1:gZAh5/EyT/HQwlpkCy6wTpqfH9H8Lz8zbm3dZh+OyzA= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6 h1:foEbQz/B0Oz6YIqu/69kfXPYeFQAuuMYFkjaqXzl5Wo= From 5b8add87d8a2b4d420ffbc34cf6f1b6825c8e64d Mon Sep 17 00:00:00 2001 From: Shivansh Vij Date: Wed, 28 Sep 2022 16:56:03 -0400 Subject: [PATCH 5/5] Updating changelog, bumping version --- CHANGELOG.md | 22 ++++++++++++++++++---- internal/version/version.go | 2 +- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8224a89..87d8020 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,27 +7,41 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +## [v0.7.0] - 2022-09-28 + +### Features + +- fRPC now uses the `VarInt` encoding format under the hood (added in [polyglot-go v0.5.0](https://github.com/loopholelabs/polyglot-go)) which should help reduce the number of bytes an RPC call is serialized to +- A new `CloseError` type has been added which, when returned by an RPC call, causes the connection to be closed after the message is written. This can be useful for authentication or connection management. +- Streaming is now available! The API matches gRPC's so it should be a drop-in replacement! + +### Changes + +- The [polyglot-go](https://github.com/loopholelabs/polyglot-go) dependency has been bumped to `v0.5.0` +- The [frisbee-go](https://github.com/loopholelabs/frisbee-go) dependency has been b umped to `v0.7.0` + ## [v0.6.0] - 2022-08-24 (Beta) -## Changes +### Changes - Refactoring the generated code to use the [polyglot-go](https://github.com/loopholelabs/polyglot-go) library to generate message encode/decode functions. ([#3](https://github.com/loopholelabs/frpc-go/pull/3)) -## Fixes +### Fixes - Fixed an issue with the generated code that caused compilation issues when the names of two methods in different services were the same ([#5](https://github.com/loopholelabs/frpc-go/issues/5)) ## [v0.5.1] - 2022-07-20 (Beta) -## Fixes +### Fixes - Fixed an issue where if the number of services is 0 the RPC Generator would crash ([#101](https://github.com/loopholelabs/frisbee-go/issues/101)) > Changelogs for [v0.5.0] and before can be found at https://github.com/loopholelabs/frisbee-go -[unreleased]: https://github.com/loopholelabs/frpc-go/compare/v0.6.0...HEAD +[unreleased]: https://github.com/loopholelabs/frpc-go/compare/v0.7.0...HEAD +[v0.7.0]: https://github.com/loopholelabs/frpc-go/releases/tag/v0.7.0 [v0.6.0]: https://github.com/loopholelabs/frpc-go/releases/tag/v0.6.0 [v0.5.1]: https://github.com/loopholelabs/frpc-go/releases/tag/v0.5.1 [v0.5.0]: https://github.com/loopholelabs/frisbee-go/compare/v0.4.6...v0.5.0 diff --git a/internal/version/version.go b/internal/version/version.go index 8f4b7b4..0b9768e 100644 --- a/internal/version/version.go +++ b/internal/version/version.go @@ -17,5 +17,5 @@ package version const ( - Version = "v0.6.0" + Version = "v0.7.0" )