├── .github ├── dependabot.yml └── workflows │ ├── dependabot-auto-merge-go.yml │ ├── lint.yml │ ├── resolve-modules.sh │ └── test.yml ├── .golangci.goheader.template ├── .golangci.yml ├── LICENSE.md ├── README.md ├── bwgrpc ├── .golangci.goheader.template ├── .golangci.yml ├── LICENSE.md ├── README.md ├── client.go ├── client_test.go ├── go.mod ├── go.sum └── testproto │ ├── buf.gen.yaml │ ├── buf.yaml │ ├── gen.go │ ├── mock.go │ ├── test.pb.go │ ├── test.proto │ └── test_grpc.pb.go ├── byte.go ├── examples ├── client │ └── main.go └── server │ └── main.go ├── go.mod ├── go.sum ├── io.go ├── io_test.go └── net.go /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # Docs: https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/configuration-options-for-dependency-updates 2 | version: 2 3 | updates: 4 | 5 | # Maintain dependencies for GitHub Actions 6 | - package-ecosystem: "github-actions" 7 | directory: "/" 8 | schedule: 9 | interval: "daily" 10 | commit-message: 11 | prefix: ".github:" 12 | 13 | # Maintain dependencies for Go 14 | - package-ecosystem: "gomod" 15 | directory: "/" 16 | schedule: 17 | interval: "daily" 18 | commit-message: 19 | prefix: "go.mod:" 20 | -------------------------------------------------------------------------------- /.github/workflows/dependabot-auto-merge-go.yml: -------------------------------------------------------------------------------- 1 | # This action automatically merges dependabot PRs that update go dependencies (only patch and minor updates). 2 | # Based on: https://docs.github.com/en/code-security/supply-chain-security/keeping-your-dependencies-updated-automatically/automating-dependabot-with-github-actions#enable-auto-merge-on-a-pull-request 3 | 4 | name: Dependabot auto-merge 5 | on: 6 | pull_request: 7 | # Run this action when dependabot labels the PR, we care about the 'go' label. 8 | types: [labeled] 9 | 10 | permissions: 11 | pull-requests: write 12 | contents: write 13 | 14 | jobs: 15 | dependabot-go: 16 | runs-on: ubuntu-latest 17 | if: ${{ github.actor == 'dependabot[bot]' && contains(github.event.pull_request.labels.*.name, 'go') }} 18 | steps: 19 | - name: Dependabot metadata 20 | id: metadata 21 | uses: dependabot/fetch-metadata@v2.4.0 22 | with: 23 | github-token: "${{ secrets.GITHUB_TOKEN }}" 24 | 25 | - name: Approve PR 26 | # Approve only patch and minor updates 27 | if: ${{ steps.metadata.outputs.update-type != 'version-update:semver-major' }} 28 | run: gh pr review --approve "$PR_URL" 29 | env: 30 | PR_URL: ${{ github.event.pull_request.html_url }} 31 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 32 | 33 | - name: Enable auto-merge for Dependabot PRs 34 | # Enable auto-merging only for patch and minor updates 35 | if: ${{ steps.metadata.outputs.update-type != 'version-update:semver-major' }} 36 | run: gh pr merge --auto --squash "$PR_URL" 37 | env: 38 | PR_URL: ${{ github.event.pull_request.html_url }} 39 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 40 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: lint 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | 8 | jobs: 9 | resolve-modules: 10 | name: Resolve Modules 11 | runs-on: ubuntu-latest 12 | outputs: 13 | matrix: ${{ steps.set-matrix.outputs.matrix }} 14 | steps: 15 | - name: Checkout Sources 16 | uses: actions/checkout@v4 17 | - id: set-matrix 18 | run: ./.github/workflows/resolve-modules.sh 19 | golangci-lint: 20 | needs: resolve-modules 21 | runs-on: ubuntu-latest 22 | strategy: 23 | matrix: ${{ fromJson(needs.resolve-modules.outputs.matrix) }} 24 | steps: 25 | - uses: actions/checkout@v4 26 | - uses: actions/setup-go@v5 27 | with: 28 | go-version-file: 'go.mod' 29 | 30 | - name: golangci-lint 31 | uses: golangci/golangci-lint-action@v8 32 | with: 33 | version: v2.1.6 34 | working-directory: ${{ matrix.workdir }} 35 | 36 | -------------------------------------------------------------------------------- /.github/workflows/resolve-modules.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # Recursively finds all directories with a go.mod file and creates 3 | # a GitHub Actions JSON output option. This is used by the linter action. 4 | 5 | # Credits go to twelho - https://github.com/golangci/golangci-lint/issues/828#issuecomment-658207652 6 | 7 | echo "Resolving modules in $(pwd)" 8 | 9 | PATHS=$(find . -type f -name go.mod -printf '{"workdir":"%h"},') 10 | echo "::set-output name=matrix::{\"include\":[${PATHS%?}]}" 11 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: test 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | 8 | jobs: 9 | test: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v4 13 | - uses: actions/setup-go@v5 14 | with: 15 | go-version-file: 'go.mod' 16 | 17 | # go test runs tests for all modules 18 | - name: go test 19 | run: find . -name go.mod -execdir go test -v -race -count=1 ./... \; 20 | -------------------------------------------------------------------------------- /.golangci.goheader.template: -------------------------------------------------------------------------------- 1 | Copyright © {{ copyright-year }} Meroxa, Inc. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | version: "2" 2 | linters: 3 | default: none 4 | enable: 5 | - bodyclose 6 | - dogsled 7 | - durationcheck 8 | - errcheck 9 | - errname 10 | - goconst 11 | - gocritic 12 | - gocyclo 13 | - goheader 14 | - gomoddirectives 15 | - gomodguard 16 | - goprintffuncname 17 | - gosec 18 | - govet 19 | - ineffassign 20 | - makezero 21 | - noctx 22 | - nolintlint 23 | - predeclared 24 | - revive 25 | - staticcheck 26 | - unconvert 27 | - unused 28 | - wastedassign 29 | - whitespace 30 | settings: 31 | gocyclo: 32 | min-complexity: 20 33 | goheader: 34 | values: 35 | regexp: 36 | copyright-year: 20[2-9]\d 37 | template-path: .golangci.goheader.template 38 | nolintlint: 39 | require-explanation: true 40 | require-specific: true 41 | allow-unused: false 42 | exclusions: 43 | generated: lax 44 | presets: 45 | - comments 46 | - common-false-positives 47 | - legacy 48 | - std-error-handling 49 | rules: 50 | - linters: 51 | - goconst 52 | path: (.+)_test\.go 53 | paths: 54 | - examples/.* 55 | formatters: 56 | enable: 57 | - gofmt 58 | - goimports 59 | settings: 60 | gofmt: 61 | simplify: false 62 | exclusions: 63 | generated: lax 64 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright © 2023 Meroxa, Inc. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BWLimit 2 | 3 | [![License](https://img.shields.io/badge/license-Apache%202-blue)](https://github.com/ConduitIO/bwlimit/blob/main/LICENSE.md) 4 | [![Test](https://github.com/ConduitIO/bwlimit/actions/workflows/test.yml/badge.svg)](https://github.com/ConduitIO/bwlimit/actions/workflows/test.yml) 5 | [![Go Report Card](https://goreportcard.com/badge/github.com/conduitio/bwlimit)](https://goreportcard.com/report/github.com/conduitio/bwlimit) 6 | [![Go Reference](https://pkg.go.dev/badge/github.com/conduitio/bwlimit.svg)](https://pkg.go.dev/github.com/conduitio/bwlimit) 7 | 8 | BWLimit lets you configure a bandwidth limit on [`net.Conn`](https://pkg.go.dev/net#Conn), 9 | [`io.Reader`](https://pkg.go.dev/io#Reader) and [`io.Writer`](https://pkg.go.dev/io#Writer). 10 | 11 | ## Quick Start 12 | 13 | BWLimit can be used to throttle the bandwidth (bytes per second) either on the 14 | client or server. 15 | 16 | Install it with: 17 | 18 | ```sh 19 | go get github.com/conduitio/bwlimit 20 | ``` 21 | 22 | See usage examples below: 23 | - [Server Side](#server-side) 24 | - [Client Side](#client-side) 25 | - [gRPC Client Interceptor](#grpc-client-interceptor) 26 | 27 | Or check out the [runnable examples](./examples). 28 | 29 | ### Server Side 30 | 31 | To limit the bandwidth on the server use 32 | [`bwlimit.NewListener`](https://pkg.go.dev/github.com/conduitio/bwlimit#NewListener). 33 | 34 | ```go 35 | package main 36 | 37 | import ( 38 | "io" 39 | "log" 40 | "net" 41 | "net/http" 42 | 43 | "github.com/conduitio/bwlimit" 44 | ) 45 | 46 | const ( 47 | writeLimit = 1 * bwlimit.Mebibyte // write limit is 1048576 B/s 48 | readLimit = 4 * bwlimit.KB // read limit is 4000 B/s 49 | ) 50 | 51 | func main() { 52 | ln, err := net.Listen("tcp", ":8080") 53 | if err != nil { 54 | log.Fatalf("Failed to listen: %v", err) 55 | } 56 | // limit the listener bandwidth 57 | ln = bwlimit.NewListener(ln, writeLimit, readLimit) 58 | 59 | http.Handle("/echo", http.HandlerFunc(echoHandler)) 60 | srv := &http.Server{Addr: addr} 61 | log.Fatalf("Failed to serve: %v", srv.Serve(ln)) 62 | } 63 | 64 | func echoHandler(w http.ResponseWriter, r *http.Request) { 65 | body, _ := io.ReadAll(r.Body) 66 | _, _ = w.Write(body) 67 | } 68 | ``` 69 | 70 | ### Client Side 71 | 72 | To limit the bandwidth on the client use 73 | [`bwlimit.NewDialer`](https://pkg.go.dev/github.com/conduitio/bwlimit#NewDialer). 74 | 75 | ```go 76 | package main 77 | 78 | import ( 79 | "io" 80 | "net" 81 | "net/http" 82 | "time" 83 | 84 | "github.com/conduitio/bwlimit" 85 | ) 86 | 87 | const ( 88 | writeLimit = 1 * bwlimit.Mebibyte // write limit is 1048576 B/s 89 | readLimit = 4 * bwlimit.KB // read limit is 4000 B/s 90 | ) 91 | 92 | func main() { 93 | // change dialer in the default transport to use a bandwidth limit 94 | dialer := bwlimit.NewDialer(&net.Dialer{ 95 | Timeout: 30 * time.Second, 96 | KeepAlive: 30 * time.Second, 97 | }, writeLimit, readLimit) 98 | http.DefaultTransport.(*http.Transport).DialContext = dialer.DialContext 99 | 100 | // requests through the default client respect the bandwidth limit now 101 | resp, _ := http.DefaultClient.Get("http://localhost:8080/echo") 102 | _, _ = io.ReadAll(resp.Body) 103 | } 104 | ``` 105 | 106 | ### gRPC Client Interceptor 107 | 108 | The gRPC interceptor is provided in a separate module, import it with: 109 | 110 | ```sh 111 | go get github.com/conduitio/bwlimit/bwgrpc 112 | ``` 113 | 114 | To limit the bandwidth on a gRPC client use 115 | [`bwgrpc.WithBandwidthLimitedContextDialer`](https://pkg.go.dev/github.com/conduitio/bwlimit/bwgrpc#WithBandwidthLimitedContextDialer). 116 | 117 | ```go 118 | package main 119 | 120 | import ( 121 | "context" 122 | "log" 123 | 124 | "github.com/conduitio/bwlimit" 125 | "github.com/conduitio/bwlimit/bwgrpc" 126 | "github.com/conduitio/bwlimit/bwgrpc/testproto" 127 | "google.golang.org/grpc" 128 | ) 129 | 130 | const ( 131 | writeLimit = 1 * bwlimit.Mebibyte // write limit is 1048576 B/s 132 | readLimit = 4 * bwlimit.KB // read limit is 4000 B/s 133 | ) 134 | 135 | func main() { 136 | // open connection with limited bandwidth 137 | conn, err := grpc.DialContext( 138 | context.Background(), 139 | "localhost:8080", 140 | // limit the bandwidth 141 | bwgrpc.WithBandwidthLimitedContextDialer(writeLimit, readLimit, nil), 142 | ) 143 | if err != nil { 144 | log.Fatalf("Failed to dial: %v", err) 145 | } 146 | defer conn.Close() 147 | 148 | // create gRPC client with the limited connection 149 | c := testproto.NewTestServiceClient(conn) 150 | 151 | // use client to send request 152 | _, err = c.TestRPC(ctx, &testproto.TestRequest{}) 153 | if err != nil { 154 | log.Fatalf("Failed to send RPC: %v", err) 155 | } 156 | } 157 | ``` 158 | 159 | ## Limitation 160 | 161 | Please note that bwlimit limits the speed at which data is read from the local 162 | kernel's TCP buffer, and not directly from the remote connection. This means 163 | that the local buffer may become filled and cause the network to be idle while 164 | data is read slowly from the buffer, which can cause the actual bandwidth to 165 | differ from the one measured in Go code. 166 | -------------------------------------------------------------------------------- /bwgrpc/.golangci.goheader.template: -------------------------------------------------------------------------------- 1 | ../.golangci.goheader.template -------------------------------------------------------------------------------- /bwgrpc/.golangci.yml: -------------------------------------------------------------------------------- 1 | ../.golangci.yml -------------------------------------------------------------------------------- /bwgrpc/LICENSE.md: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright © 2023 Meroxa, Inc. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /bwgrpc/README.md: -------------------------------------------------------------------------------- 1 | # BWLimit gRPC 2 | 3 | [![Go Reference](https://pkg.go.dev/badge/github.com/conduitio/bwlimit/bwgrpc.svg)](https://pkg.go.dev/github.com/conduitio/bwlimit/bwgrpc) 4 | 5 | This module provides a `grpc.DialOption` for constructing a gRPC connection with 6 | a bandwidth limit. See 7 | [github.com/ConduitIO/bwlimit](https://github.com/ConduitIO/bwlimit) for more 8 | information. 9 | 10 | ## Quick Start 11 | 12 | Install it using: 13 | 14 | ```sh 15 | go get github.com/conduitio/bwlimit/bwgrpc 16 | ``` 17 | 18 | To limit the bandwidth on a gRPC client use 19 | [`bwgrpc.WithBandwidthLimitedContextDialer`](https://pkg.go.dev/github.com/conduitio/bwlimit/bwgrpc#WithBandwidthLimitedContextDialer). 20 | 21 | ```go 22 | package main 23 | 24 | import ( 25 | "context" 26 | "log" 27 | 28 | "github.com/conduitio/bwlimit" 29 | "github.com/conduitio/bwlimit/bwgrpc" 30 | "github.com/conduitio/bwlimit/bwgrpc/testproto" 31 | "google.golang.org/grpc" 32 | ) 33 | 34 | const ( 35 | writeLimit = 1 * bwlimit.Mebibyte // write limit is 1048576 B/s 36 | readLimit = 4 * bwlimit.KB // read limit is 4000 B/s 37 | ) 38 | 39 | func main() { 40 | // open connection with limited bandwidth 41 | conn, err := grpc.DialContext( 42 | context.Background(), 43 | "localhost:8080", 44 | // limit the bandwidth 45 | bwgrpc.WithBandwidthLimitedContextDialer(writeLimit, readLimit, nil), 46 | ) 47 | if err != nil { 48 | log.Fatalf("Failed to dial: %v", err) 49 | } 50 | defer conn.Close() 51 | 52 | // create gRPC client with the limited connection 53 | c := testproto.NewTestServiceClient(conn) 54 | 55 | // use client to send request 56 | _, err = c.TestRPC(ctx, &testproto.TestRequest{}) 57 | if err != nil { 58 | log.Fatalf("Failed to send RPC: %v", err) 59 | } 60 | } 61 | ``` 62 | -------------------------------------------------------------------------------- /bwgrpc/client.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Meroxa, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package bwgrpc 16 | 17 | import ( 18 | "context" 19 | "net" 20 | "net/url" 21 | "strings" 22 | 23 | "github.com/conduitio/bwlimit" 24 | 25 | "google.golang.org/grpc" 26 | ) 27 | 28 | // WithBandwidthLimitedContextDialer returns a DialOption that sets a dialer to 29 | // create connections with a bandwidth limit. If FailOnNonTempDialError() is set 30 | // to true, and an error is returned by f, gRPC checks the error's Temporary() 31 | // method to decide if it should try to reconnect to the network address. 32 | // A zero value for writeBytesPerSecond or readBytesPerSecond means the 33 | // corresponding action will not have a bandwidth limit. 34 | // This option can NOT be used together with grpc.WithContextDialer. 35 | func WithBandwidthLimitedContextDialer( 36 | writeBytesPerSecond, 37 | readBytesPerSecond bwlimit.Byte, 38 | f func(context.Context, string) (net.Conn, error), 39 | ) grpc.DialOption { 40 | return grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) { 41 | conn, err := dial(ctx, addr, f) 42 | if err != nil { 43 | return nil, err 44 | } 45 | 46 | return bwlimit.NewConn(conn, writeBytesPerSecond, readBytesPerSecond), nil 47 | }) 48 | } 49 | 50 | // dial uses the dialer to get a connection if supplied, and falls back to the 51 | // default implementation used by google.golang.org/grpc. 52 | func dial(ctx context.Context, addr string, dialer func(context.Context, string) (net.Conn, error)) (net.Conn, error) { 53 | if dialer != nil { 54 | return dialer(ctx, addr) 55 | } 56 | 57 | // default dialer copied from google.golang.org/grpc 58 | networkType, address := parseDialTarget(addr) 59 | return (&net.Dialer{}).DialContext(ctx, networkType, address) 60 | } 61 | 62 | // parseDialTarget returns the network and address to pass to dialer. 63 | // Copied from google.golang.org/grpc. 64 | func parseDialTarget(target string) (string, string) { 65 | net := "tcp" 66 | m1 := strings.Index(target, ":") 67 | m2 := strings.Index(target, ":/") 68 | // handle unix:addr which will fail with url.Parse 69 | if m1 >= 0 && m2 < 0 { 70 | if n := target[0:m1]; n == "unix" { 71 | return n, target[m1+1:] 72 | } 73 | } 74 | if m2 >= 0 { 75 | t, err := url.Parse(target) 76 | if err != nil { 77 | return net, target 78 | } 79 | scheme := t.Scheme 80 | addr := t.Path 81 | if scheme == "unix" { 82 | if addr == "" { 83 | addr = t.Host 84 | } 85 | return scheme, addr 86 | } 87 | } 88 | return net, target 89 | } 90 | -------------------------------------------------------------------------------- /bwgrpc/client_test.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Meroxa, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package bwgrpc 16 | 17 | import ( 18 | "context" 19 | "log" 20 | "net" 21 | "sync" 22 | "testing" 23 | "time" 24 | 25 | "github.com/conduitio/bwlimit/bwgrpc/testproto" 26 | "github.com/golang/mock/gomock" 27 | "google.golang.org/grpc" 28 | "google.golang.org/grpc/credentials/insecure" 29 | "google.golang.org/grpc/test/bufconn" 30 | ) 31 | 32 | func TestInterceptorBandwidthLimit(t *testing.T) { 33 | // use in-memory connection 34 | lis := bufconn.Listen(1024 * 1024) 35 | dialer := func(ctx context.Context, _ string) (net.Conn, error) { 36 | return lis.DialContext(ctx) 37 | } 38 | 39 | // prepare server 40 | wantResp := &testproto.TestResponse{Code: 1} 41 | startTestServer(t, lis, wantResp) 42 | 43 | // prepare client with write bandwidth limit of 100 B/s 44 | c := newTestClient(t, WithBandwidthLimitedContextDialer(100, 0, dialer)) 45 | 46 | // send a request and measure how long it takes to get a response 47 | before := time.Now() 48 | resp, err := c.TestRPC(context.Background(), &testproto.TestRequest{Id: "abcdefghijklmnopqrstuvwxyz"}) 49 | gotDelay := time.Since(before) 50 | if err != nil { 51 | t.Fatalf("Failed to call TestRPC: %v", err) 52 | } 53 | 54 | if resp.Code != wantResp.Code { 55 | t.Fatalf("responses don't match, expected %v, got %v", resp, wantResp) 56 | } 57 | 58 | // check how long it took 59 | const ( 60 | // It should take 0.55 seconds, since we need to write 155 bytes and are rate limited to 100 B/s 61 | // After writing 100 bytes we delay for 550ms to write the remaining 55 bytes 62 | wantDelay = 550 * time.Millisecond 63 | // Allow 10 milliseconds of difference 64 | epsilon = 10 * time.Millisecond 65 | ) 66 | 67 | gotDiff := gotDelay - wantDelay 68 | if gotDiff < 0 { 69 | gotDiff = -gotDiff 70 | } 71 | 72 | if gotDiff > epsilon { 73 | t.Fatalf("expected a maximum delay of %v, got %v, allowed epsilon of %v exceeded", wantDelay, gotDelay, epsilon) 74 | } 75 | } 76 | 77 | func startTestServer(t *testing.T, lis net.Listener, resp *testproto.TestResponse) { 78 | ctrl := gomock.NewController(t) 79 | srv := grpc.NewServer() 80 | 81 | // create and register simple mock server 82 | mockServer := testproto.NewMockTestServiceServer(ctrl) 83 | mockServer.EXPECT(). 84 | TestRPC(gomock.Any(), gomock.Any()). 85 | DoAndReturn( 86 | func(context.Context, *testproto.TestRequest) (*testproto.TestResponse, error) { 87 | return resp, nil 88 | }, 89 | ) 90 | testproto.RegisterTestServiceServer(srv, mockServer) 91 | 92 | // start gRPC server 93 | var wg sync.WaitGroup 94 | wg.Add(1) 95 | go func() { 96 | defer wg.Done() 97 | if err := srv.Serve(lis); err != nil { 98 | log.Fatalf("Server exited with error: %v", err) 99 | } 100 | }() 101 | t.Cleanup(func() { 102 | srv.GracefulStop() 103 | wg.Wait() 104 | }) 105 | } 106 | 107 | func newTestClient(t *testing.T, dialerOption grpc.DialOption) testproto.TestServiceClient { 108 | conn, err := grpc.DialContext( 109 | context.Background(), 110 | "bufnet", 111 | grpc.WithTransportCredentials(insecure.NewCredentials()), 112 | // this interceptor limits the bandwidth 113 | dialerOption, 114 | ) 115 | if err != nil { 116 | t.Fatalf("Failed to dial bufnet: %v", err) 117 | } 118 | t.Cleanup(func() { 119 | conn.Close() 120 | }) 121 | 122 | return testproto.NewTestServiceClient(conn) 123 | } 124 | -------------------------------------------------------------------------------- /bwgrpc/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/conduitio/bwlimit/bwgrpc 2 | 3 | go 1.20 4 | 5 | require ( 6 | github.com/conduitio/bwlimit v0.1.0 7 | github.com/golang/mock v1.6.0 8 | google.golang.org/grpc v1.54.0 9 | google.golang.org/protobuf v1.30.0 10 | ) 11 | 12 | require ( 13 | github.com/golang/protobuf v1.5.2 // indirect 14 | golang.org/x/net v0.8.0 // indirect 15 | golang.org/x/sys v0.6.0 // indirect 16 | golang.org/x/text v0.8.0 // indirect 17 | golang.org/x/time v0.3.0 // indirect 18 | google.golang.org/genproto v0.0.0-20230110181048-76db0878b65f // indirect 19 | ) 20 | -------------------------------------------------------------------------------- /bwgrpc/go.sum: -------------------------------------------------------------------------------- 1 | github.com/conduitio/bwlimit v0.1.0 h1:x3ijON0TSghQob4tFKaEvKixFmYKfVJQeSpXluC2JvE= 2 | github.com/conduitio/bwlimit v0.1.0/go.mod h1:E+ASZ1/5L33MTb8hJTERs5Xnmh6Ulq3jbRh7LrdbXWU= 3 | github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= 4 | github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= 5 | github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= 6 | github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= 7 | github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= 8 | github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 9 | github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= 10 | github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= 11 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 12 | golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 13 | golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= 14 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 15 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 16 | golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= 17 | golang.org/x/net v0.8.0 h1:Zrh2ngAOFYneWTAIAPethzeaQLuHwhuBkuV6ZiRnUaQ= 18 | golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= 19 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 20 | golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 21 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 22 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 23 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 24 | golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 25 | golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 26 | golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= 27 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 28 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 29 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 30 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 31 | golang.org/x/text v0.8.0 h1:57P1ETyNKtuIjB4SRd15iJxuhj8Gc416Y78H3qgMh68= 32 | golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= 33 | golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= 34 | golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= 35 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 36 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 37 | golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= 38 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 39 | golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 40 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 41 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 42 | google.golang.org/genproto v0.0.0-20230110181048-76db0878b65f h1:BWUVssLB0HVOSY78gIdvk1dTVYtT1y8SBWtPYuTJ/6w= 43 | google.golang.org/genproto v0.0.0-20230110181048-76db0878b65f/go.mod h1:RGgjbofJ8xD9Sq1VVhDM1Vok1vRONV+rg+CjzG4SZKM= 44 | google.golang.org/grpc v1.54.0 h1:EhTqbhiYeixwWQtAEZAxmV9MGqcjEU2mFx52xCzNyag= 45 | google.golang.org/grpc v1.54.0/go.mod h1:PUSEXI6iWghWaB6lXM4knEgpJNu2qUcKfDtNci3EC2g= 46 | google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= 47 | google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= 48 | google.golang.org/protobuf v1.30.0 h1:kPPoIgf3TsEvrm0PFe15JQ+570QVxYzEvvHqChK+cng= 49 | google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= 50 | -------------------------------------------------------------------------------- /bwgrpc/testproto/buf.gen.yaml: -------------------------------------------------------------------------------- 1 | version: v1 2 | managed: 3 | enabled: true 4 | go_package_prefix: 5 | default: "github.com/conduitio/bwlimit/bwgrpc/testproto" 6 | plugins: 7 | - plugin: buf.build/protocolbuffers/go:v1.29.1 8 | out: . 9 | opt: 10 | - paths=source_relative 11 | - plugin: buf.build/grpc/go:v1.3.0 12 | out: . 13 | opt: 14 | - paths=source_relative 15 | -------------------------------------------------------------------------------- /bwgrpc/testproto/buf.yaml: -------------------------------------------------------------------------------- 1 | version: v1 2 | name: buf.build/conduitio/bwlimit 3 | -------------------------------------------------------------------------------- /bwgrpc/testproto/gen.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Meroxa, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package testproto 16 | 17 | //go:generate mockgen -destination=mock.go -package=testproto -mock_names=TestServiceServer=MockTestServiceServer github.com/conduitio/bwlimit/bwgrpc/testproto TestServiceServer 18 | -------------------------------------------------------------------------------- /bwgrpc/testproto/mock.go: -------------------------------------------------------------------------------- 1 | // Code generated by MockGen. DO NOT EDIT. 2 | // Source: github.com/conduitio/bwlimit/bwgrpc/testproto (interfaces: TestServiceServer) 3 | 4 | // Package testproto is a generated GoMock package. 5 | package testproto 6 | 7 | import ( 8 | context "context" 9 | reflect "reflect" 10 | 11 | gomock "github.com/golang/mock/gomock" 12 | ) 13 | 14 | // MockTestServiceServer is a mock of TestServiceServer interface. 15 | type MockTestServiceServer struct { 16 | ctrl *gomock.Controller 17 | recorder *MockTestServiceServerMockRecorder 18 | } 19 | 20 | // MockTestServiceServerMockRecorder is the mock recorder for MockTestServiceServer. 21 | type MockTestServiceServerMockRecorder struct { 22 | mock *MockTestServiceServer 23 | } 24 | 25 | // NewMockTestServiceServer creates a new mock instance. 26 | func NewMockTestServiceServer(ctrl *gomock.Controller) *MockTestServiceServer { 27 | mock := &MockTestServiceServer{ctrl: ctrl} 28 | mock.recorder = &MockTestServiceServerMockRecorder{mock} 29 | return mock 30 | } 31 | 32 | // EXPECT returns an object that allows the caller to indicate expected use. 33 | func (m *MockTestServiceServer) EXPECT() *MockTestServiceServerMockRecorder { 34 | return m.recorder 35 | } 36 | 37 | // TestRPC mocks base method. 38 | func (m *MockTestServiceServer) TestRPC(arg0 context.Context, arg1 *TestRequest) (*TestResponse, error) { 39 | m.ctrl.T.Helper() 40 | ret := m.ctrl.Call(m, "TestRPC", arg0, arg1) 41 | ret0, _ := ret[0].(*TestResponse) 42 | ret1, _ := ret[1].(error) 43 | return ret0, ret1 44 | } 45 | 46 | // TestRPC indicates an expected call of TestRPC. 47 | func (mr *MockTestServiceServerMockRecorder) TestRPC(arg0, arg1 interface{}) *gomock.Call { 48 | mr.mock.ctrl.T.Helper() 49 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TestRPC", reflect.TypeOf((*MockTestServiceServer)(nil).TestRPC), arg0, arg1) 50 | } 51 | 52 | // mustEmbedUnimplementedTestServiceServer mocks base method. 53 | func (m *MockTestServiceServer) mustEmbedUnimplementedTestServiceServer() { 54 | m.ctrl.T.Helper() 55 | m.ctrl.Call(m, "mustEmbedUnimplementedTestServiceServer") 56 | } 57 | 58 | // mustEmbedUnimplementedTestServiceServer indicates an expected call of mustEmbedUnimplementedTestServiceServer. 59 | func (mr *MockTestServiceServerMockRecorder) mustEmbedUnimplementedTestServiceServer() *gomock.Call { 60 | mr.mock.ctrl.T.Helper() 61 | return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "mustEmbedUnimplementedTestServiceServer", reflect.TypeOf((*MockTestServiceServer)(nil).mustEmbedUnimplementedTestServiceServer)) 62 | } 63 | -------------------------------------------------------------------------------- /bwgrpc/testproto/test.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. DO NOT EDIT. 2 | // versions: 3 | // protoc-gen-go v1.29.1 4 | // protoc (unknown) 5 | // source: test.proto 6 | 7 | package testproto 8 | 9 | import ( 10 | protoreflect "google.golang.org/protobuf/reflect/protoreflect" 11 | protoimpl "google.golang.org/protobuf/runtime/protoimpl" 12 | reflect "reflect" 13 | sync "sync" 14 | ) 15 | 16 | const ( 17 | // Verify that this generated code is sufficiently up-to-date. 18 | _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) 19 | // Verify that runtime/protoimpl is sufficiently up-to-date. 20 | _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) 21 | ) 22 | 23 | type TestRequest struct { 24 | state protoimpl.MessageState 25 | sizeCache protoimpl.SizeCache 26 | unknownFields protoimpl.UnknownFields 27 | 28 | Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` 29 | } 30 | 31 | func (x *TestRequest) Reset() { 32 | *x = TestRequest{} 33 | if protoimpl.UnsafeEnabled { 34 | mi := &file_test_proto_msgTypes[0] 35 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) 36 | ms.StoreMessageInfo(mi) 37 | } 38 | } 39 | 40 | func (x *TestRequest) String() string { 41 | return protoimpl.X.MessageStringOf(x) 42 | } 43 | 44 | func (*TestRequest) ProtoMessage() {} 45 | 46 | func (x *TestRequest) ProtoReflect() protoreflect.Message { 47 | mi := &file_test_proto_msgTypes[0] 48 | if protoimpl.UnsafeEnabled && x != nil { 49 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) 50 | if ms.LoadMessageInfo() == nil { 51 | ms.StoreMessageInfo(mi) 52 | } 53 | return ms 54 | } 55 | return mi.MessageOf(x) 56 | } 57 | 58 | // Deprecated: Use TestRequest.ProtoReflect.Descriptor instead. 59 | func (*TestRequest) Descriptor() ([]byte, []int) { 60 | return file_test_proto_rawDescGZIP(), []int{0} 61 | } 62 | 63 | func (x *TestRequest) GetId() string { 64 | if x != nil { 65 | return x.Id 66 | } 67 | return "" 68 | } 69 | 70 | type TestResponse struct { 71 | state protoimpl.MessageState 72 | sizeCache protoimpl.SizeCache 73 | unknownFields protoimpl.UnknownFields 74 | 75 | Code int32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"` 76 | } 77 | 78 | func (x *TestResponse) Reset() { 79 | *x = TestResponse{} 80 | if protoimpl.UnsafeEnabled { 81 | mi := &file_test_proto_msgTypes[1] 82 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) 83 | ms.StoreMessageInfo(mi) 84 | } 85 | } 86 | 87 | func (x *TestResponse) String() string { 88 | return protoimpl.X.MessageStringOf(x) 89 | } 90 | 91 | func (*TestResponse) ProtoMessage() {} 92 | 93 | func (x *TestResponse) ProtoReflect() protoreflect.Message { 94 | mi := &file_test_proto_msgTypes[1] 95 | if protoimpl.UnsafeEnabled && x != nil { 96 | ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) 97 | if ms.LoadMessageInfo() == nil { 98 | ms.StoreMessageInfo(mi) 99 | } 100 | return ms 101 | } 102 | return mi.MessageOf(x) 103 | } 104 | 105 | // Deprecated: Use TestResponse.ProtoReflect.Descriptor instead. 106 | func (*TestResponse) Descriptor() ([]byte, []int) { 107 | return file_test_proto_rawDescGZIP(), []int{1} 108 | } 109 | 110 | func (x *TestResponse) GetCode() int32 { 111 | if x != nil { 112 | return x.Code 113 | } 114 | return 0 115 | } 116 | 117 | var File_test_proto protoreflect.FileDescriptor 118 | 119 | var file_test_proto_rawDesc = []byte{ 120 | 0x0a, 0x0a, 0x74, 0x65, 0x73, 0x74, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x1d, 0x0a, 0x0b, 121 | 0x54, 0x65, 0x73, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 122 | 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x22, 0x22, 0x0a, 0x0c, 0x54, 123 | 0x65, 0x73, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x63, 124 | 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x32, 125 | 0x37, 0x0a, 0x0b, 0x54, 0x65, 0x73, 0x74, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, 0x65, 0x12, 0x28, 126 | 0x0a, 0x07, 0x54, 0x65, 0x73, 0x74, 0x52, 0x50, 0x43, 0x12, 0x0c, 0x2e, 0x54, 0x65, 0x73, 0x74, 127 | 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x0d, 0x2e, 0x54, 0x65, 0x73, 0x74, 0x52, 0x65, 128 | 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x42, 0x3c, 0x42, 0x09, 0x54, 0x65, 0x73, 0x74, 129 | 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x2d, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 130 | 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x6e, 0x64, 0x75, 0x69, 0x74, 0x69, 0x6f, 0x2f, 0x62, 0x77, 131 | 0x6c, 0x69, 0x6d, 0x69, 0x74, 0x2f, 0x62, 0x77, 0x67, 0x72, 0x70, 0x63, 0x2f, 0x74, 0x65, 0x73, 132 | 0x74, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, 133 | } 134 | 135 | var ( 136 | file_test_proto_rawDescOnce sync.Once 137 | file_test_proto_rawDescData = file_test_proto_rawDesc 138 | ) 139 | 140 | func file_test_proto_rawDescGZIP() []byte { 141 | file_test_proto_rawDescOnce.Do(func() { 142 | file_test_proto_rawDescData = protoimpl.X.CompressGZIP(file_test_proto_rawDescData) 143 | }) 144 | return file_test_proto_rawDescData 145 | } 146 | 147 | var file_test_proto_msgTypes = make([]protoimpl.MessageInfo, 2) 148 | var file_test_proto_goTypes = []interface{}{ 149 | (*TestRequest)(nil), // 0: TestRequest 150 | (*TestResponse)(nil), // 1: TestResponse 151 | } 152 | var file_test_proto_depIdxs = []int32{ 153 | 0, // 0: TestService.TestRPC:input_type -> TestRequest 154 | 1, // 1: TestService.TestRPC:output_type -> TestResponse 155 | 1, // [1:2] is the sub-list for method output_type 156 | 0, // [0:1] is the sub-list for method input_type 157 | 0, // [0:0] is the sub-list for extension type_name 158 | 0, // [0:0] is the sub-list for extension extendee 159 | 0, // [0:0] is the sub-list for field type_name 160 | } 161 | 162 | func init() { file_test_proto_init() } 163 | func file_test_proto_init() { 164 | if File_test_proto != nil { 165 | return 166 | } 167 | if !protoimpl.UnsafeEnabled { 168 | file_test_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { 169 | switch v := v.(*TestRequest); i { 170 | case 0: 171 | return &v.state 172 | case 1: 173 | return &v.sizeCache 174 | case 2: 175 | return &v.unknownFields 176 | default: 177 | return nil 178 | } 179 | } 180 | file_test_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { 181 | switch v := v.(*TestResponse); i { 182 | case 0: 183 | return &v.state 184 | case 1: 185 | return &v.sizeCache 186 | case 2: 187 | return &v.unknownFields 188 | default: 189 | return nil 190 | } 191 | } 192 | } 193 | type x struct{} 194 | out := protoimpl.TypeBuilder{ 195 | File: protoimpl.DescBuilder{ 196 | GoPackagePath: reflect.TypeOf(x{}).PkgPath(), 197 | RawDescriptor: file_test_proto_rawDesc, 198 | NumEnums: 0, 199 | NumMessages: 2, 200 | NumExtensions: 0, 201 | NumServices: 1, 202 | }, 203 | GoTypes: file_test_proto_goTypes, 204 | DependencyIndexes: file_test_proto_depIdxs, 205 | MessageInfos: file_test_proto_msgTypes, 206 | }.Build() 207 | File_test_proto = out.File 208 | file_test_proto_rawDesc = nil 209 | file_test_proto_goTypes = nil 210 | file_test_proto_depIdxs = nil 211 | } 212 | -------------------------------------------------------------------------------- /bwgrpc/testproto/test.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | message TestRequest { 4 | string id = 1; 5 | } 6 | 7 | message TestResponse { 8 | int32 code = 1; 9 | } 10 | 11 | service TestService { 12 | rpc TestRPC(TestRequest) returns (TestResponse) {}; 13 | } -------------------------------------------------------------------------------- /bwgrpc/testproto/test_grpc.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go-grpc. DO NOT EDIT. 2 | // versions: 3 | // - protoc-gen-go-grpc v1.3.0 4 | // - protoc (unknown) 5 | // source: test.proto 6 | 7 | package testproto 8 | 9 | import ( 10 | context "context" 11 | grpc "google.golang.org/grpc" 12 | codes "google.golang.org/grpc/codes" 13 | status "google.golang.org/grpc/status" 14 | ) 15 | 16 | // This is a compile-time assertion to ensure that this generated file 17 | // is compatible with the grpc package it is being compiled against. 18 | // Requires gRPC-Go v1.32.0 or later. 19 | const _ = grpc.SupportPackageIsVersion7 20 | 21 | const ( 22 | TestService_TestRPC_FullMethodName = "/TestService/TestRPC" 23 | ) 24 | 25 | // TestServiceClient is the client API for TestService service. 26 | // 27 | // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. 28 | type TestServiceClient interface { 29 | TestRPC(ctx context.Context, in *TestRequest, opts ...grpc.CallOption) (*TestResponse, error) 30 | } 31 | 32 | type testServiceClient struct { 33 | cc grpc.ClientConnInterface 34 | } 35 | 36 | func NewTestServiceClient(cc grpc.ClientConnInterface) TestServiceClient { 37 | return &testServiceClient{cc} 38 | } 39 | 40 | func (c *testServiceClient) TestRPC(ctx context.Context, in *TestRequest, opts ...grpc.CallOption) (*TestResponse, error) { 41 | out := new(TestResponse) 42 | err := c.cc.Invoke(ctx, TestService_TestRPC_FullMethodName, in, out, opts...) 43 | if err != nil { 44 | return nil, err 45 | } 46 | return out, nil 47 | } 48 | 49 | // TestServiceServer is the server API for TestService service. 50 | // All implementations must embed UnimplementedTestServiceServer 51 | // for forward compatibility 52 | type TestServiceServer interface { 53 | TestRPC(context.Context, *TestRequest) (*TestResponse, error) 54 | mustEmbedUnimplementedTestServiceServer() 55 | } 56 | 57 | // UnimplementedTestServiceServer must be embedded to have forward compatible implementations. 58 | type UnimplementedTestServiceServer struct { 59 | } 60 | 61 | func (UnimplementedTestServiceServer) TestRPC(context.Context, *TestRequest) (*TestResponse, error) { 62 | return nil, status.Errorf(codes.Unimplemented, "method TestRPC not implemented") 63 | } 64 | func (UnimplementedTestServiceServer) mustEmbedUnimplementedTestServiceServer() {} 65 | 66 | // UnsafeTestServiceServer may be embedded to opt out of forward compatibility for this service. 67 | // Use of this interface is not recommended, as added methods to TestServiceServer will 68 | // result in compilation errors. 69 | type UnsafeTestServiceServer interface { 70 | mustEmbedUnimplementedTestServiceServer() 71 | } 72 | 73 | func RegisterTestServiceServer(s grpc.ServiceRegistrar, srv TestServiceServer) { 74 | s.RegisterService(&TestService_ServiceDesc, srv) 75 | } 76 | 77 | func _TestService_TestRPC_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 78 | in := new(TestRequest) 79 | if err := dec(in); err != nil { 80 | return nil, err 81 | } 82 | if interceptor == nil { 83 | return srv.(TestServiceServer).TestRPC(ctx, in) 84 | } 85 | info := &grpc.UnaryServerInfo{ 86 | Server: srv, 87 | FullMethod: TestService_TestRPC_FullMethodName, 88 | } 89 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 90 | return srv.(TestServiceServer).TestRPC(ctx, req.(*TestRequest)) 91 | } 92 | return interceptor(ctx, in, info, handler) 93 | } 94 | 95 | // TestService_ServiceDesc is the grpc.ServiceDesc for TestService service. 96 | // It's only intended for direct use with grpc.RegisterService, 97 | // and not to be introspected or modified (even as a copy) 98 | var TestService_ServiceDesc = grpc.ServiceDesc{ 99 | ServiceName: "TestService", 100 | HandlerType: (*TestServiceServer)(nil), 101 | Methods: []grpc.MethodDesc{ 102 | { 103 | MethodName: "TestRPC", 104 | Handler: _TestService_TestRPC_Handler, 105 | }, 106 | }, 107 | Streams: []grpc.StreamDesc{}, 108 | Metadata: "test.proto", 109 | } 110 | -------------------------------------------------------------------------------- /byte.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Meroxa, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package bwlimit 16 | 17 | // Byte represents a number of bytes as an int. 18 | type Byte int 19 | 20 | // Base-2 byte units. 21 | const ( 22 | Kibibyte Byte = 1024 23 | KiB = Kibibyte 24 | Mebibyte = Kibibyte * 1024 25 | MiB = Mebibyte 26 | Gibibyte = Mebibyte * 1024 27 | GiB = Gibibyte 28 | ) 29 | 30 | // SI base-10 byte units. 31 | const ( 32 | Kilobyte Byte = 1000 33 | KB = Kilobyte 34 | Megabyte = Kilobyte * 1000 35 | MB = Megabyte 36 | Gigabyte = Megabyte * 1000 37 | GB = Gigabyte 38 | ) 39 | -------------------------------------------------------------------------------- /examples/client/main.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Meroxa, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package main 16 | 17 | import ( 18 | "crypto/rand" 19 | "io" 20 | "log" 21 | "net" 22 | "net/http" 23 | "time" 24 | 25 | "github.com/conduitio/bwlimit" 26 | ) 27 | 28 | const ( 29 | addr = "http://localhost:8080/echo" 30 | requestSize = 20 * bwlimit.KB 31 | 32 | readLimit = bwlimit.MiB // read limit is 1048576 B/s 33 | writeLimit = 4 * bwlimit.KB // write limit is 4000 B/s 34 | ) 35 | 36 | func main() { 37 | // change dialer in the default transport to use a bandwidth limit 38 | dialer := bwlimit.NewDialer(&net.Dialer{ 39 | Timeout: 30 * time.Second, 40 | KeepAlive: 30 * time.Second, 41 | }, writeLimit, readLimit) 42 | http.DefaultTransport.(*http.Transport).DialContext = dialer.DialContext 43 | 44 | body := randomBody(int64(requestSize)) 45 | resp, err := send(body) 46 | if err != nil { 47 | log.Fatalf("failed to send request: %v", err) 48 | } 49 | 50 | err = read(resp) 51 | if err != nil { 52 | log.Fatalf("failed to read response: %v", err) 53 | } 54 | } 55 | 56 | func send(body io.Reader) (*http.Response, error) { 57 | req, err := http.NewRequest("POST", addr, body) 58 | if err != nil { 59 | return nil, err 60 | } 61 | 62 | bandwidth := measureBandwidth("send") 63 | resp, err := http.DefaultClient.Do(req) 64 | bandwidth(int(requestSize)) 65 | return resp, err 66 | } 67 | 68 | func read(resp *http.Response) error { 69 | bandwidth := measureBandwidth("read") 70 | body, err := io.ReadAll(resp.Body) 71 | bandwidth(len(body)) 72 | return err 73 | } 74 | 75 | func measureBandwidth(operation string) func(count int) { 76 | start := time.Now() 77 | return func(count int) { 78 | elapsed := time.Since(start) + time.Second // add 1 second to display the true rate 79 | log.Printf("%v bandwidth: %.0f B/s", operation, float64(count)/elapsed.Seconds()) 80 | } 81 | } 82 | 83 | func randomBody(size int64) io.Reader { 84 | pr, pw := io.Pipe() 85 | go func() { 86 | random := io.LimitReader(rand.Reader, size) 87 | _, err := io.Copy(pw, random) 88 | _ = pw.CloseWithError(err) 89 | }() 90 | return pr 91 | } 92 | -------------------------------------------------------------------------------- /examples/server/main.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Meroxa, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package main 16 | 17 | import ( 18 | "io" 19 | "log" 20 | "net" 21 | "net/http" 22 | "strconv" 23 | "time" 24 | 25 | "github.com/conduitio/bwlimit" 26 | ) 27 | 28 | const ( 29 | addr = ":8080" 30 | echoEndpoint = "/echo" 31 | 32 | readLimit = bwlimit.MiB // read limit is 1048576 B/s 33 | writeLimit = 4 * bwlimit.KB // write limit is 4000 B/s 34 | ) 35 | 36 | func main() { 37 | ln, err := net.Listen("tcp", addr) 38 | if err != nil { 39 | log.Fatal(err) 40 | } 41 | // limit the listener bandwidth 42 | ln = bwlimit.NewListener(ln, writeLimit, readLimit) 43 | defer ln.Close() 44 | 45 | http.Handle(echoEndpoint, http.HandlerFunc(echoHandler)) 46 | srv := &http.Server{Addr: addr} 47 | log.Fatal(srv.Serve(ln)) 48 | } 49 | 50 | func echoHandler(w http.ResponseWriter, r *http.Request) { 51 | b, err := read(r) 52 | if err != nil { 53 | log.Printf("failed to read request: %v", err) 54 | return 55 | } 56 | 57 | err = write(w, b) 58 | if err != nil { 59 | log.Printf("failed to write response: %v", err) 60 | } 61 | } 62 | 63 | func read(r *http.Request) ([]byte, error) { 64 | defer r.Body.Close() 65 | bandwidth := measureBandwidth("read") 66 | body, err := io.ReadAll(r.Body) 67 | bandwidth(len(body)) 68 | return body, err 69 | } 70 | 71 | func write(w http.ResponseWriter, b []byte) error { 72 | w.Header().Set("Content-Length", strconv.Itoa(len(b))) 73 | bandwidth := measureBandwidth("write") 74 | n, err := w.Write(b) 75 | bandwidth(n) 76 | return err 77 | } 78 | 79 | func measureBandwidth(operation string) func(count int) { 80 | start := time.Now() 81 | return func(count int) { 82 | elapsed := time.Since(start) + time.Second // add 1 second to display the true rate 83 | log.Printf("%v bandwidth: %.0f B/s", operation, float64(count)/elapsed.Seconds()) 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/conduitio/bwlimit 2 | 3 | go 1.23.0 4 | 5 | require golang.org/x/time v0.11.0 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0= 2 | golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= 3 | -------------------------------------------------------------------------------- /io.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Meroxa, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package bwlimit 16 | 17 | import ( 18 | "context" 19 | "errors" 20 | "io" 21 | "math" 22 | "os" 23 | "time" 24 | 25 | "golang.org/x/time/rate" 26 | ) 27 | 28 | // Reader wraps an io.Reader and imposes a bandwidth limit on calls to Read. 29 | type Reader struct { 30 | io.Reader 31 | 32 | limiter *rate.Limiter 33 | reservation *rate.Reservation 34 | deadline time.Time 35 | } 36 | 37 | // NewReader wraps an existing io.Reader and returns a Reader that limits the 38 | // bandwidth of reads. 39 | // A zero value for bytesPerSecond means that Read will not have a bandwidth 40 | // limit. 41 | func NewReader(r io.Reader, bytesPerSecond Byte) *Reader { 42 | bwr := &Reader{ 43 | Reader: r, 44 | limiter: rate.NewLimiter(toLimit(bytesPerSecond), toBurst(bytesPerSecond)), 45 | } 46 | return bwr 47 | } 48 | 49 | // Deadline returns the configured deadline (see SetDeadline). 50 | func (r *Reader) Deadline() time.Time { 51 | return r.deadline 52 | } 53 | 54 | // SetDeadline sets the read deadline associated with the reader. 55 | // 56 | // A deadline is an absolute time after which Read fails instead of blocking. 57 | // The deadline applies to all future and pending calls to Read, not just the 58 | // immediately following call to Read. After a deadline has been exceeded, the 59 | // reader can be refreshed by setting a deadline in the future. 60 | // 61 | // If the deadline is exceeded a call to Read will return an error that wraps 62 | // os.ErrDeadlineExceeded. This can be tested using 63 | // errors.Is(err, os.ErrDeadlineExceeded). 64 | // 65 | // An idle timeout can be implemented by repeatedly extending the deadline after 66 | // successful Read calls. 67 | // 68 | // A zero value for t means that calls to Read will not time out. 69 | func (r *Reader) SetDeadline(t time.Time) { 70 | r.deadline = t 71 | } 72 | 73 | // BandwidthLimit returns the current bandwidth limit. 74 | func (r *Reader) BandwidthLimit() Byte { 75 | return Byte(r.limiter.Limit()) 76 | } 77 | 78 | // SetBandwidthLimit sets the bandwidth limit for future Read calls and 79 | // any currently-blocked Read call. 80 | // A zero value for bytesPerSecond means the bandwidth limit is removed. 81 | func (r *Reader) SetBandwidthLimit(bytesPerSecond Byte) { 82 | r.limiter.SetLimit(toLimit(bytesPerSecond)) 83 | r.limiter.SetBurst(toBurst(bytesPerSecond)) 84 | } 85 | 86 | // Close forwards the call to the wrapped io.Reader if it implements io.Closer, 87 | // otherwise it is a noop. 88 | func (r *Reader) Close() error { 89 | if rc, ok := r.Reader.(io.Closer); ok { 90 | return rc.Close() 91 | } 92 | return nil 93 | } 94 | 95 | // Read reads up to len(p) bytes into p. It returns the number of bytes 96 | // read (0 <= n <= len(p)) and any error encountered. 97 | // 98 | // Read will limit the speed of the reads if a bandwidth limit is configured. If 99 | // the size of p is bigger than the rate of bytes per second, reads will be 100 | // split into smaller chunks. 101 | // Note that since it's not known in advance how many bytes will be read, the 102 | // bandwidth can burst up to 2x of the configured limit when reading the first 2 103 | // chunks. 104 | func (r *Reader) Read(p []byte) (n int, err error) { 105 | if r.limiter.Limit() == rate.Inf { 106 | // no limit, just pass the call through to the connection 107 | return r.Reader.Read(p) 108 | } 109 | 110 | ctx := context.Background() 111 | if !r.deadline.IsZero() { 112 | var cancel context.CancelFunc 113 | ctx, cancel = context.WithDeadline(ctx, r.deadline) 114 | defer cancel() 115 | } 116 | 117 | for _, chunk := range split(p, int(r.limiter.Limit())) { 118 | bytesRead, err := r.readWithRateLimit(ctx, chunk) 119 | n += bytesRead 120 | if err != nil { 121 | return n, err 122 | } 123 | if bytesRead < len(p) { 124 | // we did not read a whole chunk, we need to return and let the 125 | // caller call Read again, so we split the bytes again in new chunks 126 | return n, nil 127 | } 128 | } 129 | return n, nil 130 | } 131 | 132 | // readWithRateLimit will delay the read if needed to match the configured 133 | // bandwidth limit. 134 | func (r *Reader) readWithRateLimit(ctx context.Context, p []byte) (int, error) { 135 | // we first need to delay the read if there was a read that happened before 136 | if r.reservation != nil && r.reservation.OK() { 137 | err := r.wait(ctx, r.reservation.Delay()) 138 | if err != nil { 139 | if errors.Is(err, context.DeadlineExceeded) { 140 | // according to net.Conn the error should be os.ErrDeadlineExceeded 141 | err = os.ErrDeadlineExceeded 142 | } 143 | return 0, err 144 | } 145 | r.reservation = nil 146 | } 147 | 148 | at := time.Now() 149 | n, err := r.Reader.Read(p) 150 | if n > 0 { 151 | // reserve the number of actually read bytes to delay future reads 152 | r.reservation = r.limiter.ReserveN(at, n) 153 | } 154 | return n, err 155 | } 156 | 157 | func (r *Reader) wait(ctx context.Context, d time.Duration) error { 158 | if d == 0 { 159 | return nil 160 | } 161 | timer := time.NewTimer(d) 162 | defer timer.Stop() 163 | select { 164 | case <-timer.C: 165 | return nil 166 | case <-ctx.Done(): 167 | return ctx.Err() 168 | } 169 | } 170 | 171 | // Writer wraps an io.Writer and imposes a bandwidth limit on calls to Write. 172 | type Writer struct { 173 | io.Writer 174 | 175 | limiter *rate.Limiter 176 | deadline time.Time 177 | } 178 | 179 | // NewWriter wraps an existing io.Writer and returns a Writer that limits the 180 | // bandwidth of writes. 181 | // A zero value for bytesPerSecond means that Write will not have a bandwidth 182 | // limit. 183 | func NewWriter(w io.Writer, bytesPerSecond Byte) *Writer { 184 | bwr := &Writer{ 185 | Writer: w, 186 | limiter: rate.NewLimiter(toLimit(bytesPerSecond), toBurst(bytesPerSecond)), 187 | } 188 | return bwr 189 | } 190 | 191 | // Deadline returns the configured deadline (see SetDeadline). 192 | func (w *Writer) Deadline() time.Time { 193 | return w.deadline 194 | } 195 | 196 | // SetDeadline sets the write deadline associated with the writer. 197 | // 198 | // A deadline is an absolute time after which Write fails instead of blocking. 199 | // The deadline applies to all future and pending calls to Write, not just the 200 | // immediately following call to Write. After a deadline has been exceeded, the 201 | // writer can be refreshed by setting a deadline in the future. 202 | // 203 | // If the deadline is exceeded a call to Write will return an error that wraps 204 | // os.ErrDeadlineExceeded. This can be tested using 205 | // errors.Is(err, os.ErrDeadlineExceeded). 206 | // 207 | // An idle timeout can be implemented by repeatedly extending the deadline after 208 | // successful Write calls. 209 | // 210 | // A zero value for t means that calls to Write will not time out. 211 | func (w *Writer) SetDeadline(t time.Time) { 212 | w.deadline = t 213 | } 214 | 215 | // BandwidthLimit returns the current bandwidth limit. 216 | func (w *Writer) BandwidthLimit() Byte { 217 | return Byte(w.limiter.Limit()) 218 | } 219 | 220 | // SetBandwidthLimit sets the bandwidth limit for future Write calls and 221 | // any currently-blocked Write call. 222 | // A zero value for bytesPerSecond means the bandwidth limit is removed. 223 | func (w *Writer) SetBandwidthLimit(bytesPerSecond Byte) { 224 | w.limiter.SetLimit(toLimit(bytesPerSecond)) 225 | w.limiter.SetBurst(toBurst(bytesPerSecond)) 226 | } 227 | 228 | // Close forwards the call to the wrapped io.Writer if it implements io.Closer, 229 | // otherwise it is a noop. 230 | func (w *Writer) Close() error { 231 | if wc, ok := w.Writer.(io.Closer); ok { 232 | return wc.Close() 233 | } 234 | return nil 235 | } 236 | 237 | // Write writes len(p) bytes from p to the underlying data stream. 238 | // It returns the number of bytes written from p (0 <= n <= len(p)) 239 | // and any error encountered that caused the write to stop early. 240 | // 241 | // Write will limit the speed of the writes if a bandwidth limit is configured. 242 | // If the size of p is bigger than the rate of bytes per second, writes will be 243 | // split into smaller chunks. 244 | func (w *Writer) Write(p []byte) (n int, err error) { 245 | if w.limiter.Limit() == rate.Inf { 246 | // no limit, just pass the call through to the connection 247 | return w.Writer.Write(p) 248 | } 249 | 250 | ctx := context.Background() 251 | if !w.deadline.IsZero() { 252 | var cancel context.CancelFunc 253 | ctx, cancel = context.WithDeadline(ctx, w.deadline) 254 | defer cancel() 255 | } 256 | 257 | for _, chunk := range split(p, int(w.limiter.Limit())) { 258 | bytesWritten, err := w.writeWithRateLimit(ctx, chunk) 259 | n += bytesWritten 260 | if err != nil { 261 | return n, err 262 | } 263 | } 264 | return n, nil 265 | } 266 | 267 | // writeWithRateLimit will delay the write if needed to match the configured 268 | // bandwidth limit. 269 | func (w *Writer) writeWithRateLimit(ctx context.Context, b []byte) (int, error) { 270 | err := w.limiter.WaitN(ctx, len(b)) 271 | if err != nil { 272 | if errors.Is(err, context.DeadlineExceeded) { 273 | // according to net.Conn the error should be os.ErrDeadlineExceeded 274 | err = os.ErrDeadlineExceeded 275 | } 276 | return 0, err 277 | } 278 | return w.Writer.Write(b) 279 | } 280 | 281 | // split takes a byte slice and splits it into chunks of size maxSize. If b is 282 | // not divisible by maxSize, the last chunk will be smaller. 283 | func split(b []byte, maxSize int) [][]byte { 284 | var end int 285 | out := make([][]byte, ((len(b)-1)/maxSize)+1) 286 | for i := range out { 287 | start := end 288 | end += maxSize 289 | if end > len(b) { 290 | end = len(b) 291 | } 292 | out[i] = b[start:end] 293 | } 294 | return out 295 | } 296 | 297 | func toLimit(b Byte) rate.Limit { 298 | if b <= 0 { 299 | return rate.Inf 300 | } 301 | return rate.Limit(b) 302 | } 303 | 304 | func toBurst(b Byte) int { 305 | if b <= 0 { 306 | return math.MaxInt 307 | } 308 | return int(b) 309 | } 310 | -------------------------------------------------------------------------------- /io_test.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Meroxa, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package bwlimit 16 | 17 | import ( 18 | "crypto/rand" 19 | "fmt" 20 | "io" 21 | "testing" 22 | "time" 23 | ) 24 | 25 | // epsilon is the allowed difference between the expected and actual delay 26 | var epsilon time.Duration 27 | 28 | func init() { 29 | // we measure how long it takes to read 10 bytes and calculate the 30 | // acceptable epsilon in read times when limiting the bandwidth 31 | r := randomReader(10) 32 | start := time.Now() 33 | _, err := r.Read(make([]byte, 2)) 34 | epsilon = time.Millisecond + (time.Since(start) * 20) 35 | if err != nil { 36 | panic(fmt.Errorf("error reading: %v", err)) 37 | } 38 | } 39 | 40 | func randomReader(size int64) io.Reader { 41 | pr, pw := io.Pipe() 42 | go func() { 43 | random := io.LimitReader(rand.Reader, size) 44 | _, err := io.Copy(pw, random) 45 | _ = pw.CloseWithError(err) 46 | }() 47 | return pr 48 | } 49 | 50 | func TestReader_Read(t *testing.T) { 51 | t.Logf("epsilon: %v", epsilon) 52 | 53 | testCases := []struct { 54 | byteCount int64 55 | bytesPerSecond Byte 56 | wantDelay time.Duration 57 | }{{ 58 | byteCount: 1, 59 | bytesPerSecond: 0, 60 | wantDelay: 0, // no delay 61 | }, { 62 | byteCount: 1, 63 | bytesPerSecond: 1, 64 | wantDelay: 0, // no delay 65 | }, { 66 | byteCount: 4, 67 | bytesPerSecond: 2, 68 | // expected delay is 1 second: 69 | // - first read happens instantly, returns 2 bytes 70 | // - second read happens instantly (reservation contains no delay), returns 2 bytes 71 | // - third read is delayed by 1s (reservation contains delay), returns EOF 72 | wantDelay: 1 * time.Second, 73 | }, { 74 | byteCount: 102, 75 | bytesPerSecond: 100, 76 | // expected delay is 20 milliseconds: 77 | // - first read happens instantly, returns 100 bytes 78 | // - second read happens instantly (reservation contains no delay), returns 2 bytes 79 | // - third read is delayed by 20ms (2/100 of a second, as reservation contains 2 tokens), returns EOF 80 | wantDelay: 20 * time.Millisecond, 81 | }, { 82 | byteCount: 103, 83 | bytesPerSecond: 100, 84 | // expected delay is 30 milliseconds: 85 | // - first read happens instantly, returns 100 bytes 86 | // - second read happens instantly (reservation contains no delay), returns 3 bytes 87 | // - third read is delayed by 30ms (3/100 of a second, as reservation contains 3 tokens), returns EOF 88 | wantDelay: 30 * time.Millisecond, 89 | }} 90 | 91 | for _, tc := range testCases { 92 | tc := tc // assign to local var as test cases run in parallel 93 | t.Run(fmt.Sprintf("%d byte/%d bps", tc.byteCount, tc.bytesPerSecond), func(t *testing.T) { 94 | // these tests are blocking, run them in parallel 95 | t.Parallel() 96 | 97 | r := NewReader(randomReader(tc.byteCount), tc.bytesPerSecond) 98 | start := time.Now() 99 | got, err := io.ReadAll(r) 100 | gotDelay := time.Since(start) 101 | if err != nil { 102 | t.Fatalf("error reading: %v", err) 103 | } 104 | 105 | if len(got) != int(tc.byteCount) { 106 | t.Fatalf("expected %d bytes, got %d", tc.byteCount, len(got)) 107 | } 108 | 109 | gotDiff := tc.wantDelay - gotDelay 110 | if gotDiff < 0 { 111 | gotDiff = -gotDiff 112 | } 113 | 114 | if gotDiff > epsilon { 115 | t.Fatalf("expected a maximum delay of %v, got %v, allowed epsilon of %v exceeded", tc.wantDelay, gotDelay, epsilon) 116 | } 117 | }) 118 | } 119 | } 120 | 121 | func TestWriter_Write(t *testing.T) { 122 | t.Logf("epsilon: %v", epsilon) 123 | 124 | testCases := []struct { 125 | byteCount int64 126 | bytesPerSecond Byte 127 | wantDelay time.Duration 128 | }{{ 129 | byteCount: 1, 130 | bytesPerSecond: 0, 131 | wantDelay: 0, // no delay 132 | }, { 133 | byteCount: 1, 134 | bytesPerSecond: 1, 135 | wantDelay: 0, // no delay 136 | }, { 137 | byteCount: 4, 138 | bytesPerSecond: 2, 139 | // expected delay is 1 second: 140 | // - first write happens instantly, writes 2 bytes 141 | // - second write is delayed by 1s, writes 2 bytes 142 | wantDelay: 1 * time.Second, 143 | }, { 144 | byteCount: 102, 145 | bytesPerSecond: 100, 146 | // expected delay is 20 milliseconds: 147 | // - first write happens instantly, writes 100 bytes 148 | // - second write is delayed by 20ms (2/100 of a second to reserve 2 tokens), writes 2 bytes 149 | wantDelay: 20 * time.Millisecond, 150 | }, { 151 | byteCount: 103, 152 | bytesPerSecond: 100, 153 | // expected delay is 30 milliseconds: 154 | // - first write happens instantly, writes 100 bytes 155 | // - second write is delayed by 30ms (3/100 of a second to reserve 3 tokens), writes 3 bytes 156 | wantDelay: 30 * time.Millisecond, 157 | }} 158 | 159 | for _, tc := range testCases { 160 | tc := tc // assign to local var as test cases run in parallel 161 | t.Run(fmt.Sprintf("%d byte/%d bps", tc.byteCount, tc.bytesPerSecond), func(t *testing.T) { 162 | // these tests are blocking, run them in parallel 163 | t.Parallel() 164 | 165 | w := NewWriter(io.Discard, tc.bytesPerSecond) 166 | start := time.Now() 167 | n, err := io.Copy(w, randomReader(tc.byteCount)) 168 | gotDelay := time.Since(start) 169 | if err != nil { 170 | t.Fatalf("error reading: %v", err) 171 | } 172 | 173 | if n != tc.byteCount { 174 | t.Fatalf("expected %d bytes, got %d", tc.byteCount, n) 175 | } 176 | 177 | gotDiff := tc.wantDelay - gotDelay 178 | if gotDiff < 0 { 179 | gotDiff = -gotDiff 180 | } 181 | 182 | if gotDiff > epsilon { 183 | t.Fatalf("expected a maximum delay of %v, got %v, allowed epsilon of %v exceeded", tc.wantDelay, gotDelay, epsilon) 184 | } 185 | }) 186 | } 187 | } 188 | -------------------------------------------------------------------------------- /net.go: -------------------------------------------------------------------------------- 1 | // Copyright © 2023 Meroxa, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package bwlimit 16 | 17 | import ( 18 | "context" 19 | "net" 20 | "time" 21 | ) 22 | 23 | // Conn is a net.Conn connection that limits the bandwidth of writes and reads. 24 | type Conn struct { 25 | net.Conn 26 | 27 | reader *Reader 28 | writer *Writer 29 | } 30 | 31 | // NewConn wraps an existing net.Conn and returns a Conn that limits the 32 | // bandwidth of writes and reads. 33 | // A zero value for writeLimitPerSecond or readLimitPerSecond means the 34 | // corresponding action will not have a bandwidth limit. 35 | func NewConn(conn net.Conn, writeLimitPerSecond, readLimitPerSecond Byte) *Conn { 36 | bwconn := &Conn{ 37 | Conn: conn, 38 | reader: NewReader(conn, readLimitPerSecond), 39 | writer: NewWriter(conn, writeLimitPerSecond), 40 | } 41 | return bwconn 42 | } 43 | 44 | // Write writes data to the connection. 45 | // Write can be made to time out and return an error after a fixed 46 | // time limit; see SetDeadline and SetWriteDeadline. 47 | // Write will limit the connection bandwidth if a limit is configured. If the 48 | // size of b is bigger than the rate of bytes per second, writes will be split 49 | // into smaller chunks. 50 | func (c *Conn) Write(b []byte) (n int, err error) { 51 | return c.writer.Write(b) 52 | } 53 | 54 | // Read reads data from the connection. 55 | // Read can be made to time out and return an error after a fixed 56 | // time limit; see SetDeadline and SetReadDeadline. 57 | // Read will limit the connection bandwidth if a limit is configured. If the 58 | // size of b is bigger than the rate of bytes per second, reads will be split 59 | // into smaller chunks. 60 | // Note that since it's not known in advance how many bytes will be read, the 61 | // bandwidth can burst up to 2x of the configured limit when reading the first 2 62 | // chunks. 63 | func (c *Conn) Read(b []byte) (n int, err error) { 64 | return c.reader.Read(b) 65 | } 66 | 67 | // SetDeadline sets the read and write deadlines associated 68 | // with the connection. It is equivalent to calling both 69 | // SetReadDeadline and SetWriteDeadline. 70 | // 71 | // A deadline is an absolute time after which I/O operations 72 | // fail instead of blocking. The deadline applies to all future 73 | // and pending I/O, not just the immediately following call to 74 | // Read or Write. After a deadline has been exceeded, the 75 | // connection can be refreshed by setting a deadline in the future. 76 | // 77 | // If the deadline is exceeded a call to Read or Write or to other 78 | // I/O methods will return an error that wraps os.ErrDeadlineExceeded. 79 | // This can be tested using errors.Is(err, os.ErrDeadlineExceeded). 80 | // The error's Timeout method will return true, but note that there 81 | // are other possible errors for which the Timeout method will 82 | // return true even if the deadline has not been exceeded. 83 | // 84 | // An idle timeout can be implemented by repeatedly extending 85 | // the deadline after successful Read or Write calls. 86 | // 87 | // A zero value for t means I/O operations will not time out. 88 | func (c *Conn) SetDeadline(t time.Time) error { 89 | err := c.Conn.SetDeadline(t) 90 | if err == nil { 91 | c.writer.SetDeadline(t) 92 | c.reader.SetDeadline(t) 93 | } 94 | return err 95 | } 96 | 97 | // SetWriteDeadline sets the deadline for future Write calls 98 | // and any currently-blocked Write call. 99 | // Even if write times out, it may return n > 0, indicating that 100 | // some of the data was successfully written. 101 | // A zero value for t means Write will not time out. 102 | func (c *Conn) SetWriteDeadline(t time.Time) error { 103 | err := c.Conn.SetWriteDeadline(t) 104 | if err == nil { 105 | c.writer.SetDeadline(t) 106 | } 107 | return err 108 | } 109 | 110 | // SetReadDeadline sets the deadline for future Read calls 111 | // and any currently-blocked Read call. 112 | // A zero value for t means Read will not time out. 113 | func (c *Conn) SetReadDeadline(t time.Time) error { 114 | err := c.Conn.SetReadDeadline(t) 115 | if err == nil { 116 | c.reader.SetDeadline(t) 117 | } 118 | return err 119 | } 120 | 121 | // SetWriteBandwidthLimit sets the bandwidth limit for future Write calls and 122 | // any currently-blocked Write call. 123 | // A zero value for bytesPerSecond means the bandwidth limit is removed. 124 | func (c *Conn) SetWriteBandwidthLimit(bytesPerSecond Byte) { 125 | c.writer.SetBandwidthLimit(bytesPerSecond) 126 | } 127 | 128 | // SetReadBandwidthLimit sets the bandwidth limit for future Read calls and any 129 | // currently-blocked Read call. 130 | // A zero value for bytesPerSecond means the bandwidth limit is removed. 131 | func (c *Conn) SetReadBandwidthLimit(bytesPerSecond Byte) { 132 | c.reader.SetBandwidthLimit(bytesPerSecond) 133 | } 134 | 135 | // SetBandwidthLimit sets the read and write bandwidth limits associated with 136 | // the connection. It is equivalent to calling both SetReadBandwidthLimit and 137 | // SetWriteBandwidthLimit. 138 | func (c *Conn) SetBandwidthLimit(bytesPerSecond Byte) { 139 | c.writer.SetBandwidthLimit(bytesPerSecond) 140 | c.reader.SetBandwidthLimit(bytesPerSecond) 141 | } 142 | 143 | // WriteBandwidthLimit returns the current write bandwidth limit. 144 | func (c *Conn) WriteBandwidthLimit() Byte { 145 | return c.writer.BandwidthLimit() 146 | } 147 | 148 | // ReadBandwidthLimit returns the current read bandwidth limit. 149 | func (c *Conn) ReadBandwidthLimit() Byte { 150 | return c.reader.BandwidthLimit() 151 | } 152 | 153 | // Listener is a net.Listener that limits the bandwidth of the connections it 154 | // creates. 155 | type Listener struct { 156 | net.Listener 157 | 158 | writeBytesPerSecond Byte 159 | readBytesPerSecond Byte 160 | } 161 | 162 | // NewListener wraps an existing net.Listener and returns a Listener that limits 163 | // the bandwidth of the connections it creates. 164 | // A zero value for writeLimitPerSecond or readLimitPerSecond means the 165 | // corresponding action will not have a bandwidth limit. 166 | func NewListener(lis net.Listener, writeLimitPerSecond, readLimitPerSecond Byte) *Listener { 167 | bwlis := &Listener{Listener: lis} 168 | bwlis.SetWriteBandwidthLimit(writeLimitPerSecond) 169 | bwlis.SetReadBandwidthLimit(readLimitPerSecond) 170 | return bwlis 171 | } 172 | 173 | // Accept waits for and returns the next connection to the listener. 174 | // It returns a connection with a configured bandwidth limit. Each connection 175 | // tracks its own bandwidth. 176 | func (l *Listener) Accept() (net.Conn, error) { 177 | conn, err := l.Listener.Accept() 178 | if conn != nil { 179 | conn = NewConn(conn, l.writeBytesPerSecond, l.readBytesPerSecond) 180 | } 181 | return conn, err 182 | } 183 | 184 | // WriteBandwidthLimit returns the current write bandwidth limit. 185 | func (l *Listener) WriteBandwidthLimit() Byte { 186 | return l.writeBytesPerSecond 187 | } 188 | 189 | // ReadBandwidthLimit returns the current read bandwidth limit. 190 | func (l *Listener) ReadBandwidthLimit() Byte { 191 | return l.readBytesPerSecond 192 | } 193 | 194 | // SetWriteBandwidthLimit sets the bandwidth limit for writes on future 195 | // connections opened in Accept. It has no effect on already opened connections. 196 | // A zero value for bytesPerSecond means the bandwidth limit is removed. 197 | func (l *Listener) SetWriteBandwidthLimit(bytesPerSecond Byte) { 198 | if bytesPerSecond <= 0 { 199 | l.writeBytesPerSecond = 0 200 | return 201 | } 202 | l.writeBytesPerSecond = bytesPerSecond 203 | } 204 | 205 | // SetReadBandwidthLimit sets the bandwidth limit for reads on future 206 | // connections opened in Accept. It has no effect on already opened connections. 207 | // A zero value for bytesPerSecond means the bandwidth limit is removed. 208 | func (l *Listener) SetReadBandwidthLimit(bytesPerSecond Byte) { 209 | if bytesPerSecond <= 0 { 210 | l.readBytesPerSecond = 0 211 | return 212 | } 213 | l.readBytesPerSecond = bytesPerSecond 214 | } 215 | 216 | // Dialer is a net.Dialer that limits the bandwidth of the connections it 217 | // creates. 218 | type Dialer struct { 219 | *net.Dialer 220 | 221 | writeBytesPerSecond Byte 222 | readBytesPerSecond Byte 223 | } 224 | 225 | // NewDialer wraps an existing net.Dialer and returns a Dialer that limits 226 | // the bandwidth of the connections it creates. 227 | // A zero value for writeLimitPerSecond or readLimitPerSecond means the 228 | // corresponding action will not have a bandwidth limit. 229 | func NewDialer(d *net.Dialer, writeLimitPerSecond, readLimitPerSecond Byte) *Dialer { 230 | bwd := &Dialer{Dialer: d} 231 | bwd.SetWriteBandwidthLimit(writeLimitPerSecond) 232 | bwd.SetReadBandwidthLimit(readLimitPerSecond) 233 | return bwd 234 | } 235 | 236 | // Dial connects to the address on the named network. It returns a connection 237 | // with the configured bandwidth limits. Each connection tracks its own 238 | // bandwidth. 239 | func (d *Dialer) Dial(network, address string) (net.Conn, error) { 240 | conn, err := d.Dialer.Dial(network, address) 241 | if conn != nil { 242 | conn = NewConn(conn, d.writeBytesPerSecond, d.readBytesPerSecond) 243 | } 244 | return conn, err 245 | } 246 | 247 | // DialContext connects to the address on the named network using the provided 248 | // context. It returns a connection with the configured bandwidth limits. 249 | func (d *Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) { 250 | conn, err := d.Dialer.DialContext(ctx, network, address) 251 | if conn != nil { 252 | conn = NewConn(conn, d.writeBytesPerSecond, d.readBytesPerSecond) 253 | } 254 | return conn, err 255 | } 256 | 257 | // WriteBandwidthLimit returns the current write bandwidth limit. 258 | func (d *Dialer) WriteBandwidthLimit() Byte { 259 | return d.writeBytesPerSecond 260 | } 261 | 262 | // ReadBandwidthLimit returns the current read bandwidth limit. 263 | func (d *Dialer) ReadBandwidthLimit() Byte { 264 | return d.readBytesPerSecond 265 | } 266 | 267 | // SetWriteBandwidthLimit sets the bandwidth limit for writes on future 268 | // connections opened in Accept. It has no effect on already opened connections. 269 | // A zero value for bytesPerSecond means the bandwidth limit is removed. 270 | func (d *Dialer) SetWriteBandwidthLimit(bytesPerSecond Byte) { 271 | if bytesPerSecond <= 0 { 272 | d.writeBytesPerSecond = 0 273 | return 274 | } 275 | d.writeBytesPerSecond = bytesPerSecond 276 | } 277 | 278 | // SetReadBandwidthLimit sets the bandwidth limit for reads on future 279 | // connections opened in Accept. It has no effect on already opened connections. 280 | // A zero value for bytesPerSecond means the bandwidth limit is removed. 281 | func (d *Dialer) SetReadBandwidthLimit(bytesPerSecond Byte) { 282 | if bytesPerSecond <= 0 { 283 | d.readBytesPerSecond = 0 284 | return 285 | } 286 | d.readBytesPerSecond = bytesPerSecond 287 | } 288 | --------------------------------------------------------------------------------