Compare commits
	
		
			212 Commits
		
	
	
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| d830f70157 | |||
| 581fecd8f1 | |||
| d5d1e26d7b | |||
| aabfecfd3d | |||
| ff7a88fcce | |||
| 397f5414b3 | |||
| 9dd6efddf9 | |||
| 1e587b348a | |||
| 8475922d42 | |||
| 69fe6994ae | |||
| 6360feb351 | |||
| 0845f4873b | |||
| 747e35148f | |||
| 21f06fee6c | |||
| f4f8793686 | |||
| ec4922ad8b | |||
| eaea14e5a8 | |||
| f6f7139d2f | |||
| 51e4118dfc | |||
| aaf8c43e04 | |||
| cfecb4afd0 | |||
| ae4ae64694 | |||
| 2ca4e5c74e | |||
| 2809ebcaeb | |||
| 3f04403319 | |||
| 8edfc11eef | |||
| cb5ef75e09 | |||
| d5bd105cc6 | |||
| 1ba02ed8ad | |||
| 7c5da60556 | |||
| 07fa36d704 | |||
| 849bbd7a09 | |||
| f461bb6876 | |||
| 201d22d1c4 | |||
| ff6a272594 | |||
| 1018abe7bd | |||
| 398c3c81cb | |||
|  | 786d03b521 | ||
| 937c9d5720 | |||
|  | 951fba55fa | ||
|  | ec5238ed14 | ||
| d8f44a924e | |||
|  | ffe9e5d952 | ||
| 8c362fd6ae | |||
| 90365a455c | |||
| 6a218ca7b2 | |||
| ba9b88c650 | |||
| aedd60ea87 | |||
| ea2ac477be | |||
| c1fa2f639d | |||
| 8e3f2c67d7 | |||
| e66194695e | |||
| 894d6f4f20 | |||
| d404fa31ab | |||
| 88777a29ad | |||
| 23c2903c21 | |||
| 8fcc23f639 | |||
| 25dda1f34c | |||
| fe66086c40 | |||
| 7329bc23bc | |||
| c240631cdb | |||
|  | 6a68533824 | ||
| 058b6354c0 | |||
| 1f4cf11afe | |||
| 39177da1d0 | |||
| d559db4050 | |||
| aa946c469a | |||
| 9c4d88bb69 | |||
| 56288f46b1 | |||
| 81dcef8b28 | |||
| ec7a22b2dc | |||
| d2ac0c1360 | |||
| 69dd8c4eea | |||
| 27a6a923cd | |||
| 0a395235d6 | |||
| 23f0ad0f2f | |||
| 4fcbe0a770 | |||
| 28c9865121 | |||
| 697413d829 | |||
| 8a64e8c5cc | |||
| 2c8ca8d14f | |||
| 769ac6322f | |||
| 52318d68b8 | |||
| 5c4332ffc4 | |||
| 3a86d4c0f4 | |||
| 8bbcc30d04 | |||
| 221b248b1f | |||
| a9b13378f3 | |||
| adb5c9bfc9 | |||
|  | 92bf44e543 | ||
| e48ded17ee | |||
|  | 7753ecd14f | ||
| 7766fbf312 | |||
|  | 6916724a8b | ||
| e584100c18 | |||
|  | 63cc0c1cc6 | ||
| 396e71e9f7 | |||
|  | 4709eaf769 | ||
| 366bdea3d0 | |||
|  | 947fca7cd5 | ||
| 97c55fa16b | |||
|  | c845a00697 | ||
|  | dbee3ac120 | ||
|  | 740926d262 | ||
|  | 03d78ef2ff | ||
|  | 90063ef841 | ||
| 7faf1dfbc8 | |||
|  | 5a80d798c6 | ||
| 0323c5fccc | |||
|  | 80e7f6b19f | ||
| 9a4cc96640 | |||
|  | 4a67d63e4e | ||
| f69d96756e | |||
|  | 67dbeb2c57 | ||
| 328d15311b | |||
|  | 2899b963c4 | ||
|  | 78f07ac959 | ||
| dc1ebd45be | |||
|  | 6925f0291d | ||
| 5d8a72fa86 | |||
|  | f7096e71cf | ||
|  | ab10ca9658 | ||
|  | bb269b5879 | ||
| 24a6b4045e | |||
|  | 09b1b526b8 | ||
| af9bca00a1 | |||
|  | 1c2cc611ef | ||
|  | d6e18b5163 | ||
|  | 37d571076f | ||
|  | ddba046c77 | ||
| 7390973672 | |||
| 6360f5e78f | |||
|  | 9a69314c25 | ||
|  | a4eb047a58 | ||
|  | 7ad74ea1fc | ||
| 821b12484e | |||
| 893794dbf4 | |||
| ea629d6e34 | |||
| 585c94ad65 | |||
| 1d100aee63 | |||
| 6ccc996fe6 | |||
| 0d8c5d3a86 | |||
| 203266aaea | |||
|  | a7fed3241d | ||
|  | d0dbb58f4b | ||
| 71de5058a7 | |||
|  | 0e0762180d | ||
| 80523cf9bb | |||
|  | 9c4f7d65d2 | ||
|  | 4b4add52a6 | ||
|  | 61003dd396 | ||
|  | 12bee708a0 | ||
|  | f4a0c3e5de | ||
|  | 2e065f49c0 | ||
| 2a91aba7bf | |||
|  | fe4cf8a492 | ||
|  | cbf92e21e0 | ||
|  | ce096a23c0 | ||
|  | 105faed19f | ||
| d6ff088e1f | |||
|  | a33b7c1ccb | ||
| 87b5b3dd9f | |||
| 3081e902d2 | |||
|  | 204cd9608c | ||
| caefafeea7 | |||
|  | 05b0ede365 | ||
| b3e8eeb6ff | |||
|  | 1a1e359a4e | ||
| b7a77d4038 | |||
|  | d1b6d2187a | ||
| a4a88c1aad | |||
|  | 3a9c961474 | ||
| 0f0e095629 | |||
|  | 70a4aa1982 | ||
| 7cfe5bcd98 | |||
|  | 7ad07bd79e | ||
| 9d4aa6ce53 | |||
|  | 8f500ef92c | ||
| f6bad32a6a | |||
|  | dc30c68388 | ||
|  | b099c2d0e0 | ||
|  | 389736e131 | ||
|  | e774a716c5 | ||
|  | f208bf9272 | ||
|  | a0a86ef4f6 | ||
|  | 3a5716419d | ||
|  | 10188f073b | ||
|  | df5999629c | ||
|  | 6b051b3fd8 | ||
|  | d856988a16 | ||
| bc0d2026ad | |||
| 1fc59df95b | |||
| ff82f9f960 | |||
|  | 221f07ca97 | ||
| 44b9a59aab | |||
|  | 81cd4c1ec6 | ||
| 50d1343adb | |||
|  | 4c6b057a90 | ||
| 06acad41fe | |||
|  | 0ac121099f | ||
| d30f3d200b | |||
| 4373f485ce | |||
|  | 9faac6a407 | ||
| 02134eacc2 | |||
|  | be302e0816 | ||
| cfd4fb611e | |||
|  | 619d9d0d70 | ||
| ebad3e1369 | |||
|  | 485de5136f | ||
| 6ce9ed8e84 | |||
| 2c74b3232b | |||
| 69fb765b09 | 
							
								
								
									
										19
									
								
								.github/dependabot.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										19
									
								
								.github/dependabot.yml
									
									
									
									
										vendored
									
									
								
							| @@ -1,19 +0,0 @@ | |||||||
| # To get started with Dependabot version updates, you'll need to specify which |  | ||||||
| # package ecosystems to update and where the package manifests are located. |  | ||||||
| # Please see the documentation for all configuration options: |  | ||||||
| # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates |  | ||||||
|  |  | ||||||
| version: 2 |  | ||||||
| updates: |  | ||||||
|  |  | ||||||
|   # Maintain dependencies for GitHub Actions |  | ||||||
|   - package-ecosystem: "github-actions" |  | ||||||
|     directory: "/" |  | ||||||
|     schedule: |  | ||||||
|       interval: "daily" |  | ||||||
|  |  | ||||||
|   # Maintain dependencies for Golang |  | ||||||
|   - package-ecosystem: "gomod" |  | ||||||
|     directory: "/" |  | ||||||
|     schedule: |  | ||||||
|       interval: "daily" |  | ||||||
							
								
								
									
										46
									
								
								.github/workflows/build.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										46
									
								
								.github/workflows/build.yml
									
									
									
									
										vendored
									
									
								
							| @@ -1,46 +0,0 @@ | |||||||
| name: build |  | ||||||
| on: |  | ||||||
|  push: |  | ||||||
|     branches: |  | ||||||
|     - master |  | ||||||
| jobs: |  | ||||||
|   test: |  | ||||||
|     name: test |  | ||||||
|     runs-on: ubuntu-latest |  | ||||||
|     steps: |  | ||||||
|     - name: setup |  | ||||||
|       uses: actions/setup-go@v2 |  | ||||||
|       with: |  | ||||||
|         go-version: 1.16 |  | ||||||
|     - name: checkout |  | ||||||
|       uses: actions/checkout@v2 |  | ||||||
|     - name: cache |  | ||||||
|       uses: actions/cache@v2 |  | ||||||
|       with: |  | ||||||
|         path: ~/go/pkg/mod |  | ||||||
|         key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} |  | ||||||
|         restore-keys: ${{ runner.os }}-go- |  | ||||||
|     - name: deps |  | ||||||
|       run: go get -v -t -d ./... |  | ||||||
|     - name: test |  | ||||||
|       env: |  | ||||||
|         INTEGRATION_TESTS: yes |  | ||||||
|       run: go test -mod readonly -v ./... |  | ||||||
|   lint: |  | ||||||
|     name: lint |  | ||||||
|     runs-on: ubuntu-latest |  | ||||||
|     steps: |  | ||||||
|       - name: checkout |  | ||||||
|         uses: actions/checkout@v2 |  | ||||||
|       - name: lint |  | ||||||
|         uses: golangci/golangci-lint-action@v2 |  | ||||||
|         continue-on-error: true |  | ||||||
|         with: |  | ||||||
|           # Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version. |  | ||||||
|           version: v1.30 |  | ||||||
|           # Optional: working directory, useful for monorepos |  | ||||||
|           # working-directory: somedir |  | ||||||
|           # Optional: golangci-lint command line arguments. |  | ||||||
|           # args: --issues-exit-code=0 |  | ||||||
|           # Optional: show only new issues if it's a pull request. The default value is `false`. |  | ||||||
|           # only-new-issues: true |  | ||||||
							
								
								
									
										75
									
								
								.github/workflows/codeql-analysis.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										75
									
								
								.github/workflows/codeql-analysis.yml
									
									
									
									
										vendored
									
									
								
							| @@ -1,75 +0,0 @@ | |||||||
| # For most projects, this workflow file will not need changing; you simply need |  | ||||||
| # to commit it to your repository. |  | ||||||
| # |  | ||||||
| # You may wish to alter this file to override the set of languages analyzed, |  | ||||||
| # or to provide custom queries or build logic. |  | ||||||
| # |  | ||||||
| # ******** NOTE ******** |  | ||||||
| # We have attempted to detect the languages in your repository. Please check |  | ||||||
| # the `language` matrix defined below to confirm you have the correct set of |  | ||||||
| # supported CodeQL languages. |  | ||||||
| # |  | ||||||
| name: "CodeQL" |  | ||||||
|  |  | ||||||
| on: |  | ||||||
|   workflow_run: |  | ||||||
|     workflows: ["prbuild"] |  | ||||||
|     types: |  | ||||||
|       - completed |  | ||||||
|   push: |  | ||||||
|     branches: [ master ] |  | ||||||
|   pull_request: |  | ||||||
|     # The branches below must be a subset of the branches above |  | ||||||
|     branches: [ master ] |  | ||||||
|   schedule: |  | ||||||
|     - cron: '34 1 * * 0' |  | ||||||
|  |  | ||||||
| jobs: |  | ||||||
|   analyze: |  | ||||||
|     name: Analyze |  | ||||||
|     runs-on: ubuntu-latest |  | ||||||
|     permissions: |  | ||||||
|       actions: read |  | ||||||
|       contents: read |  | ||||||
|       security-events: write |  | ||||||
|  |  | ||||||
|     strategy: |  | ||||||
|       fail-fast: false |  | ||||||
|       matrix: |  | ||||||
|         language: [ 'go' ] |  | ||||||
|         # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] |  | ||||||
|         # Learn more: |  | ||||||
|         # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed |  | ||||||
|  |  | ||||||
|     steps: |  | ||||||
|     - name: Checkout repository |  | ||||||
|       uses: actions/checkout@v2 |  | ||||||
|  |  | ||||||
|     # Initializes the CodeQL tools for scanning. |  | ||||||
|     - name: Initialize CodeQL |  | ||||||
|       uses: github/codeql-action/init@v1 |  | ||||||
|       with: |  | ||||||
|         languages: ${{ matrix.language }} |  | ||||||
|         # If you wish to specify custom queries, you can do so here or in a config file. |  | ||||||
|         # By default, queries listed here will override any specified in a config file. |  | ||||||
|         # Prefix the list here with "+" to use these queries and those in the config file. |  | ||||||
|         # queries: ./path/to/local/query, your-org/your-repo/queries@main |  | ||||||
|  |  | ||||||
|     # Autobuild attempts to build any compiled languages  (C/C++, C#, or Java). |  | ||||||
|     # If this step fails, then you should remove it and run the build manually (see below) |  | ||||||
|     - name: Autobuild |  | ||||||
|       uses: github/codeql-action/autobuild@v1 |  | ||||||
|  |  | ||||||
|     # ℹ️ Command-line programs to run using the OS shell. |  | ||||||
|     # 📚 https://git.io/JvXDl |  | ||||||
|  |  | ||||||
|     # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines |  | ||||||
|     #    and modify them (or add more) to build your code if your project |  | ||||||
|     #    uses a compiled language |  | ||||||
|  |  | ||||||
|     #- run: | |  | ||||||
|     #   make bootstrap |  | ||||||
|     #   make release |  | ||||||
|  |  | ||||||
|     - name: Perform CodeQL Analysis |  | ||||||
|       uses: github/codeql-action/analyze@v1 |  | ||||||
							
								
								
									
										66
									
								
								.github/workflows/dependabot-automerge.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										66
									
								
								.github/workflows/dependabot-automerge.yml
									
									
									
									
										vendored
									
									
								
							| @@ -1,66 +0,0 @@ | |||||||
| name: "prautomerge" |  | ||||||
|  |  | ||||||
| on: |  | ||||||
|   workflow_run: |  | ||||||
|     workflows: ["prbuild"] |  | ||||||
|     types: |  | ||||||
|       - completed |  | ||||||
|  |  | ||||||
| permissions: |  | ||||||
|   contents: write |  | ||||||
|   pull-requests: write |  | ||||||
|  |  | ||||||
| jobs: |  | ||||||
|   Dependabot-Automerge: |  | ||||||
|     runs-on: ubuntu-latest |  | ||||||
|     # Contains workaround to execute if dependabot updates the PR by checking for the base branch in the linked PR |  | ||||||
|     # The the github.event.workflow_run.event value is 'push' and not 'pull_request' |  | ||||||
|     # dont work with multiple workflows when last returns success |  | ||||||
|     if: >- |  | ||||||
|       github.event.workflow_run.conclusion == 'success' |  | ||||||
|       && github.actor == 'dependabot[bot]' |  | ||||||
|       && github.event.sender.login == 'dependabot[bot]' |  | ||||||
|       && github.event.sender.type == 'Bot' |  | ||||||
|       && (github.event.workflow_run.event == 'pull_request' |  | ||||||
|           || (github.event.workflow_run.event == 'push' && github.event.workflow_run.pull_requests[0].base.ref == github.event.repository.default_branch )) |  | ||||||
|     steps: |  | ||||||
|       - name: Approve Changes and Merge changes if label 'dependencies' is set |  | ||||||
|         uses: actions/github-script@v5 |  | ||||||
|         with: |  | ||||||
|           github-token: ${{ secrets.GITHUB_TOKEN }} |  | ||||||
|           script: | |  | ||||||
|             console.log(context.payload.workflow_run); |  | ||||||
|              |  | ||||||
|             var labelNames = await github.paginate( |  | ||||||
|               github.issues.listLabelsOnIssue, |  | ||||||
|               { |  | ||||||
|                 repo: context.repo.repo, |  | ||||||
|                 owner: context.repo.owner, |  | ||||||
|                 issue_number: context.payload.workflow_run.pull_requests[0].number, |  | ||||||
|               }, |  | ||||||
|               (response) => response.data.map( |  | ||||||
|                 (label) => label.name |  | ||||||
|               ) |  | ||||||
|             ); |  | ||||||
|  |  | ||||||
|             console.log(labelNames); |  | ||||||
|  |  | ||||||
|             if (labelNames.includes('dependencies')) { |  | ||||||
|               console.log('Found label'); |  | ||||||
|  |  | ||||||
|               await github.pulls.createReview({ |  | ||||||
|                 repo: context.repo.repo, |  | ||||||
|                 owner: context.repo.owner, |  | ||||||
|                 pull_number: context.payload.workflow_run.pull_requests[0].number, |  | ||||||
|                 event: 'APPROVE' |  | ||||||
|               }); |  | ||||||
|               console.log('Approved PR'); |  | ||||||
|  |  | ||||||
|               await github.pulls.merge({ |  | ||||||
|                 repo: context.repo.repo, |  | ||||||
|                 owner: context.repo.owner, |  | ||||||
|                 pull_number: context.payload.workflow_run.pull_requests[0].number, |  | ||||||
|               }); |  | ||||||
|  |  | ||||||
|               console.log('Merged PR'); |  | ||||||
|             } |  | ||||||
							
								
								
									
										53
									
								
								.github/workflows/job_coverage.yml
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										53
									
								
								.github/workflows/job_coverage.yml
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @@ -0,0 +1,53 @@ | |||||||
|  | name: coverage | ||||||
|  |  | ||||||
|  | on: | ||||||
|  |   push: | ||||||
|  |     branches: [ main, v3, v4 ] | ||||||
|  |     paths-ignore: | ||||||
|  |       - '.github/**' | ||||||
|  |       - '.gitea/**' | ||||||
|  |   pull_request: | ||||||
|  |     branches: [ main, v3, v4 ] | ||||||
|  |  | ||||||
|  | jobs: | ||||||
|  |  | ||||||
|  |   build: | ||||||
|  |     if: github.server_url != 'https://github.com' | ||||||
|  |     runs-on: ubuntu-latest | ||||||
|  |     steps: | ||||||
|  |     - name: checkout code | ||||||
|  |       uses: actions/checkout@v4 | ||||||
|  |       with: | ||||||
|  |         filter: 'blob:none' | ||||||
|  |  | ||||||
|  |     - name: setup go | ||||||
|  |       uses: actions/setup-go@v5 | ||||||
|  |       with: | ||||||
|  |         cache-dependency-path: "**/*.sum" | ||||||
|  |         go-version: 'stable' | ||||||
|  |  | ||||||
|  |     - name: test coverage | ||||||
|  |       run: | | ||||||
|  |         go test -v -cover ./... -covermode=count -coverprofile coverage.out -coverpkg ./... | ||||||
|  |         go tool cover -func coverage.out -o coverage.out | ||||||
|  |  | ||||||
|  |     - name: coverage badge | ||||||
|  |       uses: tj-actions/coverage-badge-go@v2 | ||||||
|  |       with: | ||||||
|  |         green: 80 | ||||||
|  |         filename: coverage.out | ||||||
|  |  | ||||||
|  |     - uses: stefanzweifel/git-auto-commit-action@v4 | ||||||
|  |       name: autocommit | ||||||
|  |       with: | ||||||
|  |         commit_message: Apply Code Coverage Badge | ||||||
|  |         skip_fetch: false | ||||||
|  |         skip_checkout: false | ||||||
|  |         file_pattern: ./README.md | ||||||
|  |  | ||||||
|  |     - name: push | ||||||
|  |       if: steps.auto-commit-action.outputs.changes_detected == 'true' | ||||||
|  |       uses: ad-m/github-push-action@master | ||||||
|  |       with: | ||||||
|  |         github_token: ${{ github.token }} | ||||||
|  |         branch: ${{ github.ref }} | ||||||
							
								
								
									
										29
									
								
								.github/workflows/job_lint.yml
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										29
									
								
								.github/workflows/job_lint.yml
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @@ -0,0 +1,29 @@ | |||||||
|  | name: lint | ||||||
|  |  | ||||||
|  | on: | ||||||
|  |   pull_request: | ||||||
|  |     types: [opened, reopened, synchronize] | ||||||
|  |     branches: [ master, v3, v4 ] | ||||||
|  |     paths-ignore: | ||||||
|  |       - '.github/**' | ||||||
|  |       - '.gitea/**' | ||||||
|  |  | ||||||
|  | jobs: | ||||||
|  |   lint: | ||||||
|  |     runs-on: ubuntu-latest | ||||||
|  |     steps: | ||||||
|  |     - name: checkout code | ||||||
|  |       uses: actions/checkout@v4 | ||||||
|  |       with: | ||||||
|  |         filter: 'blob:none' | ||||||
|  |     - name: setup go | ||||||
|  |       uses: actions/setup-go@v5 | ||||||
|  |       with: | ||||||
|  |         cache-dependency-path: "**/*.sum" | ||||||
|  |         go-version: 'stable' | ||||||
|  |     - name: setup deps | ||||||
|  |       run: go get -v ./... | ||||||
|  |     - name: run lint | ||||||
|  |       uses: golangci/golangci-lint-action@v6 | ||||||
|  |       with: | ||||||
|  |         version: 'latest' | ||||||
							
								
								
									
										31
									
								
								.github/workflows/job_test.yml
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										31
									
								
								.github/workflows/job_test.yml
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @@ -0,0 +1,31 @@ | |||||||
|  | name: test | ||||||
|  |  | ||||||
|  | on: | ||||||
|  |   pull_request: | ||||||
|  |     types: [opened, reopened, synchronize] | ||||||
|  |     branches: [ master, v3, v4 ] | ||||||
|  |   push: | ||||||
|  |     branches: [ master, v3, v4 ] | ||||||
|  |     paths-ignore: | ||||||
|  |       - '.github/**' | ||||||
|  |       - '.gitea/**' | ||||||
|  |  | ||||||
|  | jobs: | ||||||
|  |   test: | ||||||
|  |     runs-on: ubuntu-latest | ||||||
|  |     steps: | ||||||
|  |     - name: checkout code | ||||||
|  |       uses: actions/checkout@v4 | ||||||
|  |       with: | ||||||
|  |         filter: 'blob:none' | ||||||
|  |     - name: setup go | ||||||
|  |       uses: actions/setup-go@v5 | ||||||
|  |       with: | ||||||
|  |         cache-dependency-path: "**/*.sum" | ||||||
|  |         go-version: 'stable' | ||||||
|  |     - name: setup deps | ||||||
|  |       run: go get -v ./... | ||||||
|  |     - name: run test | ||||||
|  |       env: | ||||||
|  |         INTEGRATION_TESTS: yes | ||||||
|  |       run: go test -mod readonly -v ./... | ||||||
							
								
								
									
										50
									
								
								.github/workflows/job_tests.yml
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										50
									
								
								.github/workflows/job_tests.yml
									
									
									
									
										vendored
									
									
										Normal file
									
								
							| @@ -0,0 +1,50 @@ | |||||||
|  | name: test | ||||||
|  |  | ||||||
|  | on: | ||||||
|  |   pull_request: | ||||||
|  |     types: [opened, reopened, synchronize] | ||||||
|  |     branches: [ master, v3, v4 ] | ||||||
|  |   push: | ||||||
|  |     branches: [ master, v3, v4 ] | ||||||
|  |     paths-ignore: | ||||||
|  |       - '.github/**' | ||||||
|  |       - '.gitea/**' | ||||||
|  |  | ||||||
|  | jobs: | ||||||
|  |   test: | ||||||
|  |     runs-on: ubuntu-latest | ||||||
|  |     steps: | ||||||
|  |     - name: checkout code | ||||||
|  |       uses: actions/checkout@v4 | ||||||
|  |       with: | ||||||
|  |         filter: 'blob:none' | ||||||
|  |     - name: checkout tests | ||||||
|  |       uses: actions/checkout@v4 | ||||||
|  |       with: | ||||||
|  |         ref: master | ||||||
|  |         filter: 'blob:none' | ||||||
|  |         repository: unistack-org/micro-tests | ||||||
|  |         path: micro-tests | ||||||
|  |     - name: setup go | ||||||
|  |       uses: actions/setup-go@v5 | ||||||
|  |       with: | ||||||
|  |         cache-dependency-path: "**/*.sum" | ||||||
|  |         go-version: 'stable' | ||||||
|  |     - name: setup go work | ||||||
|  |       env: | ||||||
|  |         GOWORK: ${{ github.workspace }}/go.work | ||||||
|  |       run: | | ||||||
|  |         go work init | ||||||
|  |         go work use . | ||||||
|  |         go work use micro-tests | ||||||
|  |     - name: setup deps | ||||||
|  |       env: | ||||||
|  |         GOWORK: ${{ github.workspace }}/go.work | ||||||
|  |       run: go get -v ./... | ||||||
|  |     - name: run tests | ||||||
|  |       env: | ||||||
|  |         INTEGRATION_TESTS: yes | ||||||
|  |         GOWORK: ${{ github.workspace }}/go.work | ||||||
|  |       run: | | ||||||
|  |         cd micro-tests | ||||||
|  |         go test -mod readonly -v ./... || true | ||||||
							
								
								
									
										46
									
								
								.github/workflows/pr.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										46
									
								
								.github/workflows/pr.yml
									
									
									
									
										vendored
									
									
								
							| @@ -1,46 +0,0 @@ | |||||||
| name: prbuild |  | ||||||
| on: |  | ||||||
|   pull_request: |  | ||||||
|     branches: |  | ||||||
|     - master |  | ||||||
| jobs: |  | ||||||
|   test: |  | ||||||
|     name: test |  | ||||||
|     runs-on: ubuntu-latest |  | ||||||
|     steps: |  | ||||||
|     - name: setup |  | ||||||
|       uses: actions/setup-go@v2 |  | ||||||
|       with: |  | ||||||
|         go-version: 1.16 |  | ||||||
|     - name: checkout |  | ||||||
|       uses: actions/checkout@v2 |  | ||||||
|     - name: cache |  | ||||||
|       uses: actions/cache@v2 |  | ||||||
|       with: |  | ||||||
|         path: ~/go/pkg/mod |  | ||||||
|         key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} |  | ||||||
|         restore-keys: ${{ runner.os }}-go- |  | ||||||
|     - name: deps |  | ||||||
|       run: go get -v -t -d ./... |  | ||||||
|     - name: test |  | ||||||
|       env: |  | ||||||
|         INTEGRATION_TESTS: yes |  | ||||||
|       run: go test -mod readonly -v ./... |  | ||||||
|   lint: |  | ||||||
|     name: lint |  | ||||||
|     runs-on: ubuntu-latest |  | ||||||
|     steps: |  | ||||||
|       - name: checkout |  | ||||||
|         uses: actions/checkout@v2 |  | ||||||
|       - name: lint |  | ||||||
|         uses: golangci/golangci-lint-action@v2 |  | ||||||
|         continue-on-error: true |  | ||||||
|         with: |  | ||||||
|           # Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version. |  | ||||||
|           version: v1.30 |  | ||||||
|           # Optional: working directory, useful for monorepos |  | ||||||
|           # working-directory: somedir |  | ||||||
|           # Optional: golangci-lint command line arguments. |  | ||||||
|           # args: --issues-exit-code=0 |  | ||||||
|           # Optional: show only new issues if it's a pull request. The default value is `false`. |  | ||||||
|           # only-new-issues: true |  | ||||||
							
								
								
									
										6
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										6
									
								
								.gitignore
									
									
									
									
										vendored
									
									
								
							| @@ -13,3 +13,9 @@ | |||||||
|  |  | ||||||
| # Dependency directories (remove the comment below to include it) | # Dependency directories (remove the comment below to include it) | ||||||
| # vendor/ | # vendor/ | ||||||
|  |  | ||||||
|  | # General | ||||||
|  | .DS_Store | ||||||
|  | .idea | ||||||
|  | .vscode | ||||||
|  | bin/ | ||||||
|   | |||||||
							
								
								
									
										5
									
								
								.golangci.yml
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										5
									
								
								.golangci.yml
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,5 @@ | |||||||
|  | run: | ||||||
|  |   concurrency: 8 | ||||||
|  |   timeout: 5m | ||||||
|  |   issues-exit-code: 1 | ||||||
|  |   tests: true | ||||||
							
								
								
									
										11
									
								
								README.md
									
									
									
									
									
								
							
							
						
						
									
										11
									
								
								README.md
									
									
									
									
									
								
							| @@ -1,2 +1,9 @@ | |||||||
| # micro-broker-kgo | # broker-kgo | ||||||
| yet another micro kafka broker alternative |  | ||||||
|  | TODO: | ||||||
|  |  | ||||||
|  | 1) экспортируем текущий оффсет для каждой партиции в группе | ||||||
|  | 2) экспортируем лаг для группы | ||||||
|  | 3) мониторим | ||||||
|  |    1) если есть лаг больше нуля | ||||||
|  |    2) если дельта оффсета за нужное нам время не  | ||||||
							
								
								
									
										93
									
								
								carrier.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										93
									
								
								carrier.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,93 @@ | |||||||
|  | package kgo | ||||||
|  |  | ||||||
|  | import ( | ||||||
|  | 	"net/http" | ||||||
|  | 	"slices" | ||||||
|  | 	"strings" | ||||||
|  |  | ||||||
|  | 	"github.com/twmb/franz-go/pkg/kgo" | ||||||
|  | 	"go.unistack.org/micro/v3/metadata" | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | // RecordCarrier injects and extracts traces from a kgo.Record. | ||||||
|  | // | ||||||
|  | // This type exists to satisfy the otel/propagation.TextMapCarrier interface. | ||||||
|  | type RecordCarrier struct { | ||||||
|  | 	record *kgo.Record | ||||||
|  | } | ||||||
|  |  | ||||||
|  | // NewRecordCarrier creates a new RecordCarrier. | ||||||
|  | func NewRecordCarrier(record *kgo.Record) RecordCarrier { | ||||||
|  | 	return RecordCarrier{record: record} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | // Get retrieves a single value for a given key if it exists. | ||||||
|  | func (c RecordCarrier) Get(key string) string { | ||||||
|  | 	for _, h := range c.record.Headers { | ||||||
|  | 		if h.Key == key { | ||||||
|  | 			return string(h.Value) | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  | 	return "" | ||||||
|  | } | ||||||
|  |  | ||||||
|  | // Set sets a header. | ||||||
|  | func (c RecordCarrier) Set(key, val string) { | ||||||
|  | 	// Check if key already exists. | ||||||
|  | 	for i, h := range c.record.Headers { | ||||||
|  | 		if h.Key == key { | ||||||
|  | 			// Key exist, update the value. | ||||||
|  | 			c.record.Headers[i].Value = []byte(val) | ||||||
|  | 			return | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  | 	// Key does not exist, append new header. | ||||||
|  | 	c.record.Headers = append(c.record.Headers, kgo.RecordHeader{ | ||||||
|  | 		Key:   key, | ||||||
|  | 		Value: []byte(val), | ||||||
|  | 	}) | ||||||
|  | } | ||||||
|  |  | ||||||
|  | // Keys returns a slice of all key identifiers in the carrier. | ||||||
|  | func (c RecordCarrier) Keys() []string { | ||||||
|  | 	out := make([]string, len(c.record.Headers)) | ||||||
|  | 	for i, h := range c.record.Headers { | ||||||
|  | 		out[i] = h.Key | ||||||
|  | 	} | ||||||
|  | 	return out | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func setHeaders(r *kgo.Record, md metadata.Metadata, exclude ...string) { | ||||||
|  | 	seen := make(map[string]struct{}) | ||||||
|  |  | ||||||
|  | loop: | ||||||
|  | 	for k, v := range md { | ||||||
|  | 		k = http.CanonicalHeaderKey(k) | ||||||
|  |  | ||||||
|  | 		if _, ok := seen[k]; ok { | ||||||
|  | 			continue loop | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		if slices.ContainsFunc(exclude, func(s string) bool { | ||||||
|  | 			return strings.EqualFold(s, k) | ||||||
|  | 		}) { | ||||||
|  | 			continue loop | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		for i := 0; i < len(r.Headers); i++ { | ||||||
|  | 			if strings.EqualFold(r.Headers[i].Key, k) { | ||||||
|  | 				// Key exist, update the value. | ||||||
|  | 				r.Headers[i].Value = []byte(v) | ||||||
|  | 				continue loop | ||||||
|  | 			} | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		// Key does not exist, append new header. | ||||||
|  | 		r.Headers = append(r.Headers, kgo.RecordHeader{ | ||||||
|  | 			Key:   k, | ||||||
|  | 			Value: []byte(v), | ||||||
|  | 		}) | ||||||
|  |  | ||||||
|  | 		seen[k] = struct{}{} | ||||||
|  | 	} | ||||||
|  | } | ||||||
							
								
								
									
										10
									
								
								errors.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										10
									
								
								errors.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,10 @@ | |||||||
|  | package kgo | ||||||
|  |  | ||||||
|  | import ( | ||||||
|  | 	"context" | ||||||
|  | 	"errors" | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | func isContextError(err error) bool { | ||||||
|  | 	return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) | ||||||
|  | } | ||||||
							
								
								
									
										50
									
								
								event.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										50
									
								
								event.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,50 @@ | |||||||
|  | package kgo | ||||||
|  |  | ||||||
|  | import ( | ||||||
|  | 	"context" | ||||||
|  | 	"sync" | ||||||
|  |  | ||||||
|  | 	"go.unistack.org/micro/v3/broker" | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | type event struct { | ||||||
|  | 	msg *broker.Message | ||||||
|  | 	err error | ||||||
|  | 	ctx context.Context | ||||||
|  |  | ||||||
|  | 	topic string | ||||||
|  |  | ||||||
|  | 	sync.RWMutex | ||||||
|  | 	ack bool | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (p *event) Context() context.Context { | ||||||
|  | 	return p.ctx | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (p *event) Topic() string { | ||||||
|  | 	return p.topic | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (p *event) Message() *broker.Message { | ||||||
|  | 	return p.msg | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (p *event) Ack() error { | ||||||
|  | 	p.ack = true | ||||||
|  | 	return nil | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (p *event) Error() error { | ||||||
|  | 	return p.err | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (p *event) SetError(err error) { | ||||||
|  | 	p.err = err | ||||||
|  | } | ||||||
|  |  | ||||||
|  | var eventPool = sync.Pool{ | ||||||
|  | 	New: func() interface{} { | ||||||
|  | 		return &event{msg: &broker.Message{}} | ||||||
|  | 	}, | ||||||
|  | } | ||||||
							
								
								
									
										32
									
								
								go.mod
									
									
									
									
									
								
							
							
						
						
									
										32
									
								
								go.mod
									
									
									
									
									
								
							| @@ -1,10 +1,32 @@ | |||||||
| module go.unistack.org/micro-broker-kgo/v3 | module go.unistack.org/micro-broker-kgo/v3 | ||||||
|  |  | ||||||
| go 1.16 | go 1.24.0 | ||||||
|  |  | ||||||
|  | toolchain go1.24.3 | ||||||
|  |  | ||||||
| require ( | require ( | ||||||
| 	github.com/klauspost/compress v1.13.6 // indirect | 	github.com/google/uuid v1.6.0 | ||||||
| 	github.com/twmb/franz-go v1.1.2 | 	github.com/stretchr/testify v1.11.1 | ||||||
| 	github.com/twmb/franz-go/pkg/kmsg v0.0.0-20210930203137-7fbfd17de279 | 	github.com/twmb/franz-go v1.19.5 | ||||||
| 	go.unistack.org/micro/v3 v3.8.0 | 	github.com/twmb/franz-go/pkg/kadm v1.16.1 | ||||||
|  | 	github.com/twmb/franz-go/pkg/kmsg v1.11.2 | ||||||
|  | 	go.opentelemetry.io/otel v1.38.0 | ||||||
|  | 	go.unistack.org/micro/v3 v3.11.45 | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | require ( | ||||||
|  | 	github.com/ash3in/uuidv8 v1.2.0 // indirect | ||||||
|  | 	github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect | ||||||
|  | 	github.com/klauspost/compress v1.18.0 // indirect | ||||||
|  | 	github.com/kr/pretty v0.3.1 // indirect | ||||||
|  | 	github.com/matoous/go-nanoid v1.5.1 // indirect | ||||||
|  | 	github.com/pierrec/lz4/v4 v4.1.22 // indirect | ||||||
|  | 	github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect | ||||||
|  | 	go.unistack.org/micro-proto/v3 v3.4.1 // indirect | ||||||
|  | 	golang.org/x/crypto v0.43.0 // indirect | ||||||
|  | 	golang.org/x/sys v0.37.0 // indirect | ||||||
|  | 	google.golang.org/genproto/googleapis/rpc v0.0.0-20251007200510-49b9836ed3ff // indirect | ||||||
|  | 	google.golang.org/grpc v1.76.0 // indirect | ||||||
|  | 	google.golang.org/protobuf v1.36.10 // indirect | ||||||
|  | 	gopkg.in/yaml.v3 v3.0.1 // indirect | ||||||
| ) | ) | ||||||
|   | |||||||
							
								
								
									
										127
									
								
								go.sum
									
									
									
									
									
								
							
							
						
						
									
										127
									
								
								go.sum
									
									
									
									
									
								
							| @@ -1,67 +1,62 @@ | |||||||
| github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= | github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU= | ||||||
| github.com/ef-ds/deque v1.0.4/go.mod h1:gXDnTC3yqvBcHbq2lcExjtAcVrOnJCbMcZXmuj8Z4tg= | github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU= | ||||||
| github.com/golang-jwt/jwt/v4 v4.1.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg= | github.com/ash3in/uuidv8 v1.2.0 h1:2oogGdtCPwaVtyvPPGin4TfZLtOGE5F+W++E880G6SI= | ||||||
| github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= | github.com/ash3in/uuidv8 v1.2.0/go.mod h1:BnU0wJBxnzdEKmVg4xckBkD+VZuecTFTUP3M0dWgyY4= | ||||||
| github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= | github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= | ||||||
| github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= | ||||||
| github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= | ||||||
| github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= | github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= | ||||||
| github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= | github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= | ||||||
| github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= | github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= | ||||||
| github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= | github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= | ||||||
| github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs= | github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= | ||||||
| github.com/jcmturner/dnsutils/v2 v2.0.0/go.mod h1:b0TnjGOvI/n42bZa+hmXL+kFJZsFT7G4t3HTlQ184QM= | github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= | ||||||
| github.com/jcmturner/gofork v1.0.0/go.mod h1:MK8+TM0La+2rjBD4jE12Kj1pCCxK7d2LK/UM3ncEo0o= | github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= | ||||||
| github.com/jcmturner/goidentity/v6 v6.0.1/go.mod h1:X1YW3bgtvwAXju7V3LCIMpY0Gbxyjn/mY9zx4tFonSg= | github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= | ||||||
| github.com/jcmturner/gokrb5/v8 v8.4.2/go.mod h1:sb+Xq/fTY5yktf/VxLsE3wlfPqQjp0aWNYyvBVK62bc= | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= | ||||||
| github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc= | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= | ||||||
| github.com/klauspost/compress v1.13.5/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= | ||||||
| github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc= | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= | ||||||
| github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= | github.com/matoous/go-nanoid v1.5.1 h1:aCjdvTyO9LLnTIi0fgdXhOPPvOHjpXN6Ik9DaNjIct4= | ||||||
| github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= | github.com/matoous/go-nanoid v1.5.1/go.mod h1:zyD2a71IubI24efhpvkJz+ZwfwagzgSO6UNiFsZKN7U= | ||||||
| github.com/pierrec/lz4/v4 v4.1.8 h1:ieHkV+i2BRzngO4Wd/3HGowuZStgq6QkPsD1eolNAO4= | github.com/pierrec/lz4/v4 v4.1.22 h1:cKFw6uJDK+/gfw5BcDL0JL5aBsAFdsIT18eRtLj7VIU= | ||||||
| github.com/pierrec/lz4/v4 v4.1.8/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= | github.com/pierrec/lz4/v4 v4.1.22/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= | ||||||
| github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= | github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= | ||||||
| github.com/silas/dag v0.0.0-20210626123444-3804bac2d6d4/go.mod h1:7RTUFBdIRC9nZ7/3RyRNH1bdqIShrDejd1YbLwgPS+I= | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= | ||||||
| github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= | ||||||
| github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= | github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= | ||||||
| github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= | github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= | ||||||
| github.com/twmb/franz-go v1.1.2 h1:i9lCDEcXWpRd3YXFlffIc/koBl+JijI13F5sg69NPRk= | github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= | ||||||
| github.com/twmb/franz-go v1.1.2/go.mod h1:KerrVhzNpasYrWJLr2Yj6Cui43f1BxH4U9SJEDVOjqQ= | github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= | ||||||
| github.com/twmb/franz-go/pkg/kmsg v0.0.0-20210914042331-106aef61b693/go.mod h1:SxG/xJKhgPu25SamAq0rrucfp7lbzCpEXOC+vH/ELrY= | github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= | ||||||
| github.com/twmb/franz-go/pkg/kmsg v0.0.0-20210930203137-7fbfd17de279 h1:58GX0Ju/PCG1zWVdsLEE5OUu70KlfOrxY7djPszuqiw= | github.com/twmb/franz-go v1.19.5 h1:W7+o8D0RsQsedqib71OVlLeZ0zI6CbFra7yTYhZTs5Y= | ||||||
| github.com/twmb/franz-go/pkg/kmsg v0.0.0-20210930203137-7fbfd17de279/go.mod h1:SxG/xJKhgPu25SamAq0rrucfp7lbzCpEXOC+vH/ELrY= | github.com/twmb/franz-go v1.19.5/go.mod h1:4kFJ5tmbbl7asgwAGVuyG1ZMx0NNpYk7EqflvWfPCpM= | ||||||
| github.com/twmb/go-rbtree v1.0.0 h1:KxN7dXJ8XaZ4cvmHV1qqXTshxX3EBvX/toG5+UR49Mg= | github.com/twmb/franz-go/pkg/kadm v1.16.1 h1:IEkrhTljgLHJ0/hT/InhXGjPdmWfFvxp7o/MR7vJ8cw= | ||||||
| github.com/twmb/go-rbtree v1.0.0/go.mod h1:UlIAI8gu3KRPkXSobZnmJfVwCJgEhD/liWzT5ppzIyc= | github.com/twmb/franz-go/pkg/kadm v1.16.1/go.mod h1:Ue/ye1cc9ipsQFg7udFbbGiFNzQMqiH73fGC2y0rwyc= | ||||||
| github.com/unistack-org/micro-proto v0.0.9 h1:KrWLS4FUX7UAWNAilQf70uad6ZPf/0EudeddCXllRVc= | github.com/twmb/franz-go/pkg/kmsg v1.11.2 h1:hIw75FpwcAjgeyfIGFqivAvwC5uNIOWRGvQgZhH4mhg= | ||||||
| github.com/unistack-org/micro-proto v0.0.9/go.mod h1:Cckwmzd89gvS7ThxzZp9kQR/EOdksFQcsTAtDDyKwrg= | github.com/twmb/franz-go/pkg/kmsg v1.11.2/go.mod h1:CFfkkLysDNmukPYhGzuUcDtf46gQSqCZHMW1T4Z+wDE= | ||||||
| go.unistack.org/micro/v3 v3.8.0 h1:9k6C40xdJf65VW6cVB8sOJVSJhyz1UfFOhX7/II2ivo= | go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8= | ||||||
| go.unistack.org/micro/v3 v3.8.0/go.mod h1:Tkteri0wiiybbH6aPqay26pZHFIAwL9LXJc2x1Jkakk= | go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM= | ||||||
| golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= | go.unistack.org/micro-proto/v3 v3.4.1 h1:UTjLSRz2YZuaHk9iSlVqqsA50JQNAEK2ZFboGqtEa9Q= | ||||||
| golang.org/x/crypto v0.0.0-20201112155050-0c6587e931a9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= | go.unistack.org/micro-proto/v3 v3.4.1/go.mod h1:okx/cnOhzuCX0ggl/vToatbCupi0O44diiiLLsZ93Zo= | ||||||
| golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= | go.unistack.org/micro/v3 v3.11.45 h1:fjTLZYWgsVf9FIMZBxOg8ios2/tmyimnjZrsrxEUeXU= | ||||||
| golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= | go.unistack.org/micro/v3 v3.11.45/go.mod h1:fDQ8Mu9wubaFP0L8hNQlpzHiEnWN0wbOlawN9HYo0N4= | ||||||
| golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= | golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04= | ||||||
| golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= | golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0= | ||||||
| golang.org/x/net v0.0.0-20210913180222-943fd674d43e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= | golang.org/x/net v0.45.0 h1:RLBg5JKixCy82FtLJpeNlVM0nrSqpCRYzVU1n8kj0tM= | ||||||
| golang.org/x/net v0.0.0-20210928044308-7d9f5e0b762b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= | golang.org/x/net v0.45.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY= | ||||||
| golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= | golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ= | ||||||
| golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= | golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= | ||||||
| golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= | golang.org/x/text v0.30.0 h1:yznKA/E9zq54KzlzBEAWn1NXSQ8DIp/NYMy88xJjl4k= | ||||||
| golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= | golang.org/x/text v0.30.0/go.mod h1:yDdHFIX9t+tORqspjENWgzaCVXgk0yYnYuSZ8UzzBVM= | ||||||
| golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= | google.golang.org/genproto/googleapis/rpc v0.0.0-20251007200510-49b9836ed3ff h1:A90eA31Wq6HOMIQlLfzFwzqGKBTuaVztYu/g8sn+8Zc= | ||||||
| golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= | google.golang.org/genproto/googleapis/rpc v0.0.0-20251007200510-49b9836ed3ff/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk= | ||||||
| golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= | google.golang.org/grpc v1.76.0 h1:UnVkv1+uMLYXoIz6o7chp59WfQUYA2ex/BXQ9rHZu7A= | ||||||
| golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= | google.golang.org/grpc v1.76.0/go.mod h1:Ju12QI8M6iQJtbcsV+awF5a4hfJMLi4X0JLo94ULZ6c= | ||||||
| golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= | google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= | ||||||
| golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= | google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= | ||||||
| golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= |  | ||||||
| golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= |  | ||||||
| golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= |  | ||||||
| google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= |  | ||||||
| google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ= |  | ||||||
| google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= |  | ||||||
| gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= | ||||||
| gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= | ||||||
| gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= | gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= | ||||||
| gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= | ||||||
|  | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= | ||||||
|   | |||||||
							
								
								
									
										73
									
								
								hook_event.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										73
									
								
								hook_event.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,73 @@ | |||||||
|  | package kgo | ||||||
|  |  | ||||||
|  | import ( | ||||||
|  | 	"context" | ||||||
|  | 	"net" | ||||||
|  | 	"sync/atomic" | ||||||
|  | 	"time" | ||||||
|  |  | ||||||
|  | 	"github.com/twmb/franz-go/pkg/kgo" | ||||||
|  | 	"go.unistack.org/micro/v3/logger" | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | type hookEvent struct { | ||||||
|  | 	log          logger.Logger | ||||||
|  | 	connected    *atomic.Uint32 | ||||||
|  | 	fatalOnError bool | ||||||
|  | } | ||||||
|  |  | ||||||
|  | var ( | ||||||
|  | 	_ kgo.HookBrokerConnect           = &hookEvent{} | ||||||
|  | 	_ kgo.HookBrokerDisconnect        = &hookEvent{} | ||||||
|  | 	_ kgo.HookBrokerRead              = &hookEvent{} | ||||||
|  | 	_ kgo.HookBrokerWrite             = &hookEvent{} | ||||||
|  | 	_ kgo.HookGroupManageError        = &hookEvent{} | ||||||
|  | 	_ kgo.HookProduceRecordUnbuffered = &hookEvent{} | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | func (m *hookEvent) OnGroupManageError(err error) { | ||||||
|  | 	switch { | ||||||
|  | 	case err == nil || isContextError(err) || kgo.IsRetryableBrokerErr(err): | ||||||
|  | 		return | ||||||
|  | 	default: | ||||||
|  | 		m.log.Error(context.TODO(), "kgo.OnGroupManageError", err) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *hookEvent) OnBrokerConnect(_ kgo.BrokerMetadata, _ time.Duration, _ net.Conn, err error) { | ||||||
|  | 	switch { | ||||||
|  | 	case err == nil || isContextError(err) || kgo.IsRetryableBrokerErr(err): | ||||||
|  | 		return | ||||||
|  | 	default: | ||||||
|  | 		m.log.Error(context.TODO(), "kgo.OnBrokerConnect", err) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *hookEvent) OnBrokerDisconnect(_ kgo.BrokerMetadata, _ net.Conn) {} | ||||||
|  |  | ||||||
|  | func (m *hookEvent) OnBrokerWrite(_ kgo.BrokerMetadata, _ int16, _ int, _ time.Duration, _ time.Duration, err error) { | ||||||
|  | 	switch { | ||||||
|  | 	case err == nil || isContextError(err) || kgo.IsRetryableBrokerErr(err): | ||||||
|  | 		return | ||||||
|  | 	default: | ||||||
|  | 		m.log.Error(context.TODO(), "kgo.OnBrokerWrite", err) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *hookEvent) OnBrokerRead(_ kgo.BrokerMetadata, _ int16, _ int, _ time.Duration, _ time.Duration, err error) { | ||||||
|  | 	switch { | ||||||
|  | 	case err == nil || isContextError(err) || kgo.IsRetryableBrokerErr(err): | ||||||
|  | 		return | ||||||
|  | 	default: | ||||||
|  | 		m.log.Error(context.TODO(), "kgo.OnBrokerRead", err) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *hookEvent) OnProduceRecordUnbuffered(_ *kgo.Record, err error) { | ||||||
|  | 	switch { | ||||||
|  | 	case err == nil || isContextError(err) || kgo.IsRetryableBrokerErr(err): | ||||||
|  | 		return | ||||||
|  | 	default: | ||||||
|  | 		m.log.Error(context.TODO(), "kgo.OnProduceRecordUnbuffered", err) | ||||||
|  | 	} | ||||||
|  | } | ||||||
							
								
								
									
										362
									
								
								hook_event_test.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										362
									
								
								hook_event_test.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,362 @@ | |||||||
|  | package kgo | ||||||
|  |  | ||||||
|  | import ( | ||||||
|  | 	"context" | ||||||
|  | 	"errors" | ||||||
|  | 	"io" | ||||||
|  | 	"net" | ||||||
|  | 	"os" | ||||||
|  | 	"testing" | ||||||
|  |  | ||||||
|  | 	"github.com/stretchr/testify/require" | ||||||
|  | 	"github.com/twmb/franz-go/pkg/kgo" | ||||||
|  | 	"go.unistack.org/micro/v3/logger" | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | func TestHookEvent_OnGroupManageError(t *testing.T) { | ||||||
|  | 	tests := []struct { | ||||||
|  | 		name                  string | ||||||
|  | 		inputErr              error | ||||||
|  | 		expectedErrorIsCalled bool | ||||||
|  | 		expectedErrorMsg      string | ||||||
|  | 	}{ | ||||||
|  | 		{ | ||||||
|  | 			name:                  "error is nil", | ||||||
|  | 			inputErr:              nil, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "context canceled", | ||||||
|  | 			inputErr:              context.Canceled, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "context deadline exceeded", | ||||||
|  | 			inputErr:              context.DeadlineExceeded, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: deadline exceeded (os package)", | ||||||
|  | 			inputErr:              os.ErrDeadlineExceeded, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: EOF (io package)", | ||||||
|  | 			inputErr:              io.EOF, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: closed network connection (net package)", | ||||||
|  | 			inputErr:              net.ErrClosed, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "some error", | ||||||
|  | 			inputErr:              errors.New("some error"), | ||||||
|  | 			expectedErrorIsCalled: true, | ||||||
|  | 			expectedErrorMsg:      "kgo.OnGroupManageError", | ||||||
|  | 		}, | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	for _, tt := range tests { | ||||||
|  | 		t.Run(tt.name, func(t *testing.T) { | ||||||
|  | 			log := &mockLogger{} | ||||||
|  | 			he := &hookEvent{log: log} | ||||||
|  | 			he.OnGroupManageError(tt.inputErr) | ||||||
|  | 			require.Equal(t, tt.expectedErrorIsCalled, log.errorIsCalled) | ||||||
|  | 			require.Equal(t, tt.expectedErrorMsg, log.errorMsg) | ||||||
|  | 		}) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func TestHookEvent_OnBrokerConnect(t *testing.T) { | ||||||
|  | 	tests := []struct { | ||||||
|  | 		name                  string | ||||||
|  | 		inputErr              error | ||||||
|  | 		expectedErrorIsCalled bool | ||||||
|  | 		expectedErrorMsg      string | ||||||
|  | 	}{ | ||||||
|  | 		{ | ||||||
|  | 			name:                  "error is nil", | ||||||
|  | 			inputErr:              nil, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "context canceled", | ||||||
|  | 			inputErr:              context.Canceled, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "context deadline exceeded", | ||||||
|  | 			inputErr:              context.DeadlineExceeded, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: deadline exceeded (os package)", | ||||||
|  | 			inputErr:              os.ErrDeadlineExceeded, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: EOF (io package)", | ||||||
|  | 			inputErr:              io.EOF, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: closed network connection (net package)", | ||||||
|  | 			inputErr:              net.ErrClosed, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "some error", | ||||||
|  | 			inputErr:              errors.New("some error"), | ||||||
|  | 			expectedErrorIsCalled: true, | ||||||
|  | 			expectedErrorMsg:      "kgo.OnBrokerConnect", | ||||||
|  | 		}, | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	for _, tt := range tests { | ||||||
|  | 		t.Run(tt.name, func(t *testing.T) { | ||||||
|  | 			log := &mockLogger{} | ||||||
|  | 			he := &hookEvent{log: log} | ||||||
|  | 			he.OnBrokerConnect(kgo.BrokerMetadata{}, 0, nil, tt.inputErr) | ||||||
|  | 			require.Equal(t, tt.expectedErrorIsCalled, log.errorIsCalled) | ||||||
|  | 			require.Equal(t, tt.expectedErrorMsg, log.errorMsg) | ||||||
|  | 		}) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func TestHookEvent_OnBrokerWrite(t *testing.T) { | ||||||
|  | 	tests := []struct { | ||||||
|  | 		name                  string | ||||||
|  | 		inputErr              error | ||||||
|  | 		expectedErrorIsCalled bool | ||||||
|  | 		expectedErrorMsg      string | ||||||
|  | 	}{ | ||||||
|  | 		{ | ||||||
|  | 			name:                  "error is nil", | ||||||
|  | 			inputErr:              nil, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "context canceled", | ||||||
|  | 			inputErr:              context.Canceled, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "context deadline exceeded", | ||||||
|  | 			inputErr:              context.DeadlineExceeded, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: deadline exceeded (os package)", | ||||||
|  | 			inputErr:              os.ErrDeadlineExceeded, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: EOF (io package)", | ||||||
|  | 			inputErr:              io.EOF, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: closed network connection (net package)", | ||||||
|  | 			inputErr:              net.ErrClosed, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "some error", | ||||||
|  | 			inputErr:              errors.New("some error"), | ||||||
|  | 			expectedErrorIsCalled: true, | ||||||
|  | 			expectedErrorMsg:      "kgo.OnBrokerWrite", | ||||||
|  | 		}, | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	for _, tt := range tests { | ||||||
|  | 		t.Run(tt.name, func(t *testing.T) { | ||||||
|  | 			log := &mockLogger{} | ||||||
|  | 			he := &hookEvent{log: log} | ||||||
|  | 			he.OnBrokerWrite(kgo.BrokerMetadata{}, 0, 0, 0, 0, tt.inputErr) | ||||||
|  | 			require.Equal(t, tt.expectedErrorIsCalled, log.errorIsCalled) | ||||||
|  | 			require.Equal(t, tt.expectedErrorMsg, log.errorMsg) | ||||||
|  | 		}) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func TestHookEvent_OnBrokerRead(t *testing.T) { | ||||||
|  | 	tests := []struct { | ||||||
|  | 		name                  string | ||||||
|  | 		inputErr              error | ||||||
|  | 		expectedErrorIsCalled bool | ||||||
|  | 		expectedErrorMsg      string | ||||||
|  | 	}{ | ||||||
|  | 		{ | ||||||
|  | 			name:                  "error is nil", | ||||||
|  | 			inputErr:              nil, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "context canceled", | ||||||
|  | 			inputErr:              context.Canceled, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "context deadline exceeded", | ||||||
|  | 			inputErr:              context.DeadlineExceeded, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: deadline exceeded (os package)", | ||||||
|  | 			inputErr:              os.ErrDeadlineExceeded, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: EOF (io package)", | ||||||
|  | 			inputErr:              io.EOF, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: closed network connection (net package)", | ||||||
|  | 			inputErr:              net.ErrClosed, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "some error", | ||||||
|  | 			inputErr:              errors.New("some error"), | ||||||
|  | 			expectedErrorIsCalled: true, | ||||||
|  | 			expectedErrorMsg:      "kgo.OnBrokerRead", | ||||||
|  | 		}, | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	for _, tt := range tests { | ||||||
|  | 		t.Run(tt.name, func(t *testing.T) { | ||||||
|  | 			log := &mockLogger{} | ||||||
|  | 			he := &hookEvent{log: log} | ||||||
|  | 			he.OnBrokerRead(kgo.BrokerMetadata{}, 0, 0, 0, 0, tt.inputErr) | ||||||
|  | 			require.Equal(t, tt.expectedErrorIsCalled, log.errorIsCalled) | ||||||
|  | 			require.Equal(t, tt.expectedErrorMsg, log.errorMsg) | ||||||
|  | 		}) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func TestHookEvent_OnProduceRecordUnbuffered(t *testing.T) { | ||||||
|  | 	tests := []struct { | ||||||
|  | 		name                  string | ||||||
|  | 		inputErr              error | ||||||
|  | 		expectedErrorIsCalled bool | ||||||
|  | 		expectedErrorMsg      string | ||||||
|  | 	}{ | ||||||
|  | 		{ | ||||||
|  | 			name:                  "error is nil", | ||||||
|  | 			inputErr:              nil, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "context canceled", | ||||||
|  | 			inputErr:              context.Canceled, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "context deadline exceeded", | ||||||
|  | 			inputErr:              context.DeadlineExceeded, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: deadline exceeded (os package)", | ||||||
|  | 			inputErr:              os.ErrDeadlineExceeded, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: EOF (io package)", | ||||||
|  | 			inputErr:              io.EOF, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "retryable error: closed network connection (net package)", | ||||||
|  | 			inputErr:              net.ErrClosed, | ||||||
|  | 			expectedErrorIsCalled: false, | ||||||
|  | 		}, | ||||||
|  | 		{ | ||||||
|  | 			name:                  "some error", | ||||||
|  | 			inputErr:              errors.New("some error"), | ||||||
|  | 			expectedErrorIsCalled: true, | ||||||
|  | 			expectedErrorMsg:      "kgo.OnProduceRecordUnbuffered", | ||||||
|  | 		}, | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	for _, tt := range tests { | ||||||
|  | 		t.Run(tt.name, func(t *testing.T) { | ||||||
|  | 			log := &mockLogger{} | ||||||
|  | 			he := &hookEvent{log: log} | ||||||
|  | 			he.OnProduceRecordUnbuffered(&kgo.Record{}, tt.inputErr) | ||||||
|  | 			require.Equal(t, tt.expectedErrorIsCalled, log.errorIsCalled) | ||||||
|  | 			require.Equal(t, tt.expectedErrorMsg, log.errorMsg) | ||||||
|  | 		}) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | // Mocks | ||||||
|  |  | ||||||
|  | type mockLogger struct { | ||||||
|  | 	errorIsCalled bool | ||||||
|  | 	errorMsg      string | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Init(...logger.Option) error { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Clone(...logger.Option) logger.Logger { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) V(logger.Level) bool { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Level(logger.Level) { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Options() logger.Options { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Fields(...interface{}) logger.Logger { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Info(context.Context, string, ...interface{}) { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Trace(context.Context, string, ...interface{}) { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Debug(context.Context, string, ...interface{}) { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Warn(context.Context, string, ...interface{}) { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Error(ctx context.Context, msg string, args ...interface{}) { | ||||||
|  | 	m.errorIsCalled = true | ||||||
|  | 	m.errorMsg = msg | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Fatal(context.Context, string, ...interface{}) { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Log(context.Context, logger.Level, string, ...interface{}) { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) Name() string { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *mockLogger) String() string { | ||||||
|  | 	panic("implement me") | ||||||
|  | } | ||||||
							
								
								
									
										654
									
								
								kgo.go
									
									
									
									
									
								
							
							
						
						
									
										654
									
								
								kgo.go
									
									
									
									
									
								
							| @@ -3,202 +3,305 @@ package kgo | |||||||
|  |  | ||||||
| import ( | import ( | ||||||
| 	"context" | 	"context" | ||||||
|  | 	"errors" | ||||||
| 	"fmt" | 	"fmt" | ||||||
|  | 	"math/rand/v2" | ||||||
|  | 	"strconv" | ||||||
| 	"strings" | 	"strings" | ||||||
| 	"sync" | 	"sync" | ||||||
|  | 	"sync/atomic" | ||||||
| 	"time" | 	"time" | ||||||
|  |  | ||||||
| 	"github.com/twmb/franz-go/pkg/kerr" | 	"github.com/google/uuid" | ||||||
| 	kgo "github.com/twmb/franz-go/pkg/kgo" | 	"github.com/twmb/franz-go/pkg/kadm" | ||||||
|  | 	"github.com/twmb/franz-go/pkg/kgo" | ||||||
| 	"github.com/twmb/franz-go/pkg/kmsg" | 	"github.com/twmb/franz-go/pkg/kmsg" | ||||||
| 	"github.com/twmb/franz-go/pkg/kversion" |  | ||||||
| 	"go.unistack.org/micro/v3/broker" | 	"go.unistack.org/micro/v3/broker" | ||||||
| 	"go.unistack.org/micro/v3/logger" | 	"go.unistack.org/micro/v3/logger" | ||||||
| 	"go.unistack.org/micro/v3/metadata" | 	"go.unistack.org/micro/v3/metadata" | ||||||
| 	"go.unistack.org/micro/v3/util/id" | 	"go.unistack.org/micro/v3/semconv" | ||||||
|  | 	"go.unistack.org/micro/v3/tracer" | ||||||
|  | 	mjitter "go.unistack.org/micro/v3/util/jitter" | ||||||
| 	mrand "go.unistack.org/micro/v3/util/rand" | 	mrand "go.unistack.org/micro/v3/util/rand" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| var _ broker.Broker = &kBroker{} | var _ broker.Broker = (*Broker)(nil) | ||||||
|  |  | ||||||
|  | var ErrLostMessage = errors.New("message not marked for offsets commit and will be lost in next iteration") | ||||||
|  |  | ||||||
|  | var DefaultRetryBackoffFn = func() func(int) time.Duration { | ||||||
|  | 	var rngMu sync.Mutex | ||||||
|  | 	return func(fails int) time.Duration { | ||||||
|  | 		const ( | ||||||
|  | 			min = 100 * time.Millisecond | ||||||
|  | 			max = time.Second | ||||||
|  | 		) | ||||||
|  | 		if fails <= 0 { | ||||||
|  | 			return min | ||||||
|  | 		} | ||||||
|  | 		if fails > 10 { | ||||||
|  | 			return max | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		backoff := min * time.Duration(1<<(fails-1)) | ||||||
|  |  | ||||||
|  | 		rngMu.Lock() | ||||||
|  | 		jitter := 0.8 + 0.4*rand.Float64() | ||||||
|  | 		rngMu.Unlock() | ||||||
|  |  | ||||||
|  | 		backoff = time.Duration(float64(backoff) * jitter) | ||||||
|  |  | ||||||
|  | 		if backoff > max { | ||||||
|  | 			return max | ||||||
|  | 		} | ||||||
|  | 		return backoff | ||||||
|  | 	} | ||||||
|  | }() | ||||||
|  |  | ||||||
|  | type Broker struct { | ||||||
|  | 	c         *kgo.Client | ||||||
|  | 	connected *atomic.Uint32 | ||||||
|  |  | ||||||
|  | 	done chan struct{} | ||||||
|  |  | ||||||
|  | 	kopts []kgo.Opt | ||||||
|  | 	subs  []*Subscriber | ||||||
|  |  | ||||||
| type kBroker struct { |  | ||||||
| 	writer    *kgo.Client // used only to push messages |  | ||||||
| 	kopts     []kgo.Opt |  | ||||||
| 	connected bool |  | ||||||
| 	init      bool |  | ||||||
| 	sync.RWMutex |  | ||||||
| 	opts broker.Options | 	opts broker.Options | ||||||
| 	subs []*subscriber | 	mu   sync.RWMutex | ||||||
|  |  | ||||||
|  | 	init bool | ||||||
| } | } | ||||||
|  |  | ||||||
| type subscriber struct { | func (r *Broker) Live() bool { | ||||||
| 	reader       *kgo.Client // used only to pull messages | 	return r.connected.Load() == 1 | ||||||
| 	topic        string |  | ||||||
| 	opts         broker.SubscribeOptions |  | ||||||
| 	kopts        broker.Options |  | ||||||
| 	handler      broker.Handler |  | ||||||
| 	batchhandler broker.BatchHandler |  | ||||||
| 	closed       bool |  | ||||||
| 	done         chan struct{} |  | ||||||
| 	consumers    map[string]map[int32]worker |  | ||||||
| 	sync.RWMutex |  | ||||||
| } | } | ||||||
|  |  | ||||||
| type publication struct { | func (r *Broker) Ready() bool { | ||||||
| 	topic string | 	return r.connected.Load() == 1 | ||||||
| 	err   error |  | ||||||
| 	sync.RWMutex |  | ||||||
| 	msg *broker.Message |  | ||||||
| 	ack bool |  | ||||||
| } | } | ||||||
|  |  | ||||||
| func (p *publication) Topic() string { | func (r *Broker) Health() bool { | ||||||
| 	return p.topic | 	return r.connected.Load() == 1 | ||||||
| } | } | ||||||
|  |  | ||||||
| func (p *publication) Message() *broker.Message { | func (k *Broker) Address() string { | ||||||
| 	return p.msg |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (p *publication) Ack() error { |  | ||||||
| 	p.ack = true |  | ||||||
| 	return nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (p *publication) Error() error { |  | ||||||
| 	return p.err |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (p *publication) SetError(err error) { |  | ||||||
| 	p.err = err |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (s *subscriber) Options() broker.SubscribeOptions { |  | ||||||
| 	return s.opts |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (s *subscriber) Topic() string { |  | ||||||
| 	return s.topic |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (s *subscriber) Unsubscribe(ctx context.Context) error { |  | ||||||
| 	if s.closed { |  | ||||||
| 		return nil |  | ||||||
| 	} |  | ||||||
| 	select { |  | ||||||
| 	case <-ctx.Done(): |  | ||||||
| 		return ctx.Err() |  | ||||||
| 	default: |  | ||||||
| 		close(s.done) |  | ||||||
| 		s.closed = true |  | ||||||
| 	} |  | ||||||
| 	return nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (k *kBroker) Address() string { |  | ||||||
| 	return strings.Join(k.opts.Addrs, ",") | 	return strings.Join(k.opts.Addrs, ",") | ||||||
| } | } | ||||||
|  |  | ||||||
| func (k *kBroker) Name() string { | func (k *Broker) Name() string { | ||||||
| 	return k.opts.Name | 	return k.opts.Name | ||||||
| } | } | ||||||
|  |  | ||||||
| func (k *kBroker) Connect(ctx context.Context) error { | func (k *Broker) Client() *kgo.Client { | ||||||
| 	k.RLock() | 	return k.c | ||||||
| 	if k.connected { | } | ||||||
| 		k.RUnlock() |  | ||||||
|  | func (k *Broker) connect(ctx context.Context, opts ...kgo.Opt) (*kgo.Client, *hookTracer, error) { | ||||||
|  | 	var c *kgo.Client | ||||||
|  | 	var err error | ||||||
|  |  | ||||||
|  | 	sp, _ := tracer.SpanFromContext(ctx) | ||||||
|  |  | ||||||
|  | 	clientID := "kgo" | ||||||
|  | 	group := "" | ||||||
|  | 	if k.opts.Context != nil { | ||||||
|  | 		if id, ok := k.opts.Context.Value(clientIDKey{}).(string); ok { | ||||||
|  | 			clientID = id | ||||||
|  | 		} | ||||||
|  | 		if id, ok := k.opts.Context.Value(groupKey{}).(string); ok { | ||||||
|  | 			group = id | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	var fatalOnError bool | ||||||
|  | 	if k.opts.Context != nil { | ||||||
|  | 		if v, ok := k.opts.Context.Value(fatalOnErrorKey{}).(bool); ok && v { | ||||||
|  | 			fatalOnError = v | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	htracer := &hookTracer{group: group, clientID: clientID, tracer: k.opts.Tracer} | ||||||
|  | 	opts = append(opts, | ||||||
|  | 		kgo.WithHooks(&hookMeter{meter: k.opts.Meter}), | ||||||
|  | 		kgo.WithHooks(htracer), | ||||||
|  | 		kgo.WithHooks(&hookEvent{log: k.opts.Logger, fatalOnError: fatalOnError, connected: k.connected}), | ||||||
|  | 	) | ||||||
|  |  | ||||||
|  | 	select { | ||||||
|  | 	case <-ctx.Done(): | ||||||
|  | 		if ctx.Err() != nil { | ||||||
|  | 			if sp != nil { | ||||||
|  | 				sp.SetStatus(tracer.SpanStatusError, ctx.Err().Error()) | ||||||
|  | 			} | ||||||
|  | 		} | ||||||
|  | 		return nil, nil, ctx.Err() | ||||||
|  | 	default: | ||||||
|  | 		c, err = kgo.NewClient(opts...) | ||||||
|  | 		if err == nil { | ||||||
|  | 			err = c.Ping(ctx) // check connectivity to cluster | ||||||
|  | 		} | ||||||
|  | 		if err != nil { | ||||||
|  | 			if sp != nil { | ||||||
|  | 				sp.SetStatus(tracer.SpanStatusError, err.Error()) | ||||||
|  | 			} | ||||||
|  | 			return nil, nil, err | ||||||
|  | 		} | ||||||
|  | 		k.connected.Store(1) | ||||||
|  |  | ||||||
|  | 		if fatalOnError { | ||||||
|  | 			go func() { | ||||||
|  | 				c := 3 | ||||||
|  | 				n := 0 | ||||||
|  | 				tc := mjitter.NewTicker(500*time.Millisecond, 1*time.Second) | ||||||
|  | 				defer tc.Stop() | ||||||
|  | 				for range tc.C { | ||||||
|  | 					if k.connected.Load() == 0 { | ||||||
|  | 						if n > c { | ||||||
|  | 							k.opts.Logger.Fatal(context.Background(), "broker fatal error") | ||||||
|  | 						} | ||||||
|  | 						n++ | ||||||
|  | 					} else { | ||||||
|  | 						n = 0 | ||||||
|  | 					} | ||||||
|  | 				} | ||||||
|  | 			}() | ||||||
|  | 		} | ||||||
|  | 		return c, htracer, nil | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (k *Broker) Connect(ctx context.Context) error { | ||||||
|  | 	if k.connected.Load() == 1 { | ||||||
| 		return nil | 		return nil | ||||||
| 	} | 	} | ||||||
| 	k.RUnlock() |  | ||||||
|  |  | ||||||
| 	nctx := k.opts.Context | 	nctx := k.opts.Context | ||||||
| 	if ctx != nil { | 	if ctx != nil { | ||||||
| 		nctx = ctx | 		nctx = ctx | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	kaddrs := k.opts.Addrs | 	c, _, err := k.connect(nctx, k.kopts...) | ||||||
|  | 	if err != nil { | ||||||
|  | 		return err | ||||||
|  | 	} | ||||||
|  |  | ||||||
| 	// shuffle addrs | 	k.mu.Lock() | ||||||
| 	var rng mrand.Rand | 	k.c = c | ||||||
| 	rng.Shuffle(len(kaddrs), func(i, j int) { | 	k.connected.Store(1) | ||||||
| 		kaddrs[i], kaddrs[j] = kaddrs[j], kaddrs[i] | 	k.mu.Unlock() | ||||||
| 	}) |  | ||||||
|  |  | ||||||
| 	kopts := append(k.kopts, kgo.SeedBrokers(kaddrs...)) | 	exposeLag := false | ||||||
|  | 	if k.opts.Context != nil { | ||||||
|  | 		if v, ok := k.opts.Context.Value(exposeLagKey{}).(bool); ok && v { | ||||||
|  | 			exposeLag = v | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  |  | ||||||
| 	select { | 	if exposeLag { | ||||||
| 	case <-nctx.Done(): | 		var mu sync.Mutex | ||||||
| 		return nctx.Err() | 		var lastUpdate time.Time | ||||||
| 	default: | 		type pl struct { | ||||||
| 		c, err := kgo.NewClient(kopts...) | 			p string | ||||||
| 		if err != nil { | 			l float64 | ||||||
| 			return err |  | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		// Request versions in order to guess Kafka Cluster version | 		lag := make(map[string]map[string]pl) // topic => group => partition => lag | ||||||
| 		versionsReq := kmsg.NewApiVersionsRequest() | 		ac := kadm.NewClient(k.c) | ||||||
| 		versionsRes, err := versionsReq.RequestWith(ctx, c) |  | ||||||
| 		if err != nil { |  | ||||||
| 			return fmt.Errorf("failed to request api versions: %w", err) |  | ||||||
| 		} |  | ||||||
| 		err = kerr.ErrorForCode(versionsRes.ErrorCode) |  | ||||||
| 		if err != nil { |  | ||||||
| 			return fmt.Errorf("failed to request api versions. Inner kafka error: %w", err) |  | ||||||
| 		} |  | ||||||
| 		versions := kversion.FromApiVersionsResponse(versionsRes) |  | ||||||
|  |  | ||||||
| 		if k.opts.Logger.V(logger.InfoLevel) { | 		updateStats := func() { | ||||||
| 			logger.Infof(ctx, "[kgo] connected to to kafka cluster version %v", versions.VersionGuess()) | 			mu.Lock() | ||||||
|  | 			if time.Since(lastUpdate) < DefaultStatsInterval { | ||||||
|  | 				return | ||||||
|  | 			} | ||||||
|  | 			mu.Unlock() | ||||||
|  |  | ||||||
|  | 			k.mu.Lock() | ||||||
|  | 			groups := make([]string, 0, len(k.subs)) | ||||||
|  | 			for _, g := range k.subs { | ||||||
|  | 				groups = append(groups, g.opts.Group) | ||||||
|  | 			} | ||||||
|  | 			k.mu.Unlock() | ||||||
|  |  | ||||||
|  | 			dgls, err := ac.Lag(ctx, groups...) | ||||||
|  | 			if err != nil || !dgls.Ok() { | ||||||
|  | 				k.opts.Logger.Error(k.opts.Context, "kgo describe group lag error", err) | ||||||
|  | 				return | ||||||
|  | 			} | ||||||
|  |  | ||||||
|  | 			for gn, dgl := range dgls { | ||||||
|  | 				for tn, lmap := range dgl.Lag { | ||||||
|  | 					if _, ok := lag[tn]; !ok { | ||||||
|  | 						lag[tn] = make(map[string]pl) | ||||||
|  | 					} | ||||||
|  | 					for p, l := range lmap { | ||||||
|  | 						lag[tn][gn] = pl{p: strconv.Itoa(int(p)), l: float64(l.Lag)} | ||||||
|  | 					} | ||||||
|  | 				} | ||||||
|  | 			} | ||||||
|  | 		} | ||||||
|  |  | ||||||
|  | 		for tn, dg := range lag { | ||||||
|  | 			for gn, gl := range dg { | ||||||
|  | 				k.opts.Meter.Gauge(semconv.BrokerGroupLag, | ||||||
|  | 					func() float64 { updateStats(); return gl.l }, | ||||||
|  | 					"topic", tn, | ||||||
|  | 					"group", gn, | ||||||
|  | 					"partition", gl.p) | ||||||
|  | 			} | ||||||
| 		} | 		} | ||||||
|  |  | ||||||
| 		k.Lock() |  | ||||||
| 		k.connected = true |  | ||||||
| 		k.writer = c |  | ||||||
| 		k.Unlock() |  | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	return nil | 	return nil | ||||||
| } | } | ||||||
|  |  | ||||||
| func (k *kBroker) Disconnect(ctx context.Context) error { | func (k *Broker) Disconnect(ctx context.Context) error { | ||||||
| 	k.RLock() | 	if k.connected.Load() == 0 { | ||||||
| 	if !k.connected { |  | ||||||
| 		k.RUnlock() |  | ||||||
| 		return nil | 		return nil | ||||||
| 	} | 	} | ||||||
| 	k.RUnlock() |  | ||||||
|  |  | ||||||
| 	k.Lock() |  | ||||||
| 	defer k.Unlock() |  | ||||||
|  |  | ||||||
| 	nctx := k.opts.Context | 	nctx := k.opts.Context | ||||||
| 	if ctx != nil { | 	if ctx != nil { | ||||||
| 		nctx = ctx | 		nctx = ctx | ||||||
| 	} | 	} | ||||||
|  | 	var span tracer.Span | ||||||
|  | 	ctx, span = k.opts.Tracer.Start(ctx, "Disconnect") | ||||||
|  | 	defer span.Finish() | ||||||
|  |  | ||||||
|  | 	k.mu.Lock() | ||||||
|  | 	defer k.mu.Unlock() | ||||||
| 	select { | 	select { | ||||||
| 	case <-nctx.Done(): | 	case <-nctx.Done(): | ||||||
| 		return nctx.Err() | 		return nctx.Err() | ||||||
| 	default: | 	default: | ||||||
| 		for _, sub := range k.subs { | 		for _, sub := range k.subs { | ||||||
|  | 			if sub.closed { | ||||||
|  | 				continue | ||||||
|  | 			} | ||||||
| 			if err := sub.Unsubscribe(ctx); err != nil { | 			if err := sub.Unsubscribe(ctx); err != nil { | ||||||
| 				return err | 				return err | ||||||
| 			} | 			} | ||||||
| 		} | 		} | ||||||
| 		k.writer.Close() | 		if k.c != nil { | ||||||
|  | 			k.c.CloseAllowingRebalance() | ||||||
|  | 			// k.c.Close() | ||||||
|  | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	k.connected = false | 	k.connected.Store(0) | ||||||
|  | 	close(k.done) | ||||||
| 	return nil | 	return nil | ||||||
| } | } | ||||||
|  |  | ||||||
| func (k *kBroker) Init(opts ...broker.Option) error { | func (k *Broker) Init(opts ...broker.Option) error { | ||||||
| 	k.Lock() | 	k.mu.Lock() | ||||||
| 	defer k.Unlock() | 	defer k.mu.Unlock() | ||||||
|  |  | ||||||
| 	if len(opts) == 0 && k.init { | 	if len(opts) == 0 && k.init { | ||||||
| 		return nil | 		return nil | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	for _, o := range opts { | 	for _, o := range opts { | ||||||
| 		o(&k.opts) | 		o(&k.opts) | ||||||
| 	} | 	} | ||||||
| @@ -222,42 +325,51 @@ func (k *kBroker) Init(opts ...broker.Option) error { | |||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	//	kgo.RecordPartitioner(), |  | ||||||
|  |  | ||||||
| 	k.init = true | 	k.init = true | ||||||
|  |  | ||||||
| 	return nil | 	return nil | ||||||
| } | } | ||||||
|  |  | ||||||
| func (k *kBroker) Options() broker.Options { | func (k *Broker) Options() broker.Options { | ||||||
| 	return k.opts | 	return k.opts | ||||||
| } | } | ||||||
|  |  | ||||||
| func (k *kBroker) BatchPublish(ctx context.Context, msgs []*broker.Message, opts ...broker.PublishOption) error { | func (k *Broker) BatchPublish(ctx context.Context, msgs []*broker.Message, opts ...broker.PublishOption) error { | ||||||
| 	return k.publish(ctx, msgs, opts...) | 	return k.publish(ctx, msgs, opts...) | ||||||
| } | } | ||||||
|  |  | ||||||
| func (k *kBroker) Publish(ctx context.Context, topic string, msg *broker.Message, opts ...broker.PublishOption) error { | func (k *Broker) Publish(ctx context.Context, topic string, msg *broker.Message, opts ...broker.PublishOption) error { | ||||||
| 	msg.Header.Set(metadata.HeaderTopic, topic) | 	msg.Header.Set(metadata.HeaderTopic, topic) | ||||||
| 	return k.publish(ctx, []*broker.Message{msg}, opts...) | 	return k.publish(ctx, []*broker.Message{msg}, opts...) | ||||||
| } | } | ||||||
|  |  | ||||||
| func (k *kBroker) publish(ctx context.Context, msgs []*broker.Message, opts ...broker.PublishOption) error { | func (k *Broker) publish(ctx context.Context, msgs []*broker.Message, opts ...broker.PublishOption) error { | ||||||
| 	options := broker.NewPublishOptions(opts...) | 	options := broker.NewPublishOptions(opts...) | ||||||
| 	records := make([]*kgo.Record, 0, len(msgs)) | 	records := make([]*kgo.Record, 0, len(msgs)) | ||||||
| 	var errs []string | 	var errs []string | ||||||
| 	var err error | 	var err error | ||||||
|  | 	var key []byte | ||||||
|  | 	var promise func(*kgo.Record, error) | ||||||
|  |  | ||||||
|  | 	if options.Context != nil { | ||||||
|  | 		if k, ok := options.Context.Value(publishKey{}).([]byte); ok && k != nil { | ||||||
|  | 			key = k | ||||||
|  | 		} | ||||||
|  | 		if p, ok := options.Context.Value(publishPromiseKey{}).(func(*kgo.Record, error)); ok && p != nil { | ||||||
|  | 			promise = p | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  |  | ||||||
| 	for _, msg := range msgs { | 	for _, msg := range msgs { | ||||||
| 		rec := &kgo.Record{} | 		rec := &kgo.Record{Context: ctx, Key: key} | ||||||
|  |  | ||||||
| 		rec.Topic, _ = msg.Header.Get(metadata.HeaderTopic) | 		rec.Topic, _ = msg.Header.Get(metadata.HeaderTopic) | ||||||
| 		if options.BodyOnly { | 		msg.Header.Del(metadata.HeaderTopic) | ||||||
|  |  | ||||||
|  | 		k.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", rec.Topic, "topic", rec.Topic).Inc() | ||||||
|  | 		if options.BodyOnly || k.opts.Codec.String() == "noop" { | ||||||
| 			rec.Value = msg.Body | 			rec.Value = msg.Body | ||||||
| 		} else if k.opts.Codec.String() == "noop" { | 			setHeaders(rec, msg.Header) | ||||||
| 			rec.Value = msg.Body |  | ||||||
| 			for k, v := range msg.Header { |  | ||||||
| 				rec.Headers = append(rec.Headers, kgo.RecordHeader{Key: k, Value: []byte(v)}) |  | ||||||
| 			} |  | ||||||
| 		} else { | 		} else { | ||||||
| 			rec.Value, err = k.opts.Codec.Marshal(msg) | 			rec.Value, err = k.opts.Codec.Marshal(msg) | ||||||
| 			if err != nil { | 			if err != nil { | ||||||
| @@ -267,12 +379,41 @@ func (k *kBroker) publish(ctx context.Context, msgs []*broker.Message, opts ...b | |||||||
| 		records = append(records, rec) | 		records = append(records, rec) | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	results := k.writer.ProduceSync(ctx, records...) | 	if promise != nil { | ||||||
|  | 		ts := time.Now() | ||||||
|  | 		for _, rec := range records { | ||||||
|  | 			k.c.Produce(ctx, rec, func(r *kgo.Record, err error) { | ||||||
|  | 				te := time.Since(ts) | ||||||
|  | 				k.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", rec.Topic, "topic", rec.Topic).Dec() | ||||||
|  | 				k.opts.Meter.Summary(semconv.PublishMessageLatencyMicroseconds, "endpoint", rec.Topic, "topic", rec.Topic).Update(te.Seconds()) | ||||||
|  | 				k.opts.Meter.Histogram(semconv.PublishMessageDurationSeconds, "endpoint", rec.Topic, "topic", rec.Topic).Update(te.Seconds()) | ||||||
|  | 				if err != nil { | ||||||
|  | 					k.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", rec.Topic, "topic", rec.Topic, "status", "failure").Inc() | ||||||
|  | 				} else { | ||||||
|  | 					k.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", rec.Topic, "topic", rec.Topic, "status", "success").Inc() | ||||||
|  | 				} | ||||||
|  | 				promise(r, err) | ||||||
|  | 			}) | ||||||
|  | 		} | ||||||
|  | 		return nil | ||||||
|  | 	} | ||||||
|  | 	ts := time.Now() | ||||||
|  |  | ||||||
|  | 	results := k.c.ProduceSync(ctx, records...) | ||||||
|  |  | ||||||
|  | 	te := time.Since(ts) | ||||||
| 	for _, result := range results { | 	for _, result := range results { | ||||||
|  | 		k.opts.Meter.Summary(semconv.PublishMessageLatencyMicroseconds, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Update(te.Seconds()) | ||||||
|  | 		k.opts.Meter.Histogram(semconv.PublishMessageDurationSeconds, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Update(te.Seconds()) | ||||||
|  | 		k.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Dec() | ||||||
| 		if result.Err != nil { | 		if result.Err != nil { | ||||||
|  | 			k.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", result.Record.Topic, "topic", result.Record.Topic, "status", "failure").Inc() | ||||||
| 			errs = append(errs, result.Err.Error()) | 			errs = append(errs, result.Err.Error()) | ||||||
|  | 		} else { | ||||||
|  | 			k.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", result.Record.Topic, "topic", result.Record.Topic, "status", "success").Inc() | ||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	if len(errs) > 0 { | 	if len(errs) > 0 { | ||||||
| 		return fmt.Errorf("publish error: %s", strings.Join(errs, "\n")) | 		return fmt.Errorf("publish error: %s", strings.Join(errs, "\n")) | ||||||
| 	} | 	} | ||||||
| @@ -280,157 +421,134 @@ func (k *kBroker) publish(ctx context.Context, msgs []*broker.Message, opts ...b | |||||||
| 	return nil | 	return nil | ||||||
| } | } | ||||||
|  |  | ||||||
| type mlogger struct { | func (k *Broker) TopicExists(ctx context.Context, topic string) error { | ||||||
| 	l   logger.Logger | 	mdreq := kmsg.NewMetadataRequest() | ||||||
| 	ctx context.Context | 	mdreq.Topics = []kmsg.MetadataRequestTopic{ | ||||||
|  | 		{Topic: &topic}, | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	mdrsp, err := mdreq.RequestWith(ctx, k.c) | ||||||
|  | 	if err != nil { | ||||||
|  | 		return err | ||||||
|  | 	} else if mdrsp.Topics[0].ErrorCode != 0 { | ||||||
|  | 		return fmt.Errorf("topic %s not exists or permission error", topic) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	return nil | ||||||
| } | } | ||||||
|  |  | ||||||
| func (l *mlogger) Log(lvl kgo.LogLevel, msg string, args ...interface{}) { | func (k *Broker) BatchSubscribe(_ context.Context, _ string, _ broker.BatchHandler, _ ...broker.SubscribeOption) (broker.Subscriber, error) { | ||||||
| 	var mlvl logger.Level |  | ||||||
| 	switch lvl { |  | ||||||
| 	case kgo.LogLevelNone: |  | ||||||
| 		return |  | ||||||
| 	case kgo.LogLevelError: |  | ||||||
| 		mlvl = logger.ErrorLevel |  | ||||||
| 	case kgo.LogLevelWarn: |  | ||||||
| 		mlvl = logger.WarnLevel |  | ||||||
| 	case kgo.LogLevelInfo: |  | ||||||
| 		mlvl = logger.InfoLevel |  | ||||||
| 	case kgo.LogLevelDebug: |  | ||||||
| 		mlvl = logger.DebugLevel |  | ||||||
| 	default: |  | ||||||
| 		return |  | ||||||
| 	} |  | ||||||
| 	fields := make(map[string]interface{}, int(len(args)/2)) |  | ||||||
| 	for i := 0; i < len(args)/2; i += 2 { |  | ||||||
| 		fields[fmt.Sprintf("%v", args[i])] = args[i+1] |  | ||||||
| 	} |  | ||||||
| 	l.l.Fields(fields).Log(l.ctx, mlvl, msg) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (l *mlogger) Level() kgo.LogLevel { |  | ||||||
| 	switch l.l.Options().Level { |  | ||||||
| 	case logger.ErrorLevel: |  | ||||||
| 		return kgo.LogLevelError |  | ||||||
| 	case logger.WarnLevel: |  | ||||||
| 		return kgo.LogLevelWarn |  | ||||||
| 	case logger.InfoLevel: |  | ||||||
| 		return kgo.LogLevelInfo |  | ||||||
| 	case logger.DebugLevel, logger.TraceLevel: |  | ||||||
| 		return kgo.LogLevelDebug |  | ||||||
| 	} |  | ||||||
| 	return kgo.LogLevelNone |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (k *kBroker) BatchSubscribe(ctx context.Context, topic string, handler broker.BatchHandler, opts ...broker.SubscribeOption) (broker.Subscriber, error) { |  | ||||||
| 	return nil, nil | 	return nil, nil | ||||||
| } | } | ||||||
|  |  | ||||||
| func (k *kBroker) Subscribe(ctx context.Context, topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) { | func (k *Broker) Subscribe(ctx context.Context, topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) { | ||||||
| 	options := broker.NewSubscribeOptions(opts...) | 	options := broker.NewSubscribeOptions(opts...) | ||||||
|  |  | ||||||
| 	if options.Group == "" { | 	if options.Group == "" { | ||||||
| 		uid, err := id.New() | 		uid, err := uuid.NewRandom() | ||||||
| 		if err != nil { | 		if err != nil { | ||||||
| 			return nil, err | 			return nil, err | ||||||
| 		} | 		} | ||||||
| 		options.Group = uid | 		options.Group = uid.String() | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	kaddrs := k.opts.Addrs | 	commitInterval := DefaultCommitInterval | ||||||
|  | 	if k.opts.Context != nil { | ||||||
|  | 		if v, ok := k.opts.Context.Value(commitIntervalKey{}).(time.Duration); ok && v > 0 { | ||||||
|  | 			commitInterval = v | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	var fatalOnError bool | ||||||
|  | 	if k.opts.Context != nil { | ||||||
|  | 		if v, ok := k.opts.Context.Value(fatalOnErrorKey{}).(bool); ok && v { | ||||||
|  | 			fatalOnError = v | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	sub := &Subscriber{ | ||||||
|  | 		topic:        topic, | ||||||
|  | 		opts:         options, | ||||||
|  | 		handler:      handler, | ||||||
|  | 		kopts:        k.opts, | ||||||
|  | 		consumers:    make(map[tp]*consumer), | ||||||
|  | 		done:         make(chan struct{}), | ||||||
|  | 		fatalOnError: fatalOnError, | ||||||
|  | 		connected:    k.connected, | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	kopts := append(k.kopts, | ||||||
|  | 		kgo.ConsumerGroup(options.Group), | ||||||
|  | 		kgo.ConsumeTopics(topic), | ||||||
|  | 		kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()), | ||||||
|  | 		kgo.FetchMaxWait(1*time.Second), | ||||||
|  | 		kgo.AutoCommitInterval(commitInterval), | ||||||
|  | 		kgo.OnPartitionsAssigned(sub.assigned), | ||||||
|  | 		kgo.OnPartitionsRevoked(sub.revoked), | ||||||
|  | 		kgo.StopProducerOnDataLossDetected(), | ||||||
|  | 		kgo.OnPartitionsLost(sub.lost), | ||||||
|  | 		kgo.AutoCommitCallback(sub.autocommit), | ||||||
|  | 		kgo.AutoCommitMarks(), | ||||||
|  | 	) | ||||||
|  |  | ||||||
|  | 	if options.Context != nil { | ||||||
|  | 		if v, ok := options.Context.Value(optionsKey{}).([]kgo.Opt); ok && len(v) > 0 { | ||||||
|  | 			kopts = append(kopts, v...) | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	c, htracer, err := k.connect(ctx, kopts...) | ||||||
|  | 	if err != nil { | ||||||
|  | 		return nil, err | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	mdreq := kmsg.NewMetadataRequest() | ||||||
|  | 	mdreq.Topics = []kmsg.MetadataRequestTopic{ | ||||||
|  | 		{Topic: &topic}, | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	mdrsp, err := mdreq.RequestWith(ctx, c) | ||||||
|  | 	if err != nil { | ||||||
|  | 		return nil, err | ||||||
|  | 	} else if mdrsp.Topics[0].ErrorCode != 0 { | ||||||
|  | 		return nil, fmt.Errorf("topic %s not exists or permission error", topic) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	sub.c = c | ||||||
|  | 	sub.htracer = htracer | ||||||
|  |  | ||||||
|  | 	go sub.poll(ctx) | ||||||
|  |  | ||||||
|  | 	k.mu.Lock() | ||||||
|  | 	k.subs = append(k.subs, sub) | ||||||
|  | 	k.mu.Unlock() | ||||||
|  | 	return sub, nil | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (k *Broker) String() string { | ||||||
|  | 	return "kgo" | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func NewBroker(opts ...broker.Option) *Broker { | ||||||
|  | 	options := broker.NewOptions(opts...) | ||||||
|  |  | ||||||
|  | 	kaddrs := options.Addrs | ||||||
| 	// shuffle addrs | 	// shuffle addrs | ||||||
| 	var rng mrand.Rand | 	var rng mrand.Rand | ||||||
| 	rng.Shuffle(len(kaddrs), func(i, j int) { | 	rng.Shuffle(len(kaddrs), func(i, j int) { | ||||||
| 		kaddrs[i], kaddrs[j] = kaddrs[j], kaddrs[i] | 		kaddrs[i], kaddrs[j] = kaddrs[j], kaddrs[i] | ||||||
| 	}) | 	}) | ||||||
|  |  | ||||||
| 	td := DefaultCommitInterval |  | ||||||
| 	if k.opts.Context != nil { |  | ||||||
| 		if v, ok := k.opts.Context.Value(commitIntervalKey{}).(time.Duration); ok && v > 0 { |  | ||||||
| 			td = v |  | ||||||
| 		} |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	sub := &subscriber{ |  | ||||||
| 		topic:     topic, |  | ||||||
| 		done:      make(chan struct{}), |  | ||||||
| 		opts:      options, |  | ||||||
| 		handler:   handler, |  | ||||||
| 		kopts:     k.opts, |  | ||||||
| 		consumers: make(map[string]map[int32]worker), |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	kopts := append(k.kopts, |  | ||||||
| 		kgo.SeedBrokers(kaddrs...), |  | ||||||
| 		kgo.ConsumerGroup(options.Group), |  | ||||||
| 		kgo.ConsumeTopics(topic), |  | ||||||
| 		kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()), |  | ||||||
| 		kgo.FetchMaxWait(1*time.Second), |  | ||||||
| 		// kgo.KeepControlRecords(), |  | ||||||
| 		kgo.Balancers(kgo.CooperativeStickyBalancer(), kgo.StickyBalancer()), |  | ||||||
| 		kgo.FetchIsolationLevel(kgo.ReadUncommitted()), |  | ||||||
| 		kgo.WithHooks(&metrics{meter: k.opts.Meter}), |  | ||||||
| 		kgo.AutoCommitMarks(), |  | ||||||
| 		kgo.AutoCommitInterval(td), |  | ||||||
| 		kgo.OnPartitionsAssigned(sub.assigned), |  | ||||||
| 		kgo.OnPartitionsRevoked(sub.revoked), |  | ||||||
| 		kgo.OnPartitionsLost(sub.revoked), |  | ||||||
| 	) |  | ||||||
|  |  | ||||||
| 	reader, err := kgo.NewClient(kopts...) |  | ||||||
| 	if err != nil { |  | ||||||
| 		return nil, err |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	sub.reader = reader |  | ||||||
| 	go sub.run(ctx) |  | ||||||
|  |  | ||||||
| 	k.Lock() |  | ||||||
| 	k.subs = append(k.subs, sub) |  | ||||||
| 	k.Unlock() |  | ||||||
| 	return sub, nil |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (k *kBroker) String() string { |  | ||||||
| 	return "kgo" |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func NewBroker(opts ...broker.Option) *kBroker { |  | ||||||
| 	options := broker.NewOptions(opts...) |  | ||||||
| 	if options.Codec.String() != "noop" { |  | ||||||
| 		options.Logger.Infof(options.Context, "broker codec not noop, disable plain kafka headers usage") |  | ||||||
| 	} |  | ||||||
| 	kopts := []kgo.Opt{ | 	kopts := []kgo.Opt{ | ||||||
|  | 		kgo.DialTimeout(3 * time.Second), | ||||||
| 		kgo.DisableIdempotentWrite(), | 		kgo.DisableIdempotentWrite(), | ||||||
| 		kgo.ProducerBatchCompression(kgo.NoCompression()), | 		kgo.ProducerBatchCompression(kgo.NoCompression()), | ||||||
| 		kgo.WithLogger(&mlogger{l: options.Logger, ctx: options.Context}), | 		kgo.WithLogger(&mlogger{l: options.Logger.Clone(logger.WithAddCallerSkipCount(2)), ctx: options.Context}), | ||||||
| 		kgo.RetryBackoffFn( | 		kgo.SeedBrokers(kaddrs...), | ||||||
| 			func() func(int) time.Duration { | 		kgo.RetryBackoffFn(DefaultRetryBackoffFn), | ||||||
| 				var rng mrand.Rand | 		kgo.BlockRebalanceOnPoll(), | ||||||
| 				return func(fails int) time.Duration { | 		kgo.Balancers(kgo.CooperativeStickyBalancer()), | ||||||
| 					const ( | 		kgo.FetchIsolationLevel(kgo.ReadUncommitted()), | ||||||
| 						min = 250 * time.Millisecond | 		kgo.UnknownTopicRetries(1), | ||||||
| 						max = 2 * time.Second |  | ||||||
| 					) |  | ||||||
| 					if fails <= 0 { |  | ||||||
| 						return min |  | ||||||
| 					} |  | ||||||
| 					if fails > 10 { |  | ||||||
| 						return max |  | ||||||
| 					} |  | ||||||
|  |  | ||||||
| 					backoff := min * time.Duration(1<<(fails-1)) |  | ||||||
| 					jitter := 0.8 + 0.4*rng.Float64() |  | ||||||
| 					backoff = time.Duration(float64(backoff) * jitter) |  | ||||||
|  |  | ||||||
| 					if backoff > max { |  | ||||||
| 						return max |  | ||||||
| 					} |  | ||||||
| 					return backoff |  | ||||||
| 				} |  | ||||||
| 			}(), |  | ||||||
| 		), |  | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	if options.Context != nil { | 	if options.Context != nil { | ||||||
| @@ -439,8 +557,10 @@ func NewBroker(opts ...broker.Option) *kBroker { | |||||||
| 		} | 		} | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	return &kBroker{ | 	return &Broker{ | ||||||
| 		opts:  options, | 		connected: &atomic.Uint32{}, | ||||||
| 		kopts: kopts, | 		opts:      options, | ||||||
|  | 		kopts:     kopts, | ||||||
|  | 		done:      make(chan struct{}), | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
|   | |||||||
							
								
								
									
										122
									
								
								kgo_test.go
									
									
									
									
									
								
							
							
						
						
									
										122
									
								
								kgo_test.go
									
									
									
									
									
								
							| @@ -2,7 +2,6 @@ package kgo_test | |||||||
|  |  | ||||||
| import ( | import ( | ||||||
| 	"context" | 	"context" | ||||||
| 	"fmt" |  | ||||||
| 	"os" | 	"os" | ||||||
| 	"strings" | 	"strings" | ||||||
| 	"sync/atomic" | 	"sync/atomic" | ||||||
| @@ -13,14 +12,15 @@ import ( | |||||||
| 	kgo "go.unistack.org/micro-broker-kgo/v3" | 	kgo "go.unistack.org/micro-broker-kgo/v3" | ||||||
| 	"go.unistack.org/micro/v3/broker" | 	"go.unistack.org/micro/v3/broker" | ||||||
| 	"go.unistack.org/micro/v3/logger" | 	"go.unistack.org/micro/v3/logger" | ||||||
|  | 	"go.unistack.org/micro/v3/logger/slog" | ||||||
| 	"go.unistack.org/micro/v3/metadata" | 	"go.unistack.org/micro/v3/metadata" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| var ( | var ( | ||||||
| 	msgcnt   = int64(12000000) | 	msgcnt   = int64(1200) | ||||||
| 	group    = "38" | 	group    = "38" | ||||||
| 	prefill  = false | 	prefill  = true | ||||||
| 	loglevel = logger.InfoLevel | 	loglevel = logger.DebugLevel | ||||||
| ) | ) | ||||||
|  |  | ||||||
| var bm = &broker.Message{ | var bm = &broker.Message{ | ||||||
| @@ -28,12 +28,121 @@ var bm = &broker.Message{ | |||||||
| 	Body:   []byte(`"body"`), | 	Body:   []byte(`"body"`), | ||||||
| } | } | ||||||
|  |  | ||||||
|  | func TestFail(t *testing.T) { | ||||||
|  | 	if tr := os.Getenv("INTEGRATION_TESTS"); len(tr) > 0 { | ||||||
|  | 		t.Skip() | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	logger.DefaultLogger = slog.NewLogger() | ||||||
|  | 	if err := logger.DefaultLogger.Init(logger.WithLevel(loglevel)); err != nil { | ||||||
|  | 		t.Fatal(err) | ||||||
|  | 	} | ||||||
|  | 	ctx := context.Background() | ||||||
|  |  | ||||||
|  | 	var addrs []string | ||||||
|  | 	if addr := os.Getenv("BROKER_ADDRS"); len(addr) == 0 { | ||||||
|  | 		addrs = []string{"127.0.0.1:9092"} | ||||||
|  | 	} else { | ||||||
|  | 		addrs = strings.Split(addr, ",") | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	b := kgo.NewBroker( | ||||||
|  | 		broker.Addrs(addrs...), | ||||||
|  | 		kgo.CommitInterval(5*time.Second), | ||||||
|  | 		kgo.Options(kg.ClientID("test"), kg.FetchMaxBytes(10*1024*1024), | ||||||
|  | 			kg.AllowAutoTopicCreation(), | ||||||
|  | 		), | ||||||
|  | 	) | ||||||
|  |  | ||||||
|  | 	t.Logf("broker init") | ||||||
|  | 	if err := b.Init(); err != nil { | ||||||
|  | 		t.Fatal(err) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	t.Logf("broker connect") | ||||||
|  | 	if err := b.Connect(ctx); err != nil { | ||||||
|  | 		t.Fatal(err) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	defer func() { | ||||||
|  | 		t.Logf("broker disconnect") | ||||||
|  | 		if err := b.Disconnect(ctx); err != nil { | ||||||
|  | 			t.Fatal(err) | ||||||
|  | 		} | ||||||
|  | 	}() | ||||||
|  |  | ||||||
|  | 	t.Logf("broker health %v", b.Health()) | ||||||
|  | 	msgs := make([]*broker.Message, 0, msgcnt) | ||||||
|  | 	for i := int64(0); i < msgcnt; i++ { | ||||||
|  | 		msgs = append(msgs, bm) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	for _, msg := range msgs { | ||||||
|  | 		t.Logf("broker publish") | ||||||
|  | 		if err := b.Publish(ctx, "test", msg); err != nil { | ||||||
|  | 			t.Fatal(err) | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  | 	//	t.Skip() | ||||||
|  |  | ||||||
|  | 	idx := int64(0) | ||||||
|  | 	fn := func(msg broker.Event) error { | ||||||
|  | 		atomic.AddInt64(&idx, 1) | ||||||
|  | 		time.Sleep(500 * time.Millisecond) | ||||||
|  | 		t.Logf("ack") | ||||||
|  | 		return msg.Ack() | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	sub, err := b.Subscribe(ctx, "test", fn, | ||||||
|  | 		broker.SubscribeAutoAck(true), | ||||||
|  | 		broker.SubscribeGroup(group), | ||||||
|  | 		broker.SubscribeBodyOnly(true)) | ||||||
|  | 	if err != nil { | ||||||
|  | 		t.Fatal(err) | ||||||
|  | 	} | ||||||
|  | 	defer func() { | ||||||
|  | 		if err := sub.Unsubscribe(ctx); err != nil { | ||||||
|  | 			t.Fatal(err) | ||||||
|  | 		} | ||||||
|  | 	}() | ||||||
|  |  | ||||||
|  | 	for { | ||||||
|  | 		t.Logf("health check") | ||||||
|  | 		if !b.Health() { | ||||||
|  | 			t.Logf("health works") | ||||||
|  | 			break | ||||||
|  | 		} | ||||||
|  | 		time.Sleep(1 * time.Second) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func TestConnect(t *testing.T) { | ||||||
|  | 	if tr := os.Getenv("INTEGRATION_TESTS"); len(tr) > 0 { | ||||||
|  | 		t.Skip() | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	var addrs []string | ||||||
|  | 	ctx := context.TODO() | ||||||
|  | 	b := kgo.NewBroker( | ||||||
|  | 		broker.Addrs(addrs...), | ||||||
|  | 		kgo.CommitInterval(5*time.Second), | ||||||
|  | 		kgo.Options(kg.ClientID("test"), kg.FetchMaxBytes(10*1024*1024)), | ||||||
|  | 	) | ||||||
|  | 	if err := b.Init(); err != nil { | ||||||
|  | 		t.Fatal(err) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	if err := b.Connect(ctx); err != nil { | ||||||
|  | 		t.Fatal(err) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
| func TestPubSub(t *testing.T) { | func TestPubSub(t *testing.T) { | ||||||
| 	if tr := os.Getenv("INTEGRATION_TESTS"); len(tr) > 0 { | 	if tr := os.Getenv("INTEGRATION_TESTS"); len(tr) > 0 { | ||||||
| 		t.Skip() | 		t.Skip() | ||||||
| 	} | 	} | ||||||
|  |  | ||||||
| 	if err := logger.DefaultLogger.Init(logger.WithLevel(loglevel), logger.WithCallerSkipCount(3)); err != nil { | 	if err := logger.DefaultLogger.Init(logger.WithLevel(loglevel)); err != nil { | ||||||
| 		t.Fatal(err) | 		t.Fatal(err) | ||||||
| 	} | 	} | ||||||
| 	ctx := context.Background() | 	ctx := context.Background() | ||||||
| @@ -50,6 +159,7 @@ func TestPubSub(t *testing.T) { | |||||||
| 		kgo.CommitInterval(5*time.Second), | 		kgo.CommitInterval(5*time.Second), | ||||||
| 		kgo.Options(kg.ClientID("test"), kg.FetchMaxBytes(10*1024*1024)), | 		kgo.Options(kg.ClientID("test"), kg.FetchMaxBytes(10*1024*1024)), | ||||||
| 	) | 	) | ||||||
|  |  | ||||||
| 	if err := b.Init(); err != nil { | 	if err := b.Init(); err != nil { | ||||||
| 		t.Fatal(err) | 		t.Fatal(err) | ||||||
| 	} | 	} | ||||||
| @@ -107,7 +217,7 @@ func TestPubSub(t *testing.T) { | |||||||
| 				if prc := atomic.LoadInt64(&idx); prc == msgcnt { | 				if prc := atomic.LoadInt64(&idx); prc == msgcnt { | ||||||
| 					close(done) | 					close(done) | ||||||
| 				} else { | 				} else { | ||||||
| 					fmt.Printf("processed %v\n", prc) | 					t.Logf("processed %v\n", prc) | ||||||
| 				} | 				} | ||||||
| 			case <-ticker.C: | 			case <-ticker.C: | ||||||
| 				close(done) | 				close(done) | ||||||
|   | |||||||
							
								
								
									
										47
									
								
								logger.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										47
									
								
								logger.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,47 @@ | |||||||
|  | package kgo | ||||||
|  |  | ||||||
|  | import ( | ||||||
|  | 	"context" | ||||||
|  |  | ||||||
|  | 	"github.com/twmb/franz-go/pkg/kgo" | ||||||
|  | 	"go.unistack.org/micro/v3/logger" | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | type mlogger struct { | ||||||
|  | 	l   logger.Logger | ||||||
|  | 	ctx context.Context | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (l *mlogger) Log(lvl kgo.LogLevel, msg string, args ...interface{}) { | ||||||
|  | 	var mlvl logger.Level | ||||||
|  | 	switch lvl { | ||||||
|  | 	case kgo.LogLevelNone: | ||||||
|  | 		return | ||||||
|  | 	case kgo.LogLevelError: | ||||||
|  | 		mlvl = logger.ErrorLevel | ||||||
|  | 	case kgo.LogLevelWarn: | ||||||
|  | 		mlvl = logger.WarnLevel | ||||||
|  | 	case kgo.LogLevelInfo: | ||||||
|  | 		mlvl = logger.InfoLevel | ||||||
|  | 	case kgo.LogLevelDebug: | ||||||
|  | 		mlvl = logger.DebugLevel | ||||||
|  | 	default: | ||||||
|  | 		return | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	l.l.Log(l.ctx, mlvl, msg, args...) | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (l *mlogger) Level() kgo.LogLevel { | ||||||
|  | 	switch l.l.Options().Level { | ||||||
|  | 	case logger.ErrorLevel: | ||||||
|  | 		return kgo.LogLevelError | ||||||
|  | 	case logger.WarnLevel: | ||||||
|  | 		return kgo.LogLevelWarn | ||||||
|  | 	case logger.InfoLevel: | ||||||
|  | 		return kgo.LogLevelInfo | ||||||
|  | 	case logger.DebugLevel, logger.TraceLevel: | ||||||
|  | 		return kgo.LogLevelDebug | ||||||
|  | 	} | ||||||
|  | 	return kgo.LogLevelNone | ||||||
|  | } | ||||||
							
								
								
									
										120
									
								
								meter.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										120
									
								
								meter.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,120 @@ | |||||||
|  | package kgo | ||||||
|  |  | ||||||
|  | import ( | ||||||
|  | 	"net" | ||||||
|  | 	"strconv" | ||||||
|  | 	"time" | ||||||
|  |  | ||||||
|  | 	"github.com/twmb/franz-go/pkg/kgo" | ||||||
|  | 	"go.unistack.org/micro/v3/meter" | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | type hookMeter struct { | ||||||
|  | 	meter meter.Meter | ||||||
|  | } | ||||||
|  |  | ||||||
|  | var ( | ||||||
|  | 	_ kgo.HookBrokerConnect    = &hookMeter{} | ||||||
|  | 	_ kgo.HookBrokerDisconnect = &hookMeter{} | ||||||
|  | 	// HookBrokerE2E | ||||||
|  | 	_ kgo.HookBrokerRead     = &hookMeter{} | ||||||
|  | 	_ kgo.HookBrokerThrottle = &hookMeter{} | ||||||
|  | 	_ kgo.HookBrokerWrite    = &hookMeter{} | ||||||
|  | 	_ kgo.HookFetchBatchRead = &hookMeter{} | ||||||
|  | 	// HookFetchRecordBuffered | ||||||
|  | 	// HookFetchRecordUnbuffered | ||||||
|  | 	_ kgo.HookGroupManageError = &hookMeter{} | ||||||
|  | 	// HookNewClient | ||||||
|  | 	_ kgo.HookProduceBatchWritten = &hookMeter{} | ||||||
|  | 	// HookProduceRecordBuffered | ||||||
|  | 	// HookProduceRecordPartitioned | ||||||
|  | 	// HookProduceRecordUnbuffered | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | const ( | ||||||
|  | 	metricBrokerConnects    = "micro_broker_connects_total" | ||||||
|  | 	metricBrokerDisconnects = "micro_broker_disconnects_total" | ||||||
|  |  | ||||||
|  | 	metricBrokerWriteErrors        = "micro_broker_write_errors_total" | ||||||
|  | 	metricBrokerWriteBytes         = "micro_broker_write_bytes_total" | ||||||
|  | 	metricBrokerWriteWaitLatencies = "micro_broker_write_wait_latencies" | ||||||
|  | 	metricBrokerWriteLatencies     = "micro_broker_write_latencies" | ||||||
|  |  | ||||||
|  | 	metricBrokerReadErrors        = "micro_broker_read_errors_total" | ||||||
|  | 	metricBrokerReadBytes         = "micro_broker_read_bytes_total" | ||||||
|  | 	metricBrokerReadWaitLatencies = "micro_broker_read_wait_latencies" | ||||||
|  | 	metricBrokerReadLatencies     = "micro_broker_read_latencies" | ||||||
|  |  | ||||||
|  | 	metricBrokerThrottleLatencies = "micro_broker_throttle_latencies" | ||||||
|  |  | ||||||
|  | 	metricBrokerProduceBytesCompressed   = "micro_broker_produce_bytes_compressed_total" | ||||||
|  | 	metricBrokerProduceBytesUncompressed = "micro_broker_produce_bytes_uncompressed_total" | ||||||
|  | 	metricBrokerFetchBytesCompressed     = "micro_broker_consume_bytes_compressed_total" | ||||||
|  | 	metricBrokerFetchBytesUncompressed   = "micro_broker_consume_bytes_uncompressed_total" | ||||||
|  |  | ||||||
|  | 	metricBrokerGroupErrors = "micro_broker_group_errors_total" | ||||||
|  |  | ||||||
|  | 	labelNode    = "node_id" | ||||||
|  | 	labelSuccess = "success" | ||||||
|  | 	labelFaulure = "failure" | ||||||
|  | 	labelStatus  = "status" | ||||||
|  | 	labelTopic   = "topic" | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | func (m *hookMeter) OnGroupManageError(_ error) { | ||||||
|  | 	m.meter.Counter(metricBrokerGroupErrors).Inc() | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *hookMeter) OnBrokerConnect(meta kgo.BrokerMetadata, _ time.Duration, _ net.Conn, err error) { | ||||||
|  | 	node := strconv.Itoa(int(meta.NodeID)) | ||||||
|  | 	if err != nil { | ||||||
|  | 		m.meter.Counter(metricBrokerConnects, labelNode, node, labelStatus, labelFaulure).Inc() | ||||||
|  | 		return | ||||||
|  | 	} | ||||||
|  | 	m.meter.Counter(metricBrokerConnects, labelNode, node, labelStatus, labelSuccess).Inc() | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *hookMeter) OnBrokerDisconnect(meta kgo.BrokerMetadata, _ net.Conn) { | ||||||
|  | 	node := strconv.Itoa(int(meta.NodeID)) | ||||||
|  | 	m.meter.Counter(metricBrokerDisconnects, labelNode, node).Inc() | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *hookMeter) OnBrokerWrite(meta kgo.BrokerMetadata, _ int16, bytesWritten int, writeWait, timeToWrite time.Duration, err error) { | ||||||
|  | 	node := strconv.Itoa(int(meta.NodeID)) | ||||||
|  | 	if err != nil { | ||||||
|  | 		m.meter.Counter(metricBrokerWriteErrors, labelNode, node).Inc() | ||||||
|  | 		return | ||||||
|  | 	} | ||||||
|  | 	m.meter.Counter(metricBrokerWriteBytes, labelNode, node).Add(bytesWritten) | ||||||
|  | 	m.meter.Histogram(metricBrokerWriteWaitLatencies, labelNode, node).Update(writeWait.Seconds()) | ||||||
|  | 	m.meter.Histogram(metricBrokerWriteLatencies, labelNode, node).Update(timeToWrite.Seconds()) | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *hookMeter) OnBrokerRead(meta kgo.BrokerMetadata, _ int16, bytesRead int, readWait, timeToRead time.Duration, err error) { | ||||||
|  | 	node := strconv.Itoa(int(meta.NodeID)) | ||||||
|  | 	if err != nil { | ||||||
|  | 		m.meter.Counter(metricBrokerReadErrors, labelNode, node).Inc() | ||||||
|  | 		return | ||||||
|  | 	} | ||||||
|  | 	m.meter.Counter(metricBrokerReadBytes, labelNode, node).Add(bytesRead) | ||||||
|  |  | ||||||
|  | 	m.meter.Histogram(metricBrokerReadWaitLatencies, labelNode, node).Update(readWait.Seconds()) | ||||||
|  | 	m.meter.Histogram(metricBrokerReadLatencies, labelNode, node).Update(timeToRead.Seconds()) | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *hookMeter) OnBrokerThrottle(meta kgo.BrokerMetadata, throttleInterval time.Duration, _ bool) { | ||||||
|  | 	node := strconv.Itoa(int(meta.NodeID)) | ||||||
|  | 	m.meter.Histogram(metricBrokerThrottleLatencies, labelNode, node).Update(throttleInterval.Seconds()) | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *hookMeter) OnProduceBatchWritten(meta kgo.BrokerMetadata, topic string, _ int32, kmetrics kgo.ProduceBatchMetrics) { | ||||||
|  | 	node := strconv.Itoa(int(meta.NodeID)) | ||||||
|  | 	m.meter.Counter(metricBrokerProduceBytesUncompressed, labelNode, node, labelTopic, topic).Add(kmetrics.UncompressedBytes) | ||||||
|  | 	m.meter.Counter(metricBrokerProduceBytesCompressed, labelNode, node, labelTopic, topic).Add(kmetrics.CompressedBytes) | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (m *hookMeter) OnFetchBatchRead(meta kgo.BrokerMetadata, topic string, _ int32, kmetrics kgo.FetchBatchMetrics) { | ||||||
|  | 	node := strconv.Itoa(int(meta.NodeID)) | ||||||
|  | 	m.meter.Counter(metricBrokerFetchBytesUncompressed, labelNode, node, labelTopic, topic).Add(kmetrics.UncompressedBytes) | ||||||
|  | 	m.meter.Counter(metricBrokerFetchBytesCompressed, labelNode, node, labelTopic, topic).Add(kmetrics.CompressedBytes) | ||||||
|  | } | ||||||
							
								
								
									
										113
									
								
								metrics.go
									
									
									
									
									
								
							
							
						
						
									
										113
									
								
								metrics.go
									
									
									
									
									
								
							| @@ -1,113 +0,0 @@ | |||||||
| package kgo |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	"net" |  | ||||||
| 	"strconv" |  | ||||||
| 	"time" |  | ||||||
|  |  | ||||||
| 	"github.com/twmb/franz-go/pkg/kgo" |  | ||||||
| 	"go.unistack.org/micro/v3/meter" |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| type metrics struct { |  | ||||||
| 	meter meter.Meter |  | ||||||
| } |  | ||||||
|  |  | ||||||
| var ( |  | ||||||
| 	_ kgo.HookBrokerConnect       = &metrics{} |  | ||||||
| 	_ kgo.HookBrokerDisconnect    = &metrics{} |  | ||||||
| 	_ kgo.HookBrokerRead          = &metrics{} |  | ||||||
| 	_ kgo.HookBrokerThrottle      = &metrics{} |  | ||||||
| 	_ kgo.HookBrokerWrite         = &metrics{} |  | ||||||
| 	_ kgo.HookFetchBatchRead      = &metrics{} |  | ||||||
| 	_ kgo.HookProduceBatchWritten = &metrics{} |  | ||||||
| 	_ kgo.HookGroupManageError    = &metrics{} |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| const ( |  | ||||||
| 	metricBrokerConnects    = "broker_connects_total" |  | ||||||
| 	metricBrokerDisconnects = "broker_disconnects_total" |  | ||||||
|  |  | ||||||
| 	metricBrokerWriteErrors        = "broker_write_errors_total" |  | ||||||
| 	metricBrokerWriteBytes         = "broker_write_bytes_total" |  | ||||||
| 	metricBrokerWriteWaitLatencies = "broker_write_wait_latencies" |  | ||||||
| 	metricBrokerWriteLatencies     = "broker_write_latencies" |  | ||||||
|  |  | ||||||
| 	metricBrokerReadErrors        = "broker_read_errors_total" |  | ||||||
| 	metricBrokerReadBytes         = "broker_read_bytes_total" |  | ||||||
| 	metricBrokerReadWaitLatencies = "broker_read_wait_latencies" |  | ||||||
| 	metricBrokerReadLatencies     = "broker_read_latencies" |  | ||||||
|  |  | ||||||
| 	metricBrokerThrottleLatencies = "broker_throttle_latencies" |  | ||||||
|  |  | ||||||
| 	metricBrokerProduceBytesCompressed   = "broker_produce_bytes_compressed_total" |  | ||||||
| 	metricBrokerProduceBytesUncompressed = "broker_produce_bytes_uncompressed_total" |  | ||||||
| 	metricBrokerFetchBytesCompressed     = "broker_consume_bytes_compressed_total" |  | ||||||
| 	metricBrokerFetchBytesUncompressed   = "broker_consume_bytes_uncompressed_total" |  | ||||||
|  |  | ||||||
| 	metricBrokerGroupErrors = "broker_group_errors_total" |  | ||||||
|  |  | ||||||
| 	labelNode    = "node_id" |  | ||||||
| 	labelSuccess = "success" |  | ||||||
| 	labelFaulure = "failure" |  | ||||||
| 	labelStatus  = "status" |  | ||||||
| 	labelTopic   = "topic" |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| func (m *metrics) OnGroupManageError(err error) { |  | ||||||
| 	m.meter.Counter(metricBrokerGroupErrors).Inc() |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (m *metrics) OnBrokerConnect(meta kgo.BrokerMetadata, _ time.Duration, _ net.Conn, err error) { |  | ||||||
| 	node := strconv.Itoa(int(meta.NodeID)) |  | ||||||
| 	if err != nil { |  | ||||||
| 		m.meter.Counter(metricBrokerConnects, labelNode, node, labelStatus, labelFaulure).Inc() |  | ||||||
| 		return |  | ||||||
| 	} |  | ||||||
| 	m.meter.Counter(metricBrokerConnects, labelNode, node, labelStatus, labelSuccess).Inc() |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (m *metrics) OnBrokerDisconnect(meta kgo.BrokerMetadata, _ net.Conn) { |  | ||||||
| 	node := strconv.Itoa(int(meta.NodeID)) |  | ||||||
| 	m.meter.Counter(metricBrokerDisconnects, labelNode, node).Inc() |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (m *metrics) OnBrokerWrite(meta kgo.BrokerMetadata, _ int16, bytesWritten int, writeWait, timeToWrite time.Duration, err error) { |  | ||||||
| 	node := strconv.Itoa(int(meta.NodeID)) |  | ||||||
| 	if err != nil { |  | ||||||
| 		m.meter.Counter(metricBrokerWriteErrors, labelNode, node).Inc() |  | ||||||
| 		return |  | ||||||
| 	} |  | ||||||
| 	m.meter.Counter(metricBrokerWriteBytes, labelNode, node).Add(bytesWritten) |  | ||||||
| 	m.meter.Histogram(metricBrokerWriteWaitLatencies, labelNode, node).Update(writeWait.Seconds()) |  | ||||||
| 	m.meter.Histogram(metricBrokerWriteLatencies, labelNode, node).Update(timeToWrite.Seconds()) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (m *metrics) OnBrokerRead(meta kgo.BrokerMetadata, _ int16, bytesRead int, readWait, timeToRead time.Duration, err error) { |  | ||||||
| 	node := strconv.Itoa(int(meta.NodeID)) |  | ||||||
| 	if err != nil { |  | ||||||
| 		m.meter.Counter(metricBrokerReadErrors, labelNode, node).Inc() |  | ||||||
| 		return |  | ||||||
| 	} |  | ||||||
| 	m.meter.Counter(metricBrokerReadBytes, labelNode, node).Add(bytesRead) |  | ||||||
|  |  | ||||||
| 	m.meter.Histogram(metricBrokerReadWaitLatencies, labelNode, node).Update(readWait.Seconds()) |  | ||||||
| 	m.meter.Histogram(metricBrokerReadLatencies, labelNode, node).Update(timeToRead.Seconds()) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (m *metrics) OnBrokerThrottle(meta kgo.BrokerMetadata, throttleInterval time.Duration, _ bool) { |  | ||||||
| 	node := strconv.Itoa(int(meta.NodeID)) |  | ||||||
| 	m.meter.Histogram(metricBrokerThrottleLatencies, labelNode, node).Update(throttleInterval.Seconds()) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (m *metrics) OnProduceBatchWritten(meta kgo.BrokerMetadata, topic string, _ int32, kmetrics kgo.ProduceBatchMetrics) { |  | ||||||
| 	node := strconv.Itoa(int(meta.NodeID)) |  | ||||||
| 	m.meter.Counter(metricBrokerProduceBytesUncompressed, labelNode, node, labelTopic, topic).Add(kmetrics.UncompressedBytes) |  | ||||||
| 	m.meter.Counter(metricBrokerProduceBytesCompressed, labelNode, node, labelTopic, topic).Add(kmetrics.CompressedBytes) |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (m *metrics) OnFetchBatchRead(meta kgo.BrokerMetadata, topic string, _ int32, kmetrics kgo.FetchBatchMetrics) { |  | ||||||
| 	node := strconv.Itoa(int(meta.NodeID)) |  | ||||||
| 	m.meter.Counter(metricBrokerFetchBytesUncompressed, labelNode, node, labelTopic, topic).Add(kmetrics.UncompressedBytes) |  | ||||||
| 	m.meter.Counter(metricBrokerFetchBytesCompressed, labelNode, node, labelTopic, topic).Add(kmetrics.CompressedBytes) |  | ||||||
| } |  | ||||||
							
								
								
									
										76
									
								
								options.go
									
									
									
									
									
								
							
							
						
						
									
										76
									
								
								options.go
									
									
									
									
									
								
							| @@ -4,13 +4,22 @@ import ( | |||||||
| 	"context" | 	"context" | ||||||
| 	"time" | 	"time" | ||||||
|  |  | ||||||
| 	kgo "github.com/twmb/franz-go/pkg/kgo" | 	"github.com/twmb/franz-go/pkg/kgo" | ||||||
| 	"go.unistack.org/micro/v3/broker" | 	"go.unistack.org/micro/v3/broker" | ||||||
| 	"go.unistack.org/micro/v3/client" | 	"go.unistack.org/micro/v3/client" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| // DefaultCommitInterval specifies how fast send commit offsets to kafka | var ( | ||||||
| var DefaultCommitInterval = 5 * time.Second |  | ||||||
|  | 	// DefaultCommitInterval specifies how fast send commit offsets to kafka | ||||||
|  | 	DefaultCommitInterval = 5 * time.Second | ||||||
|  |  | ||||||
|  | 	// DefaultStatsInterval specifies how fast check consumer lag | ||||||
|  | 	DefaultStatsInterval = 30 * time.Second | ||||||
|  |  | ||||||
|  | 	// DefaultSubscribeMaxInflight specifies how much messages keep inflight | ||||||
|  | 	DefaultSubscribeMaxInflight = 100 | ||||||
|  | ) | ||||||
|  |  | ||||||
| type subscribeContextKey struct{} | type subscribeContextKey struct{} | ||||||
|  |  | ||||||
| @@ -48,6 +57,39 @@ func Options(opts ...kgo.Opt) broker.Option { | |||||||
| 	} | 	} | ||||||
| } | } | ||||||
|  |  | ||||||
|  | // SubscribeOptions pass additional options to broker in Subscribe | ||||||
|  | func SubscribeOptions(opts ...kgo.Opt) broker.SubscribeOption { | ||||||
|  | 	return func(o *broker.SubscribeOptions) { | ||||||
|  | 		if o.Context == nil { | ||||||
|  | 			o.Context = context.Background() | ||||||
|  | 		} | ||||||
|  | 		options, ok := o.Context.Value(optionsKey{}).([]kgo.Opt) | ||||||
|  | 		if !ok { | ||||||
|  | 			options = make([]kgo.Opt, 0, len(opts)) | ||||||
|  | 		} | ||||||
|  | 		options = append(options, opts...) | ||||||
|  | 		o.Context = context.WithValue(o.Context, optionsKey{}, options) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | type fatalOnErrorKey struct{} | ||||||
|  |  | ||||||
|  | func FatalOnError(b bool) broker.Option { | ||||||
|  | 	return broker.SetOption(fatalOnErrorKey{}, b) | ||||||
|  | } | ||||||
|  |  | ||||||
|  | type clientIDKey struct{} | ||||||
|  |  | ||||||
|  | func ClientID(id string) broker.Option { | ||||||
|  | 	return broker.SetOption(clientIDKey{}, id) | ||||||
|  | } | ||||||
|  |  | ||||||
|  | type groupKey struct{} | ||||||
|  |  | ||||||
|  | func Group(id string) broker.Option { | ||||||
|  | 	return broker.SetOption(groupKey{}, id) | ||||||
|  | } | ||||||
|  |  | ||||||
| type commitIntervalKey struct{} | type commitIntervalKey struct{} | ||||||
|  |  | ||||||
| // CommitInterval specifies interval to send commits | // CommitInterval specifies interval to send commits | ||||||
| @@ -55,11 +97,33 @@ func CommitInterval(td time.Duration) broker.Option { | |||||||
| 	return broker.SetOption(commitIntervalKey{}, td) | 	return broker.SetOption(commitIntervalKey{}, td) | ||||||
| } | } | ||||||
|  |  | ||||||
| var DefaultSubscribeMaxInflight = 1000 |  | ||||||
|  |  | ||||||
| type subscribeMaxInflightKey struct{} | type subscribeMaxInflightKey struct{} | ||||||
|  |  | ||||||
| // SubscribeMaxInFlight specifies interval to send commits | // SubscribeMaxInFlight max queued messages | ||||||
| func SubscribeMaxInFlight(n int) broker.SubscribeOption { | func SubscribeMaxInFlight(n int) broker.SubscribeOption { | ||||||
| 	return broker.SetSubscribeOption(subscribeMaxInflightKey{}, n) | 	return broker.SetSubscribeOption(subscribeMaxInflightKey{}, n) | ||||||
| } | } | ||||||
|  |  | ||||||
|  | // SubscribeMaxInFlight max queued messages | ||||||
|  | func SubscribeFatalOnError(b bool) broker.SubscribeOption { | ||||||
|  | 	return broker.SetSubscribeOption(fatalOnErrorKey{}, b) | ||||||
|  | } | ||||||
|  |  | ||||||
|  | type publishPromiseKey struct{} | ||||||
|  |  | ||||||
|  | // PublishPromise set the kafka promise func for Produce | ||||||
|  | func PublishPromise(fn func(*kgo.Record, error)) broker.PublishOption { | ||||||
|  | 	return broker.SetPublishOption(publishPromiseKey{}, fn) | ||||||
|  | } | ||||||
|  |  | ||||||
|  | // ClientPublishKey set the kafka message key (client option) | ||||||
|  | func ClientPublishPromise(fn func(*kgo.Record, error)) client.PublishOption { | ||||||
|  | 	return client.SetPublishOption(publishPromiseKey{}, fn) | ||||||
|  | } | ||||||
|  |  | ||||||
|  | type exposeLagKey struct{} | ||||||
|  |  | ||||||
|  | // ExposeLag enabled subscriber lag via [meter.Meter] | ||||||
|  | func ExposeLag(b bool) broker.Option { | ||||||
|  | 	return broker.SetOption(exposeLagKey{}, b) | ||||||
|  | } | ||||||
|   | |||||||
							
								
								
									
										348
									
								
								subscriber.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										348
									
								
								subscriber.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,348 @@ | |||||||
|  | package kgo | ||||||
|  |  | ||||||
|  | import ( | ||||||
|  | 	"context" | ||||||
|  | 	"fmt" | ||||||
|  | 	"sync" | ||||||
|  | 	"sync/atomic" | ||||||
|  | 	"time" | ||||||
|  |  | ||||||
|  | 	"github.com/twmb/franz-go/pkg/kgo" | ||||||
|  | 	"github.com/twmb/franz-go/pkg/kmsg" | ||||||
|  | 	"go.unistack.org/micro/v3/broker" | ||||||
|  | 	"go.unistack.org/micro/v3/logger" | ||||||
|  | 	"go.unistack.org/micro/v3/metadata" | ||||||
|  | 	"go.unistack.org/micro/v3/semconv" | ||||||
|  | 	"go.unistack.org/micro/v3/tracer" | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | type tp struct { | ||||||
|  | 	t string | ||||||
|  | 	p int32 | ||||||
|  | } | ||||||
|  |  | ||||||
|  | type consumer struct { | ||||||
|  | 	topic string | ||||||
|  |  | ||||||
|  | 	c         *kgo.Client | ||||||
|  | 	htracer   *hookTracer | ||||||
|  | 	connected *atomic.Uint32 | ||||||
|  |  | ||||||
|  | 	quit chan struct{} | ||||||
|  | 	done chan struct{} | ||||||
|  | 	recs chan kgo.FetchTopicPartition | ||||||
|  |  | ||||||
|  | 	handler broker.Handler | ||||||
|  |  | ||||||
|  | 	kopts broker.Options | ||||||
|  | 	opts  broker.SubscribeOptions | ||||||
|  |  | ||||||
|  | 	partition int32 | ||||||
|  | } | ||||||
|  |  | ||||||
|  | type Subscriber struct { | ||||||
|  | 	topic string | ||||||
|  |  | ||||||
|  | 	consumers map[tp]*consumer | ||||||
|  |  | ||||||
|  | 	c         *kgo.Client | ||||||
|  | 	htracer   *hookTracer | ||||||
|  | 	connected *atomic.Uint32 | ||||||
|  |  | ||||||
|  | 	handler broker.Handler | ||||||
|  |  | ||||||
|  | 	done chan struct{} | ||||||
|  |  | ||||||
|  | 	kopts broker.Options | ||||||
|  | 	opts  broker.SubscribeOptions | ||||||
|  |  | ||||||
|  | 	closed       bool | ||||||
|  | 	fatalOnError bool | ||||||
|  |  | ||||||
|  | 	sync.RWMutex | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (s *Subscriber) Client() *kgo.Client { | ||||||
|  | 	return s.c | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (s *Subscriber) Options() broker.SubscribeOptions { | ||||||
|  | 	return s.opts | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (s *Subscriber) Topic() string { | ||||||
|  | 	return s.topic | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (s *Subscriber) Unsubscribe(ctx context.Context) error { | ||||||
|  | 	if s.closed { | ||||||
|  | 		return nil | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	s.c.PauseFetchTopics(s.topic) | ||||||
|  | 	s.c.CloseAllowingRebalance() | ||||||
|  | 	kc := make(map[string][]int32) | ||||||
|  | 	for ctp := range s.consumers { | ||||||
|  | 		kc[ctp.t] = append(kc[ctp.t], ctp.p) | ||||||
|  | 	} | ||||||
|  | 	s.killConsumers(ctx, kc) | ||||||
|  | 	close(s.done) | ||||||
|  | 	s.closed = true | ||||||
|  | 	s.c.ResumeFetchTopics(s.topic) | ||||||
|  |  | ||||||
|  | 	return nil | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (s *Subscriber) poll(ctx context.Context) { | ||||||
|  | 	maxInflight := DefaultSubscribeMaxInflight | ||||||
|  |  | ||||||
|  | 	if s.opts.Context != nil { | ||||||
|  | 		if n, ok := s.opts.Context.Value(subscribeMaxInflightKey{}).(int); n > 0 && ok { | ||||||
|  | 			maxInflight = n | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	for { | ||||||
|  | 		select { | ||||||
|  | 		case <-ctx.Done(): | ||||||
|  | 			s.c.CloseAllowingRebalance() | ||||||
|  | 			return | ||||||
|  | 		case <-s.done: | ||||||
|  | 			return | ||||||
|  | 		default: | ||||||
|  | 			fetches := s.c.PollRecords(ctx, maxInflight) | ||||||
|  | 			if !s.closed && fetches.IsClientClosed() { | ||||||
|  | 				s.closed = true | ||||||
|  | 				return | ||||||
|  | 			} | ||||||
|  | 			fetches.EachError(func(t string, p int32, err error) { | ||||||
|  | 				if kgo.IsRetryableBrokerErr(err) { | ||||||
|  | 					s.kopts.Logger.Error(ctx, fmt.Sprintf("[kgo] fetch topic %s partition %d error", t, p), err) | ||||||
|  | 				} else { | ||||||
|  | 					s.kopts.Logger.Fatal(ctx, fmt.Sprintf("[kgo] fetch topic %s partition %d error", t, p), err) | ||||||
|  | 				} | ||||||
|  | 			}) | ||||||
|  |  | ||||||
|  | 			fetches.EachPartition(func(p kgo.FetchTopicPartition) { | ||||||
|  | 				tps := tp{p.Topic, p.Partition} | ||||||
|  | 				s.consumers[tps].recs <- p | ||||||
|  | 			}) | ||||||
|  | 			s.c.AllowRebalance() | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (s *Subscriber) killConsumers(ctx context.Context, lost map[string][]int32) { | ||||||
|  | 	var wg sync.WaitGroup | ||||||
|  | 	defer wg.Wait() | ||||||
|  |  | ||||||
|  | 	for topic, partitions := range lost { | ||||||
|  | 		for _, partition := range partitions { | ||||||
|  | 			tps := tp{topic, partition} | ||||||
|  | 			pc, ok := s.consumers[tps] | ||||||
|  | 			if !ok { | ||||||
|  | 				continue | ||||||
|  | 			} | ||||||
|  | 			delete(s.consumers, tps) | ||||||
|  | 			close(pc.quit) | ||||||
|  | 			if s.kopts.Logger.V(logger.DebugLevel) { | ||||||
|  | 				s.kopts.Logger.Debug(ctx, fmt.Sprintf("[kgo] waiting for work to finish topic %s partition %d", topic, partition)) | ||||||
|  | 			} | ||||||
|  | 			wg.Add(1) | ||||||
|  | 			go func() { <-pc.done; wg.Done() }() | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (s *Subscriber) autocommit(_ *kgo.Client, _ *kmsg.OffsetCommitRequest, _ *kmsg.OffsetCommitResponse, err error) { | ||||||
|  | 	if err != nil { | ||||||
|  | 		//		s.connected.Store(0) | ||||||
|  | 		if s.fatalOnError { | ||||||
|  | 			s.kopts.Logger.Fatal(context.TODO(), "kgo.AutoCommitCallback error", err) | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (s *Subscriber) lost(ctx context.Context, _ *kgo.Client, lost map[string][]int32) { | ||||||
|  | 	if s.kopts.Logger.V(logger.ErrorLevel) { | ||||||
|  | 		s.kopts.Logger.Error(ctx, fmt.Sprintf("[kgo] lost %#+v", lost)) | ||||||
|  | 	} | ||||||
|  | 	s.killConsumers(ctx, lost) | ||||||
|  | 	// s.connected.Store(0) | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (s *Subscriber) revoked(ctx context.Context, c *kgo.Client, revoked map[string][]int32) { | ||||||
|  | 	if s.kopts.Logger.V(logger.DebugLevel) { | ||||||
|  | 		s.kopts.Logger.Debug(ctx, fmt.Sprintf("[kgo] revoked %#+v", revoked)) | ||||||
|  | 	} | ||||||
|  | 	s.killConsumers(ctx, revoked) | ||||||
|  | 	if err := c.CommitMarkedOffsets(ctx); err != nil { | ||||||
|  | 		s.kopts.Logger.Error(ctx, "[kgo] revoked CommitMarkedOffsets error", err) | ||||||
|  | 		// s.connected.Store(0) | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (s *Subscriber) assigned(_ context.Context, c *kgo.Client, assigned map[string][]int32) { | ||||||
|  | 	for topic, partitions := range assigned { | ||||||
|  | 		for _, partition := range partitions { | ||||||
|  | 			pc := &consumer{ | ||||||
|  | 				c:         c, | ||||||
|  | 				topic:     topic, | ||||||
|  | 				partition: partition, | ||||||
|  | 				htracer:   s.htracer, | ||||||
|  | 				quit:      make(chan struct{}), | ||||||
|  | 				done:      make(chan struct{}), | ||||||
|  | 				recs:      make(chan kgo.FetchTopicPartition, 100), | ||||||
|  | 				handler:   s.handler, | ||||||
|  | 				kopts:     s.kopts, | ||||||
|  | 				opts:      s.opts, | ||||||
|  | 				connected: s.connected, | ||||||
|  | 			} | ||||||
|  | 			s.Lock() | ||||||
|  | 			s.consumers[tp{topic, partition}] = pc | ||||||
|  | 			s.Unlock() | ||||||
|  | 			go pc.consume() | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func (pc *consumer) consume() { | ||||||
|  | 	defer close(pc.done) | ||||||
|  | 	if pc.kopts.Logger.V(logger.DebugLevel) { | ||||||
|  | 		pc.kopts.Logger.Debug(pc.kopts.Context, fmt.Sprintf("starting, topic %s partition %d", pc.topic, pc.partition)) | ||||||
|  | 		defer pc.kopts.Logger.Debug(pc.kopts.Context, fmt.Sprintf("killing, topic %s partition %d", pc.topic, pc.partition)) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	eh := pc.kopts.ErrorHandler | ||||||
|  | 	if pc.opts.ErrorHandler != nil { | ||||||
|  | 		eh = pc.opts.ErrorHandler | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	for { | ||||||
|  | 		select { | ||||||
|  | 		case <-pc.quit: | ||||||
|  | 			return | ||||||
|  | 		case p := <-pc.recs: | ||||||
|  | 			for _, record := range p.Records { | ||||||
|  | 				ctx, sp := pc.htracer.WithProcessSpan(record) | ||||||
|  | 				ts := time.Now() | ||||||
|  | 				pc.kopts.Meter.Counter(semconv.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Inc() | ||||||
|  | 				p := eventPool.Get().(*event) | ||||||
|  | 				p.msg.Header = nil | ||||||
|  | 				p.msg.Body = nil | ||||||
|  | 				p.topic = record.Topic | ||||||
|  | 				p.err = nil | ||||||
|  | 				p.ack = false | ||||||
|  | 				p.msg.Header = metadata.New(len(record.Headers)) | ||||||
|  | 				p.ctx = ctx | ||||||
|  | 				for _, hdr := range record.Headers { | ||||||
|  | 					p.msg.Header.Set(hdr.Key, string(hdr.Value)) | ||||||
|  | 				} | ||||||
|  | 				if pc.kopts.Codec.String() == "noop" { | ||||||
|  | 					p.msg.Body = record.Value | ||||||
|  | 				} else if pc.opts.BodyOnly { | ||||||
|  | 					p.msg.Body = record.Value | ||||||
|  | 				} else { | ||||||
|  | 					if sp != nil { | ||||||
|  | 						sp.AddEvent("codec unmarshal start") | ||||||
|  | 					} | ||||||
|  | 					err := pc.kopts.Codec.Unmarshal(record.Value, p.msg) | ||||||
|  | 					if sp != nil { | ||||||
|  | 						sp.AddEvent("codec unmarshal stop") | ||||||
|  | 					} | ||||||
|  | 					if err != nil { | ||||||
|  | 						if sp != nil { | ||||||
|  | 							sp.SetStatus(tracer.SpanStatusError, err.Error()) | ||||||
|  | 						} | ||||||
|  | 						pc.kopts.Meter.Counter(semconv.SubscribeMessageTotal, "endpoint", record.Topic, "topic", record.Topic, "status", "failure").Inc() | ||||||
|  | 						p.err = err | ||||||
|  | 						p.msg.Body = record.Value | ||||||
|  | 						if eh != nil { | ||||||
|  | 							_ = eh(p) | ||||||
|  | 							pc.kopts.Meter.Counter(semconv.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Dec() | ||||||
|  | 							if p.ack { | ||||||
|  | 								pc.c.MarkCommitRecords(record) | ||||||
|  | 							} else { | ||||||
|  | 								eventPool.Put(p) | ||||||
|  | 								//								pc.connected.Store(0) | ||||||
|  | 								pc.kopts.Logger.Fatal(pc.kopts.Context, "[kgo] ErrLostMessage wtf?") | ||||||
|  | 								return | ||||||
|  | 							} | ||||||
|  | 							eventPool.Put(p) | ||||||
|  | 							te := time.Since(ts) | ||||||
|  | 							pc.kopts.Meter.Summary(semconv.SubscribeMessageLatencyMicroseconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds()) | ||||||
|  | 							pc.kopts.Meter.Histogram(semconv.SubscribeMessageDurationSeconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds()) | ||||||
|  | 							continue | ||||||
|  | 						} else { | ||||||
|  | 							pc.kopts.Logger.Error(pc.kopts.Context, "[kgo]: unmarshal error", err) | ||||||
|  | 						} | ||||||
|  | 						te := time.Since(ts) | ||||||
|  | 						pc.kopts.Meter.Counter(semconv.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Dec() | ||||||
|  | 						pc.kopts.Meter.Summary(semconv.SubscribeMessageLatencyMicroseconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds()) | ||||||
|  | 						pc.kopts.Meter.Histogram(semconv.SubscribeMessageDurationSeconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds()) | ||||||
|  | 						eventPool.Put(p) | ||||||
|  | 						//						pc.connected.Store(0) | ||||||
|  | 						pc.kopts.Logger.Fatal(pc.kopts.Context, "[kgo] Unmarshal err not handled wtf?") | ||||||
|  | 						if sp != nil { | ||||||
|  | 							sp.Finish() | ||||||
|  | 						} | ||||||
|  | 						return | ||||||
|  | 					} | ||||||
|  | 				} | ||||||
|  | 				if sp != nil { | ||||||
|  | 					sp.AddEvent("handler start") | ||||||
|  | 				} | ||||||
|  | 				err := pc.handler(p) | ||||||
|  | 				if sp != nil { | ||||||
|  | 					sp.AddEvent("handler stop") | ||||||
|  | 				} | ||||||
|  | 				if err == nil { | ||||||
|  | 					pc.kopts.Meter.Counter(semconv.SubscribeMessageTotal, "endpoint", record.Topic, "topic", record.Topic, "status", "success").Inc() | ||||||
|  | 				} else { | ||||||
|  | 					if sp != nil { | ||||||
|  | 						sp.SetStatus(tracer.SpanStatusError, err.Error()) | ||||||
|  | 					} | ||||||
|  | 					pc.kopts.Meter.Counter(semconv.SubscribeMessageTotal, "endpoint", record.Topic, "topic", record.Topic, "status", "failure").Inc() | ||||||
|  | 				} | ||||||
|  | 				pc.kopts.Meter.Counter(semconv.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Dec() | ||||||
|  | 				if err == nil && pc.opts.AutoAck { | ||||||
|  | 					p.ack = true | ||||||
|  | 				} else if err != nil { | ||||||
|  | 					p.err = err | ||||||
|  | 					if eh != nil { | ||||||
|  | 						if sp != nil { | ||||||
|  | 							sp.AddEvent("error handler start") | ||||||
|  | 						} | ||||||
|  | 						_ = eh(p) | ||||||
|  | 						if sp != nil { | ||||||
|  | 							sp.AddEvent("error handler stop") | ||||||
|  | 						} | ||||||
|  | 					} else { | ||||||
|  | 						if pc.kopts.Logger.V(logger.ErrorLevel) { | ||||||
|  | 							pc.kopts.Logger.Error(pc.kopts.Context, "[kgo]: subscriber error", err) | ||||||
|  | 						} | ||||||
|  | 					} | ||||||
|  | 				} | ||||||
|  | 				te := time.Since(ts) | ||||||
|  | 				pc.kopts.Meter.Summary(semconv.SubscribeMessageLatencyMicroseconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds()) | ||||||
|  | 				pc.kopts.Meter.Histogram(semconv.SubscribeMessageDurationSeconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds()) | ||||||
|  | 				if p.ack { | ||||||
|  | 					eventPool.Put(p) | ||||||
|  | 					pc.c.MarkCommitRecords(record) | ||||||
|  | 				} else { | ||||||
|  | 					eventPool.Put(p) | ||||||
|  | 					//					pc.connected.Store(0) | ||||||
|  | 					pc.kopts.Logger.Fatal(pc.kopts.Context, "[kgo] ErrLostMessage wtf?") | ||||||
|  | 					if sp != nil { | ||||||
|  | 						sp.SetStatus(tracer.SpanStatusError, "ErrLostMessage") | ||||||
|  | 						sp.Finish() | ||||||
|  | 					} | ||||||
|  | 					return | ||||||
|  | 				} | ||||||
|  | 				if sp != nil { | ||||||
|  | 					sp.Finish() | ||||||
|  | 				} | ||||||
|  | 			} | ||||||
|  | 		} | ||||||
|  | 	} | ||||||
|  | } | ||||||
							
								
								
									
										223
									
								
								tracer.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										223
									
								
								tracer.go
									
									
									
									
									
										Normal file
									
								
							| @@ -0,0 +1,223 @@ | |||||||
|  | package kgo | ||||||
|  |  | ||||||
|  | import ( | ||||||
|  | 	"context" | ||||||
|  | 	"unicode/utf8" | ||||||
|  |  | ||||||
|  | 	"github.com/twmb/franz-go/pkg/kgo" | ||||||
|  | 	semconv "go.opentelemetry.io/otel/semconv/v1.18.0" | ||||||
|  | 	"go.unistack.org/micro/v3/metadata" | ||||||
|  | 	"go.unistack.org/micro/v3/tracer" | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | type hookTracer struct { | ||||||
|  | 	tracer   tracer.Tracer | ||||||
|  | 	clientID string | ||||||
|  | 	group    string | ||||||
|  | } | ||||||
|  |  | ||||||
|  | var messagingSystem = semconv.MessagingSystemKey.String("kafka") | ||||||
|  |  | ||||||
|  | var ( | ||||||
|  | 	_ kgo.HookProduceRecordBuffered   = (*hookTracer)(nil) | ||||||
|  | 	_ kgo.HookProduceRecordUnbuffered = (*hookTracer)(nil) | ||||||
|  | 	_ kgo.HookFetchRecordBuffered     = (*hookTracer)(nil) | ||||||
|  | 	_ kgo.HookFetchRecordUnbuffered   = (*hookTracer)(nil) | ||||||
|  | ) | ||||||
|  |  | ||||||
|  | // OnProduceRecordBuffered starts a new span for the "publish" operation on a | ||||||
|  | // buffered record. | ||||||
|  | // | ||||||
|  | // It sets span options and injects the span context into record and updates | ||||||
|  | // the record's context, so it can be ended in the OnProduceRecordUnbuffered | ||||||
|  | // hook. | ||||||
|  | func (m *hookTracer) OnProduceRecordBuffered(r *kgo.Record) { | ||||||
|  | 	if !m.tracer.Enabled() { | ||||||
|  | 		return | ||||||
|  | 	} | ||||||
|  | 	// Set up span options. | ||||||
|  | 	attrs := []interface{}{ | ||||||
|  | 		messagingSystem, | ||||||
|  | 		semconv.MessagingDestinationKindTopic, | ||||||
|  | 		semconv.MessagingDestinationName(r.Topic), | ||||||
|  | 		semconv.MessagingOperationPublish, | ||||||
|  | 	} | ||||||
|  | 	attrs = maybeKeyAttr(attrs, r) | ||||||
|  | 	if m.clientID != "" { | ||||||
|  | 		attrs = append(attrs, semconv.MessagingKafkaClientIDKey.String(m.clientID)) | ||||||
|  | 	} | ||||||
|  | 	opts := []tracer.SpanOption{ | ||||||
|  | 		tracer.WithSpanLabels(attrs...), | ||||||
|  | 		tracer.WithSpanKind(tracer.SpanKindProducer), | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	if r.Context == nil { | ||||||
|  | 		r.Context = context.Background() | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	omd, ok := metadata.FromOutgoingContext(r.Context) | ||||||
|  | 	if !ok { | ||||||
|  | 		omd = metadata.New(len(r.Headers)) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	md := metadata.Copy(omd) | ||||||
|  | 	for _, h := range r.Headers { | ||||||
|  | 		md.Set(h.Key, string(h.Value)) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	if !ok { | ||||||
|  | 		r.Context, _ = m.tracer.Start(metadata.NewOutgoingContext(r.Context, md), "sdk.broker", opts...) | ||||||
|  | 	} else { | ||||||
|  | 		r.Context, _ = m.tracer.Start(r.Context, "sdk.broker", opts...) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	setHeaders(r, omd, metadata.HeaderContentType) | ||||||
|  | } | ||||||
|  |  | ||||||
|  | // OnProduceRecordUnbuffered continues and ends the "publish" span for an | ||||||
|  | // unbuffered record. | ||||||
|  | // | ||||||
|  | // It sets attributes with values unset when producing and records any error | ||||||
|  | // that occurred during the publish operation. | ||||||
|  | func (m *hookTracer) OnProduceRecordUnbuffered(r *kgo.Record, err error) { | ||||||
|  | 	if !m.tracer.Enabled() { | ||||||
|  | 		return | ||||||
|  | 	} | ||||||
|  | 	if span, ok := tracer.SpanFromContext(r.Context); ok { | ||||||
|  | 		span.AddLabels( | ||||||
|  | 			semconv.MessagingKafkaDestinationPartition(int(r.Partition)), | ||||||
|  | 		) | ||||||
|  | 		if err != nil { | ||||||
|  | 			span.SetStatus(tracer.SpanStatusError, err.Error()) | ||||||
|  | 		} | ||||||
|  | 		span.Finish() | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  |  | ||||||
|  | // OnFetchRecordBuffered starts a new span for the "receive" operation on a | ||||||
|  | // buffered record. | ||||||
|  | // | ||||||
|  | // It sets the span options and extracts the span context from the record, | ||||||
|  | // updates the record's context to ensure it can be ended in the | ||||||
|  | // OnFetchRecordUnbuffered hook and can be used in downstream consumer | ||||||
|  | // processing. | ||||||
|  | func (m *hookTracer) OnFetchRecordBuffered(r *kgo.Record) { | ||||||
|  | 	if !m.tracer.Enabled() { | ||||||
|  | 		return | ||||||
|  | 	} | ||||||
|  | 	// Set up the span options. | ||||||
|  | 	attrs := []interface{}{ | ||||||
|  | 		messagingSystem, | ||||||
|  | 		semconv.MessagingSourceKindTopic, | ||||||
|  | 		semconv.MessagingSourceName(r.Topic), | ||||||
|  | 		semconv.MessagingOperationReceive, | ||||||
|  | 		semconv.MessagingKafkaSourcePartition(int(r.Partition)), | ||||||
|  | 	} | ||||||
|  | 	attrs = maybeKeyAttr(attrs, r) | ||||||
|  | 	if m.clientID != "" { | ||||||
|  | 		attrs = append(attrs, semconv.MessagingKafkaClientIDKey.String(m.clientID)) | ||||||
|  | 	} | ||||||
|  | 	if m.group != "" { | ||||||
|  | 		attrs = append(attrs, semconv.MessagingKafkaConsumerGroupKey.String(m.group)) | ||||||
|  | 	} | ||||||
|  | 	opts := []tracer.SpanOption{ | ||||||
|  | 		tracer.WithSpanLabels(attrs...), | ||||||
|  | 		tracer.WithSpanKind(tracer.SpanKindConsumer), | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	if r.Context == nil { | ||||||
|  | 		r.Context = context.Background() | ||||||
|  | 	} | ||||||
|  | 	omd, ok := metadata.FromIncomingContext(r.Context) | ||||||
|  | 	if !ok { | ||||||
|  | 		omd = metadata.New(len(r.Headers)) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	md := metadata.Copy(omd) | ||||||
|  | 	for _, h := range r.Headers { | ||||||
|  | 		md.Set(h.Key, string(h.Value)) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	if !ok { | ||||||
|  | 		r.Context, _ = m.tracer.Start(metadata.NewIncomingContext(r.Context, md), "sdk.broker", opts...) | ||||||
|  | 	} else { | ||||||
|  | 		r.Context, _ = m.tracer.Start(r.Context, "sdk.broker", opts...) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	setHeaders(r, omd, metadata.HeaderContentType) | ||||||
|  | } | ||||||
|  |  | ||||||
|  | // OnFetchRecordUnbuffered continues and ends the "receive" span for an | ||||||
|  | // unbuffered record. | ||||||
|  | func (m *hookTracer) OnFetchRecordUnbuffered(r *kgo.Record, _ bool) { | ||||||
|  | 	if !m.tracer.Enabled() { | ||||||
|  | 		return | ||||||
|  | 	} | ||||||
|  | 	span, _ := tracer.SpanFromContext(r.Context) | ||||||
|  | 	span.Finish() | ||||||
|  | } | ||||||
|  |  | ||||||
|  | // WithProcessSpan starts a new span for the "process" operation on a consumer | ||||||
|  | // record. | ||||||
|  | // | ||||||
|  | // It sets up the span options. The user's application code is responsible for | ||||||
|  | // ending the span. | ||||||
|  | // | ||||||
|  | // This should only ever be called within a polling loop of a consumed record and | ||||||
|  | // not a record which has been created for producing, so call this at the start of each | ||||||
|  | // iteration of your processing for the record. | ||||||
|  | func (m *hookTracer) WithProcessSpan(r *kgo.Record) (context.Context, tracer.Span) { | ||||||
|  | 	if r.Context == nil { | ||||||
|  | 		r.Context = context.Background() | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	if !m.tracer.Enabled() { | ||||||
|  | 		return r.Context, nil | ||||||
|  | 	} | ||||||
|  | 	// Set up the span options. | ||||||
|  | 	attrs := []interface{}{ | ||||||
|  | 		messagingSystem, | ||||||
|  | 		semconv.MessagingSourceKindTopic, | ||||||
|  | 		semconv.MessagingSourceName(r.Topic), | ||||||
|  | 		semconv.MessagingOperationProcess, | ||||||
|  | 		semconv.MessagingKafkaSourcePartition(int(r.Partition)), | ||||||
|  | 		semconv.MessagingKafkaMessageOffset(int(r.Offset)), | ||||||
|  | 	} | ||||||
|  | 	attrs = maybeKeyAttr(attrs, r) | ||||||
|  | 	if m.clientID != "" { | ||||||
|  | 		attrs = append(attrs, semconv.MessagingKafkaClientIDKey.String(m.clientID)) | ||||||
|  | 	} | ||||||
|  | 	if m.group != "" { | ||||||
|  | 		attrs = append(attrs, semconv.MessagingKafkaConsumerGroupKey.String(m.group)) | ||||||
|  | 	} | ||||||
|  | 	opts := []tracer.SpanOption{ | ||||||
|  | 		tracer.WithSpanLabels(attrs...), | ||||||
|  | 		tracer.WithSpanKind(tracer.SpanKindConsumer), | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	if r.Context == nil { | ||||||
|  | 		r.Context = context.Background() | ||||||
|  | 	} | ||||||
|  | 	md, ok := metadata.FromIncomingContext(r.Context) | ||||||
|  | 	if !ok { | ||||||
|  | 		md = metadata.New(len(r.Headers)) | ||||||
|  | 	} | ||||||
|  | 	for _, h := range r.Headers { | ||||||
|  | 		md.Set(h.Key, string(h.Value)) | ||||||
|  | 	} | ||||||
|  |  | ||||||
|  | 	// Start a new span using the provided context and options. | ||||||
|  | 	return m.tracer.Start(r.Context, "sdk.broker", opts...) | ||||||
|  | } | ||||||
|  |  | ||||||
|  | func maybeKeyAttr(attrs []interface{}, r *kgo.Record) []interface{} { | ||||||
|  | 	if r.Key == nil { | ||||||
|  | 		return attrs | ||||||
|  | 	} | ||||||
|  | 	var keykey string | ||||||
|  | 	if !utf8.Valid(r.Key) { | ||||||
|  | 		return attrs | ||||||
|  | 	} | ||||||
|  | 	keykey = string(r.Key) | ||||||
|  | 	return append(attrs, semconv.MessagingKafkaMessageKeyKey.String(keykey)) | ||||||
|  | } | ||||||
							
								
								
									
										220
									
								
								util.go
									
									
									
									
									
								
							
							
						
						
									
										220
									
								
								util.go
									
									
									
									
									
								
							| @@ -1,220 +0,0 @@ | |||||||
| package kgo |  | ||||||
|  |  | ||||||
| import ( |  | ||||||
| 	"context" |  | ||||||
| 	"errors" |  | ||||||
| 	"sync" |  | ||||||
|  |  | ||||||
| 	kgo "github.com/twmb/franz-go/pkg/kgo" |  | ||||||
| 	"go.unistack.org/micro/v3/broker" |  | ||||||
| 	"go.unistack.org/micro/v3/logger" |  | ||||||
| 	"go.unistack.org/micro/v3/metadata" |  | ||||||
| ) |  | ||||||
|  |  | ||||||
| var ErrLostMessage = errors.New("message not marked for offsets commit and will be lost in next iteration") |  | ||||||
|  |  | ||||||
| var pPool = sync.Pool{ |  | ||||||
| 	New: func() interface{} { |  | ||||||
| 		return &publication{msg: broker.NewMessage("")} |  | ||||||
| 	}, |  | ||||||
| } |  | ||||||
|  |  | ||||||
| type worker struct { |  | ||||||
| 	done         chan struct{} |  | ||||||
| 	recs         chan []*kgo.Record |  | ||||||
| 	cherr        chan error |  | ||||||
| 	handler      broker.Handler |  | ||||||
| 	batchHandler broker.BatchHandler |  | ||||||
| 	opts         broker.SubscribeOptions |  | ||||||
| 	kopts        broker.Options |  | ||||||
| 	tpmap        map[string][]int32 |  | ||||||
| 	maxInflight  int |  | ||||||
| 	reader       *kgo.Client |  | ||||||
| 	ctx          context.Context |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (s *subscriber) run(ctx context.Context) { |  | ||||||
| 	for { |  | ||||||
| 		select { |  | ||||||
| 		case <-ctx.Done(): |  | ||||||
| 			return |  | ||||||
| 		case <-s.kopts.Context.Done(): |  | ||||||
| 			return |  | ||||||
| 		default: |  | ||||||
| 			fetches := s.reader.PollFetches(ctx) |  | ||||||
| 			if fetches.IsClientClosed() { |  | ||||||
| 				// TODO: fatal ? |  | ||||||
| 				return |  | ||||||
| 			} |  | ||||||
| 			if len(fetches.Errors()) > 0 { |  | ||||||
| 				for _, err := range fetches.Errors() { |  | ||||||
| 					s.kopts.Logger.Fatalf(ctx, "fetch err topic %s partition %d: %v", err.Topic, err.Partition, err.Err) |  | ||||||
| 				} |  | ||||||
| 				// TODO: fatal ? |  | ||||||
| 				return |  | ||||||
| 			} |  | ||||||
|  |  | ||||||
| 			fetches.EachPartition(func(p kgo.FetchTopicPartition) { |  | ||||||
| 				s.Lock() |  | ||||||
| 				consumers := s.consumers[p.Topic] |  | ||||||
| 				s.Unlock() |  | ||||||
| 				if consumers == nil { |  | ||||||
| 					return |  | ||||||
| 				} |  | ||||||
| 				w, ok := consumers[p.Partition] |  | ||||||
| 				if !ok { |  | ||||||
| 					return |  | ||||||
| 				} |  | ||||||
| 				select { |  | ||||||
| 				case err := <-w.cherr: |  | ||||||
| 					s.kopts.Logger.Fatalf(ctx, "handle err: %v", err) |  | ||||||
| 					return |  | ||||||
| 				case w.recs <- p.Records: |  | ||||||
| 				case <-w.done: |  | ||||||
| 				} |  | ||||||
| 			}) |  | ||||||
| 		} |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (s *subscriber) assigned(ctx context.Context, _ *kgo.Client, assigned map[string][]int32) { |  | ||||||
| 	maxInflight := DefaultSubscribeMaxInflight |  | ||||||
|  |  | ||||||
| 	if s.opts.Context != nil { |  | ||||||
| 		if n, ok := s.opts.Context.Value(subscribeMaxInflightKey{}).(int); n > 0 && ok { |  | ||||||
| 			maxInflight = n |  | ||||||
| 		} |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	s.Lock() |  | ||||||
| 	for topic, partitions := range assigned { |  | ||||||
| 		if s.consumers[topic] == nil { |  | ||||||
| 			s.consumers[topic] = make(map[int32]worker) |  | ||||||
| 		} |  | ||||||
| 		for _, partition := range partitions { |  | ||||||
| 			w := worker{ |  | ||||||
| 				done:         make(chan struct{}), |  | ||||||
| 				recs:         make(chan []*kgo.Record), |  | ||||||
| 				cherr:        make(chan error), |  | ||||||
| 				kopts:        s.kopts, |  | ||||||
| 				opts:         s.opts, |  | ||||||
| 				ctx:          ctx, |  | ||||||
| 				tpmap:        map[string][]int32{topic: []int32{partition}}, |  | ||||||
| 				reader:       s.reader, |  | ||||||
| 				handler:      s.handler, |  | ||||||
| 				batchHandler: s.batchhandler, |  | ||||||
| 				maxInflight:  maxInflight, |  | ||||||
| 			} |  | ||||||
| 			s.consumers[topic][partition] = w |  | ||||||
| 			go w.handle() |  | ||||||
| 		} |  | ||||||
| 	} |  | ||||||
| 	s.Unlock() |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (s *subscriber) revoked(_ context.Context, _ *kgo.Client, revoked map[string][]int32) { |  | ||||||
| 	s.Lock() |  | ||||||
| 	for topic, partitions := range revoked { |  | ||||||
| 		ptopics := s.consumers[topic] |  | ||||||
| 		for _, partition := range partitions { |  | ||||||
| 			w := ptopics[partition] |  | ||||||
| 			delete(ptopics, partition) |  | ||||||
| 			if len(ptopics) == 0 { |  | ||||||
| 				delete(s.consumers, topic) |  | ||||||
| 			} |  | ||||||
| 			close(w.done) |  | ||||||
| 		} |  | ||||||
| 	} |  | ||||||
| 	s.Unlock() |  | ||||||
| } |  | ||||||
|  |  | ||||||
| func (w *worker) handle() { |  | ||||||
| 	var err error |  | ||||||
|  |  | ||||||
| 	eh := w.kopts.ErrorHandler |  | ||||||
| 	if w.opts.ErrorHandler != nil { |  | ||||||
| 		eh = w.opts.ErrorHandler |  | ||||||
| 	} |  | ||||||
|  |  | ||||||
| 	paused := false |  | ||||||
| 	for { |  | ||||||
| 		select { |  | ||||||
| 		case <-w.ctx.Done(): |  | ||||||
| 			w.cherr <- w.ctx.Err() |  | ||||||
| 			return |  | ||||||
| 		case <-w.done: |  | ||||||
| 			return |  | ||||||
| 		case recs := <-w.recs: |  | ||||||
| 			if len(recs) >= w.maxInflight { |  | ||||||
| 				paused = true |  | ||||||
| 				w.reader.PauseFetchPartitions(w.tpmap) |  | ||||||
| 			} |  | ||||||
| 			for _, record := range recs { |  | ||||||
| 				p := pPool.Get().(*publication) |  | ||||||
| 				p.msg.Header = nil |  | ||||||
| 				p.msg.Body = nil |  | ||||||
| 				p.topic = record.Topic |  | ||||||
| 				p.err = nil |  | ||||||
| 				p.ack = false |  | ||||||
| 				if w.opts.BodyOnly { |  | ||||||
| 					p.msg.Body = record.Value |  | ||||||
| 				} else if w.kopts.Codec.String() == "noop" { |  | ||||||
| 					p.msg.Body = record.Value |  | ||||||
| 					p.msg.Header = metadata.New(len(record.Headers)) |  | ||||||
| 					for _, h := range record.Headers { |  | ||||||
| 						p.msg.Header.Set(h.Key, string(h.Value)) |  | ||||||
| 					} |  | ||||||
| 				} else { |  | ||||||
| 					if err := w.kopts.Codec.Unmarshal(record.Value, p.msg); err != nil { |  | ||||||
| 						p.err = err |  | ||||||
| 						p.msg.Body = record.Value |  | ||||||
| 						if eh != nil { |  | ||||||
| 							_ = eh(p) |  | ||||||
| 							if p.ack { |  | ||||||
| 								w.reader.MarkCommitRecords(record) |  | ||||||
| 							} else { |  | ||||||
| 								w.cherr <- ErrLostMessage |  | ||||||
| 								pPool.Put(p) |  | ||||||
| 								return |  | ||||||
| 							} |  | ||||||
| 							pPool.Put(p) |  | ||||||
| 							continue |  | ||||||
| 						} else { |  | ||||||
| 							if w.kopts.Logger.V(logger.ErrorLevel) { |  | ||||||
| 								w.kopts.Logger.Errorf(w.kopts.Context, "[kgo]: failed to unmarshal: %v", err) |  | ||||||
| 							} |  | ||||||
| 						} |  | ||||||
| 						pPool.Put(p) |  | ||||||
| 						w.cherr <- err |  | ||||||
| 						return |  | ||||||
| 					} |  | ||||||
| 				} |  | ||||||
| 				err = w.handler(p) |  | ||||||
| 				if err == nil && w.opts.AutoAck { |  | ||||||
| 					p.ack = true |  | ||||||
| 				} else if err != nil { |  | ||||||
| 					p.err = err |  | ||||||
| 					if eh != nil { |  | ||||||
| 						_ = eh(p) |  | ||||||
| 					} else { |  | ||||||
| 						if w.kopts.Logger.V(logger.ErrorLevel) { |  | ||||||
| 							w.kopts.Logger.Errorf(w.kopts.Context, "[kgo]: subscriber error: %v", err) |  | ||||||
| 						} |  | ||||||
| 					} |  | ||||||
| 				} |  | ||||||
| 				if p.ack { |  | ||||||
| 					pPool.Put(p) |  | ||||||
| 					w.reader.MarkCommitRecords(record) |  | ||||||
| 				} else { |  | ||||||
| 					pPool.Put(p) |  | ||||||
| 					w.cherr <- ErrLostMessage |  | ||||||
| 					return |  | ||||||
| 				} |  | ||||||
| 			} |  | ||||||
| 			if paused { |  | ||||||
| 				paused = false |  | ||||||
| 				w.reader.ResumeFetchPartitions(w.tpmap) |  | ||||||
| 			} |  | ||||||
| 		} |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
		Reference in New Issue
	
	Block a user