Compare commits
	
		
			85 Commits
		
	
	
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| 9dcdef57f4 | |||
| f8a115595b | |||
| 
						 | 
					52ea1ef8c0 | ||
| ffd10d7ea9 | |||
| 
						 | 
					c4f8de4aca | ||
| 63d82be92a | |||
| cced3b84c1 | |||
| 
						 | 
					82c1bda50f | ||
| 4b0b70e7d0 | |||
| 
						 | 
					da88718e03 | ||
| aed304b7e3 | |||
| b796c43257 | |||
| b0691edf82 | |||
| d43b59f2f3 | |||
| f976516d6b | |||
| 8f5c03ad60 | |||
| 
						 | 
					9e9c1434ff | ||
| fe81a14413 | |||
| eb56a48dda | |||
| 71e8a13c70 | |||
| b538ef82b5 | |||
| 44e2d5f9a4 | |||
| 
						 | 
					9426208e1c | ||
| d6e73a3419 | |||
| 969e459e3d | |||
| 
						 | 
					b2cd7d8b8e | ||
| 6d85d3ee41 | |||
| d0978fb314 | |||
| 
						 | 
					0bd81d1253 | ||
| e34f57a515 | |||
| ccd912adb2 | |||
| db97b24904 | |||
| 7410408fc4 | |||
| 4d28a6ebb2 | |||
| f73d9d7347 | |||
| 53f72f1246 | |||
| ac454693a6 | |||
| 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 | 
							
								
								
									
										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"
 | 
			
		||||
							
								
								
									
										20
									
								
								.github/workflows/autoapprove.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										20
									
								
								.github/workflows/autoapprove.yml
									
									
									
									
										vendored
									
									
								
							@@ -1,20 +0,0 @@
 | 
			
		||||
name: "autoapprove"
 | 
			
		||||
 | 
			
		||||
on:
 | 
			
		||||
  pull_request_target:
 | 
			
		||||
    types: [assigned, opened, synchronize, reopened]
 | 
			
		||||
 | 
			
		||||
permissions:
 | 
			
		||||
  pull-requests: write
 | 
			
		||||
  contents: write
 | 
			
		||||
 | 
			
		||||
jobs:
 | 
			
		||||
  autoapprove:
 | 
			
		||||
    runs-on: ubuntu-latest
 | 
			
		||||
    steps:
 | 
			
		||||
      - name: approve
 | 
			
		||||
        uses: hmarr/auto-approve-action@v3
 | 
			
		||||
        if: github.actor == 'vtolstov' || github.actor == 'dependabot[bot]'
 | 
			
		||||
        id: approve
 | 
			
		||||
        with:
 | 
			
		||||
          github-token: ${{ secrets.GITHUB_TOKEN }}
 | 
			
		||||
							
								
								
									
										21
									
								
								.github/workflows/automerge.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										21
									
								
								.github/workflows/automerge.yml
									
									
									
									
										vendored
									
									
								
							@@ -1,21 +0,0 @@
 | 
			
		||||
name: "automerge"
 | 
			
		||||
 | 
			
		||||
on:
 | 
			
		||||
  pull_request_target:
 | 
			
		||||
    types: [assigned, opened, synchronize, reopened]
 | 
			
		||||
 | 
			
		||||
permissions:
 | 
			
		||||
  pull-requests: write
 | 
			
		||||
  contents: write
 | 
			
		||||
 | 
			
		||||
jobs:
 | 
			
		||||
  automerge:
 | 
			
		||||
    runs-on: ubuntu-latest
 | 
			
		||||
    if: github.actor == 'vtolstov'
 | 
			
		||||
    steps:
 | 
			
		||||
      - name: merge
 | 
			
		||||
        id: merge
 | 
			
		||||
        run: gh pr merge --auto --merge "$PR_URL"
 | 
			
		||||
        env:
 | 
			
		||||
          PR_URL: ${{github.event.pull_request.html_url}}
 | 
			
		||||
          GITHUB_TOKEN: ${{secrets.TOKEN}}
 | 
			
		||||
							
								
								
									
										47
									
								
								.github/workflows/build.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										47
									
								
								.github/workflows/build.yml
									
									
									
									
										vendored
									
									
								
							@@ -1,47 +0,0 @@
 | 
			
		||||
name: build
 | 
			
		||||
on:
 | 
			
		||||
 push:
 | 
			
		||||
    branches:
 | 
			
		||||
    - master
 | 
			
		||||
    - v3
 | 
			
		||||
jobs:
 | 
			
		||||
  test:
 | 
			
		||||
    name: test
 | 
			
		||||
    runs-on: ubuntu-latest
 | 
			
		||||
    steps:
 | 
			
		||||
    - name: setup
 | 
			
		||||
      uses: actions/setup-go@v3
 | 
			
		||||
      with:
 | 
			
		||||
        go-version: 1.17
 | 
			
		||||
    - name: checkout
 | 
			
		||||
      uses: actions/checkout@v3
 | 
			
		||||
    - name: cache
 | 
			
		||||
      uses: actions/cache@v3
 | 
			
		||||
      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@v3
 | 
			
		||||
      - name: lint
 | 
			
		||||
        uses: golangci/golangci-lint-action@v3.4.0
 | 
			
		||||
        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
 | 
			
		||||
							
								
								
									
										78
									
								
								.github/workflows/codeql-analysis.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										78
									
								
								.github/workflows/codeql-analysis.yml
									
									
									
									
										vendored
									
									
								
							@@ -1,78 +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, v3 ]
 | 
			
		||||
  pull_request:
 | 
			
		||||
    # The branches below must be a subset of the branches above
 | 
			
		||||
    branches: [ master, v3 ]
 | 
			
		||||
  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
 | 
			
		||||
      uses: actions/checkout@v3
 | 
			
		||||
    - name: setup
 | 
			
		||||
      uses: actions/setup-go@v3
 | 
			
		||||
      with:
 | 
			
		||||
        go-version: 1.17
 | 
			
		||||
    # Initializes the CodeQL tools for scanning.
 | 
			
		||||
    - name: init
 | 
			
		||||
      uses: github/codeql-action/init@v2
 | 
			
		||||
      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@v2
 | 
			
		||||
 | 
			
		||||
    # ℹ️ 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: analyze
 | 
			
		||||
      uses: github/codeql-action/analyze@v2
 | 
			
		||||
							
								
								
									
										27
									
								
								.github/workflows/dependabot-automerge.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										27
									
								
								.github/workflows/dependabot-automerge.yml
									
									
									
									
										vendored
									
									
								
							@@ -1,27 +0,0 @@
 | 
			
		||||
name: "dependabot-automerge"
 | 
			
		||||
 | 
			
		||||
on:
 | 
			
		||||
  pull_request_target:
 | 
			
		||||
    types: [assigned, opened, synchronize, reopened]
 | 
			
		||||
 | 
			
		||||
permissions:
 | 
			
		||||
  pull-requests: write
 | 
			
		||||
  contents: write
 | 
			
		||||
 | 
			
		||||
jobs:
 | 
			
		||||
  automerge:
 | 
			
		||||
    runs-on: ubuntu-latest
 | 
			
		||||
    if: github.actor == 'dependabot[bot]'
 | 
			
		||||
    steps:
 | 
			
		||||
      - name: metadata
 | 
			
		||||
        id: metadata
 | 
			
		||||
        uses: dependabot/fetch-metadata@v1.3.6
 | 
			
		||||
        with:
 | 
			
		||||
          github-token: "${{ secrets.TOKEN }}"
 | 
			
		||||
      - name: merge
 | 
			
		||||
        id: merge
 | 
			
		||||
        if: ${{contains(steps.metadata.outputs.dependency-names, 'go.unistack.org')}}
 | 
			
		||||
        run: gh pr merge --auto --merge "$PR_URL"
 | 
			
		||||
        env:
 | 
			
		||||
          PR_URL: ${{github.event.pull_request.html_url}}
 | 
			
		||||
          GITHUB_TOKEN: ${{secrets.TOKEN}}
 | 
			
		||||
							
								
								
									
										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'
 | 
			
		||||
							
								
								
									
										94
									
								
								.github/workflows/job_sync.yml
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										94
									
								
								.github/workflows/job_sync.yml
									
									
									
									
										vendored
									
									
										Normal file
									
								
							@@ -0,0 +1,94 @@
 | 
			
		||||
name: sync
 | 
			
		||||
 | 
			
		||||
on:
 | 
			
		||||
  schedule:
 | 
			
		||||
    - cron: '*/5 * * * *'
 | 
			
		||||
  # Allows you to run this workflow manually from the Actions tab
 | 
			
		||||
  workflow_dispatch:
 | 
			
		||||
 | 
			
		||||
jobs:
 | 
			
		||||
  sync:
 | 
			
		||||
    if: github.server_url != 'https://github.com'
 | 
			
		||||
    runs-on: ubuntu-latest
 | 
			
		||||
    steps:
 | 
			
		||||
    - name: init
 | 
			
		||||
      run: |
 | 
			
		||||
        git config --global user.email "vtolstov <vtolstov@users.noreply.github.com>"
 | 
			
		||||
        git config --global user.name "github-actions[bot]"
 | 
			
		||||
        echo "machine git.unistack.org login vtolstov password ${{ secrets.TOKEN_GITEA }}" >> /root/.netrc
 | 
			
		||||
        echo "machine github.com login vtolstov password ${{ secrets.TOKEN_GITHUB }}" >> /root/.netrc
 | 
			
		||||
 | 
			
		||||
    - name: check master
 | 
			
		||||
      id: check_master
 | 
			
		||||
      run: |
 | 
			
		||||
        src_hash=$(git ls-remote https://github.com/${GITHUB_REPOSITORY} refs/heads/master | cut -f1)
 | 
			
		||||
        dst_hash=$(git ls-remote ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} refs/heads/master | cut -f1)
 | 
			
		||||
        echo "src_hash=$src_hash"
 | 
			
		||||
        echo "dst_hash=$dst_hash"
 | 
			
		||||
        if [ "$src_hash" != "$dst_hash" -a "$src_hash" != "" -a "" != "$dst_hash" ]; then
 | 
			
		||||
          echo "sync_needed=true" >> $GITHUB_OUTPUT
 | 
			
		||||
        else
 | 
			
		||||
          echo "sync_needed=false" >> $GITHUB_OUTPUT
 | 
			
		||||
        fi
 | 
			
		||||
 | 
			
		||||
    - name: sync master
 | 
			
		||||
      if: steps.check_master.outputs.sync_needed == 'true'
 | 
			
		||||
      run: |
 | 
			
		||||
        git clone --filter=blob:none --filter=tree:0 --branch master --single-branch ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} repo
 | 
			
		||||
        cd repo
 | 
			
		||||
        git remote add --no-tags --fetch --track master upstream https://github.com/${GITHUB_REPOSITORY}
 | 
			
		||||
        git pull --rebase upstream master
 | 
			
		||||
        git push upstream master --progress
 | 
			
		||||
        git push origin master --progress
 | 
			
		||||
        cd ../
 | 
			
		||||
        rm -rf repo
 | 
			
		||||
 | 
			
		||||
    - name: check v3
 | 
			
		||||
      id: check_v3
 | 
			
		||||
      run: |
 | 
			
		||||
        src_hash=$(git ls-remote https://github.com/${GITHUB_REPOSITORY} refs/heads/v3 | cut -f1)
 | 
			
		||||
        dst_hash=$(git ls-remote ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} refs/heads/v3 | cut -f1)
 | 
			
		||||
        echo "src_hash=$src_hash"
 | 
			
		||||
        echo "dst_hash=$dst_hash"
 | 
			
		||||
        if [ "$src_hash" != "$dst_hash" ]; then
 | 
			
		||||
          echo "sync_needed=true" >> $GITHUB_OUTPUT
 | 
			
		||||
        else
 | 
			
		||||
          echo "sync_needed=false" >> $GITHUB_OUTPUT
 | 
			
		||||
        fi
 | 
			
		||||
 | 
			
		||||
    - name: sync v3
 | 
			
		||||
      if: steps.check_v3.outputs.sync_needed == 'true'
 | 
			
		||||
      run: |
 | 
			
		||||
        git clone --filter=blob:none --filter=tree:0 --branch v3 --single-branch ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} repo
 | 
			
		||||
        cd repo
 | 
			
		||||
        git remote add --no-tags --fetch --track v3 upstream https://github.com/${GITHUB_REPOSITORY}
 | 
			
		||||
        git pull --rebase upstream v3
 | 
			
		||||
        git push upstream v3 --progress
 | 
			
		||||
        git push origin v3 --progress
 | 
			
		||||
        cd ../
 | 
			
		||||
        rm -rf repo
 | 
			
		||||
 | 
			
		||||
    - name: check v4
 | 
			
		||||
      id: check_v4
 | 
			
		||||
      run: |
 | 
			
		||||
        src_hash=$(git ls-remote https://github.com/${GITHUB_REPOSITORY} refs/heads/v4 | cut -f1)
 | 
			
		||||
        dst_hash=$(git ls-remote ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} refs/heads/v4 | cut -f1)
 | 
			
		||||
        echo "src_hash=$src_hash"
 | 
			
		||||
        echo "dst_hash=$dst_hash"
 | 
			
		||||
        if [ "$src_hash" != "$dst_hash" ]; then
 | 
			
		||||
          echo "sync_needed=true" >> $GITHUB_OUTPUT
 | 
			
		||||
        else
 | 
			
		||||
          echo "sync_needed=false" >> $GITHUB_OUTPUT
 | 
			
		||||
        fi
 | 
			
		||||
 | 
			
		||||
    - name: sync v4
 | 
			
		||||
      if: steps.check_v4.outputs.sync_needed == 'true'
 | 
			
		||||
      run: |
 | 
			
		||||
        git clone --filter=blob:none --filter=tree:0 --branch v4 --single-branch ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} repo
 | 
			
		||||
        cd repo
 | 
			
		||||
        git remote add --no-tags --fetch --track v4 upstream https://github.com/${GITHUB_REPOSITORY}
 | 
			
		||||
        git pull --rebase upstream v4
 | 
			
		||||
        git push upstream v4 --progress
 | 
			
		||||
        git push origin v4 --progress
 | 
			
		||||
        cd ../
 | 
			
		||||
        rm -rf repo
 | 
			
		||||
							
								
								
									
										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
 | 
			
		||||
							
								
								
									
										47
									
								
								.github/workflows/pr.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										47
									
								
								.github/workflows/pr.yml
									
									
									
									
										vendored
									
									
								
							@@ -1,47 +0,0 @@
 | 
			
		||||
name: prbuild
 | 
			
		||||
on:
 | 
			
		||||
  pull_request:
 | 
			
		||||
    branches:
 | 
			
		||||
    - master
 | 
			
		||||
    - v3
 | 
			
		||||
jobs:
 | 
			
		||||
  test:
 | 
			
		||||
    name: test
 | 
			
		||||
    runs-on: ubuntu-latest
 | 
			
		||||
    steps:
 | 
			
		||||
    - name: setup
 | 
			
		||||
      uses: actions/setup-go@v3
 | 
			
		||||
      with:
 | 
			
		||||
        go-version: 1.17
 | 
			
		||||
    - name: checkout
 | 
			
		||||
      uses: actions/checkout@v3
 | 
			
		||||
    - name: cache
 | 
			
		||||
      uses: actions/cache@v3
 | 
			
		||||
      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@v3
 | 
			
		||||
      - name: lint
 | 
			
		||||
        uses: golangci/golangci-lint-action@v3.4.0
 | 
			
		||||
        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)
 | 
			
		||||
# 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
 | 
			
		||||
@@ -1,2 +1,2 @@
 | 
			
		||||
# broker-kgo
 | 
			
		||||
 | 
			
		||||
# micro-broker-kgo
 | 
			
		||||

 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										40
									
								
								carrier.go
									
									
									
									
									
								
							
							
						
						
									
										40
									
								
								carrier.go
									
									
									
									
									
								
							@@ -1,7 +1,12 @@
 | 
			
		||||
package kgo
 | 
			
		||||
 | 
			
		||||
import (
 | 
			
		||||
	"net/http"
 | 
			
		||||
	"slices"
 | 
			
		||||
	"strings"
 | 
			
		||||
 | 
			
		||||
	"github.com/twmb/franz-go/pkg/kgo"
 | 
			
		||||
	"go.unistack.org/micro/v4/metadata"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
// RecordCarrier injects and extracts traces from a kgo.Record.
 | 
			
		||||
@@ -51,3 +56,38 @@ func (c RecordCarrier) Keys() []string {
 | 
			
		||||
	}
 | 
			
		||||
	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(strings.Join(v, ","))
 | 
			
		||||
				continue loop
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		// Key does not exist, append new header.
 | 
			
		||||
		r.Headers = append(r.Headers, kgo.RecordHeader{
 | 
			
		||||
			Key:   k,
 | 
			
		||||
			Value: []byte(strings.Join(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)
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										42
									
								
								event.go
									
									
									
									
									
								
							
							
						
						
									
										42
									
								
								event.go
									
									
									
									
									
								
							@@ -1,42 +0,0 @@
 | 
			
		||||
package kgo
 | 
			
		||||
 | 
			
		||||
import (
 | 
			
		||||
	"sync"
 | 
			
		||||
 | 
			
		||||
	"go.unistack.org/micro/v3/broker"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
type event struct {
 | 
			
		||||
	topic string
 | 
			
		||||
	err   error
 | 
			
		||||
	sync.RWMutex
 | 
			
		||||
	msg *broker.Message
 | 
			
		||||
	ack bool
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
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{}}
 | 
			
		||||
	},
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										37
									
								
								go.mod
									
									
									
									
									
								
							
							
						
						
									
										37
									
								
								go.mod
									
									
									
									
									
								
							@@ -1,24 +1,27 @@
 | 
			
		||||
module go.unistack.org/micro-broker-kgo/v3
 | 
			
		||||
module go.unistack.org/micro-broker-kgo/v4
 | 
			
		||||
 | 
			
		||||
go 1.21
 | 
			
		||||
 | 
			
		||||
toolchain go1.22.1
 | 
			
		||||
go 1.24.0
 | 
			
		||||
 | 
			
		||||
require (
 | 
			
		||||
	github.com/google/uuid v1.6.0
 | 
			
		||||
	github.com/twmb/franz-go v1.16.1
 | 
			
		||||
	github.com/twmb/franz-go/pkg/kadm v1.11.0
 | 
			
		||||
	github.com/twmb/franz-go/pkg/kmsg v1.7.0
 | 
			
		||||
	go.opentelemetry.io/otel v1.25.0
 | 
			
		||||
	go.unistack.org/micro/v3 v3.10.59
 | 
			
		||||
	github.com/stretchr/testify v1.11.1
 | 
			
		||||
	github.com/twmb/franz-go v1.20.2
 | 
			
		||||
	github.com/twmb/franz-go/pkg/kadm v1.17.1
 | 
			
		||||
	github.com/twmb/franz-go/pkg/kfake v0.0.0-20250508175730-72e1646135e3
 | 
			
		||||
	github.com/twmb/franz-go/pkg/kmsg v1.12.0
 | 
			
		||||
	go.opentelemetry.io/otel v1.38.0
 | 
			
		||||
	go.unistack.org/micro/v4 v4.1.24
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
require (
 | 
			
		||||
	github.com/klauspost/compress v1.17.8 // indirect
 | 
			
		||||
	github.com/pierrec/lz4/v4 v4.1.21 // indirect
 | 
			
		||||
	golang.org/x/crypto v0.22.0 // indirect
 | 
			
		||||
	golang.org/x/sys v0.19.0 // indirect
 | 
			
		||||
	google.golang.org/genproto/googleapis/rpc v0.0.0-20240412170617-26222e5d3d56 // indirect
 | 
			
		||||
	google.golang.org/grpc v1.63.2 // indirect
 | 
			
		||||
	google.golang.org/protobuf v1.33.0 // indirect
 | 
			
		||||
	github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
 | 
			
		||||
	github.com/google/uuid v1.6.0 // indirect
 | 
			
		||||
	github.com/klauspost/compress v1.18.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
 | 
			
		||||
	github.com/spf13/cast v1.10.0 // indirect
 | 
			
		||||
	go.unistack.org/micro-proto/v4 v4.1.0 // indirect
 | 
			
		||||
	golang.org/x/crypto v0.43.0 // indirect
 | 
			
		||||
	google.golang.org/protobuf v1.36.10 // indirect
 | 
			
		||||
	gopkg.in/yaml.v3 v3.0.1 // indirect
 | 
			
		||||
)
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										91
									
								
								go.sum
									
									
									
									
									
								
							
							
						
						
									
										91
									
								
								go.sum
									
									
									
									
									
								
							@@ -1,40 +1,59 @@
 | 
			
		||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
 | 
			
		||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
 | 
			
		||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
 | 
			
		||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
 | 
			
		||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
 | 
			
		||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
 | 
			
		||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
 | 
			
		||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
 | 
			
		||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
 | 
			
		||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
 | 
			
		||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
 | 
			
		||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
 | 
			
		||||
github.com/klauspost/compress v1.17.8 h1:YcnTYrq7MikUT7k0Yb5eceMmALQPYBW/Xltxn0NAMnU=
 | 
			
		||||
github.com/klauspost/compress v1.17.8/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
 | 
			
		||||
github.com/pierrec/lz4/v4 v4.1.21 h1:yOVMLb6qSIDP67pl/5F7RepeKYu/VmTyEXvuMI5d9mQ=
 | 
			
		||||
github.com/pierrec/lz4/v4 v4.1.21/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
 | 
			
		||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
 | 
			
		||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
 | 
			
		||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
 | 
			
		||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
 | 
			
		||||
github.com/twmb/franz-go v1.16.1 h1:rpWc7fB9jd7TgmCyfxzenBI+QbgS8ZfJOUQE+tzPtbE=
 | 
			
		||||
github.com/twmb/franz-go v1.16.1/go.mod h1:/pER254UPPGp/4WfGqRi+SIRGE50RSQzVubQp6+N4FA=
 | 
			
		||||
github.com/twmb/franz-go/pkg/kadm v1.11.0 h1:FfeWJ0qadntFpAcQt8JzNXW4dijjytZNLrzJuzzzuxA=
 | 
			
		||||
github.com/twmb/franz-go/pkg/kadm v1.11.0/go.mod h1:qrhkdH+SWS3ivmbqOgHbpgVHamhaKcjH0UM+uOp0M1A=
 | 
			
		||||
github.com/twmb/franz-go/pkg/kmsg v1.7.0 h1:a457IbvezYfA5UkiBvyV3zj0Is3y1i8EJgqjJYoij2E=
 | 
			
		||||
github.com/twmb/franz-go/pkg/kmsg v1.7.0/go.mod h1:se9Mjdt0Nwzc9lnjJ0HyDtLyBnaBDAd7pCje47OhSyw=
 | 
			
		||||
go.opentelemetry.io/otel v1.25.0 h1:gldB5FfhRl7OJQbUHt/8s0a7cE8fbsPAtdpRaApKy4k=
 | 
			
		||||
go.opentelemetry.io/otel v1.25.0/go.mod h1:Wa2ds5NOXEMkCmUou1WA7ZBfLTHWIsp034OVD7AO+Vg=
 | 
			
		||||
go.unistack.org/micro/v3 v3.10.59 h1:eneYXJLgyu5MZpSvyI0K17CeXvgOoUCN5dWZaPV5lI4=
 | 
			
		||||
go.unistack.org/micro/v3 v3.10.59/go.mod h1:erMgt3Bl7vQQ0e9UpQyR5NlLiZ9pKeEJ9+1tfYFaqUg=
 | 
			
		||||
golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30=
 | 
			
		||||
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
 | 
			
		||||
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
 | 
			
		||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
 | 
			
		||||
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
 | 
			
		||||
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
 | 
			
		||||
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
 | 
			
		||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
 | 
			
		||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240412170617-26222e5d3d56 h1:zviK8GX4VlMstrK3JkexM5UHjH1VOkRebH9y3jhSBGk=
 | 
			
		||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240412170617-26222e5d3d56/go.mod h1:WtryC6hu0hhx87FDGxWCDptyssuo68sk10vYjF+T9fY=
 | 
			
		||||
google.golang.org/grpc v1.63.2 h1:MUeiw1B2maTVZthpU5xvASfTh3LDbxHd6IJ6QQVU+xM=
 | 
			
		||||
google.golang.org/grpc v1.63.2/go.mod h1:WAX/8DgncnokcFUldAxq7GeB5DXHDbMF+lLvDomNkRA=
 | 
			
		||||
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
 | 
			
		||||
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
 | 
			
		||||
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
 | 
			
		||||
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
 | 
			
		||||
github.com/klauspost/compress v1.18.1 h1:bcSGx7UbpBqMChDtsF28Lw6v/G94LPrrbMbdC3JH2co=
 | 
			
		||||
github.com/klauspost/compress v1.18.1/go.mod h1:ZQFFVG+MdnR0P+l6wpXgIL4NTtwiKIdBnrBd8Nrxr+0=
 | 
			
		||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
 | 
			
		||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
 | 
			
		||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
 | 
			
		||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
 | 
			
		||||
github.com/matoous/go-nanoid v1.5.1 h1:aCjdvTyO9LLnTIi0fgdXhOPPvOHjpXN6Ik9DaNjIct4=
 | 
			
		||||
github.com/matoous/go-nanoid v1.5.1/go.mod h1:zyD2a71IubI24efhpvkJz+ZwfwagzgSO6UNiFsZKN7U=
 | 
			
		||||
github.com/pierrec/lz4/v4 v4.1.22 h1:cKFw6uJDK+/gfw5BcDL0JL5aBsAFdsIT18eRtLj7VIU=
 | 
			
		||||
github.com/pierrec/lz4/v4 v4.1.22/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
 | 
			
		||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
 | 
			
		||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
 | 
			
		||||
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
 | 
			
		||||
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
 | 
			
		||||
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
 | 
			
		||||
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
 | 
			
		||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
 | 
			
		||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
 | 
			
		||||
github.com/twmb/franz-go v1.19.5 h1:W7+o8D0RsQsedqib71OVlLeZ0zI6CbFra7yTYhZTs5Y=
 | 
			
		||||
github.com/twmb/franz-go v1.19.5/go.mod h1:4kFJ5tmbbl7asgwAGVuyG1ZMx0NNpYk7EqflvWfPCpM=
 | 
			
		||||
github.com/twmb/franz-go v1.20.2 h1:CiwhyKZHW6vqSHJkh+RTxFAJkio0jBjM/JQhx/HZ72A=
 | 
			
		||||
github.com/twmb/franz-go v1.20.2/go.mod h1:YCnepDd4gl6vdzG03I5Wa57RnCTIC6DVEyMpDX/J8UA=
 | 
			
		||||
github.com/twmb/franz-go/pkg/kadm v1.16.1 h1:IEkrhTljgLHJ0/hT/InhXGjPdmWfFvxp7o/MR7vJ8cw=
 | 
			
		||||
github.com/twmb/franz-go/pkg/kadm v1.16.1/go.mod h1:Ue/ye1cc9ipsQFg7udFbbGiFNzQMqiH73fGC2y0rwyc=
 | 
			
		||||
github.com/twmb/franz-go/pkg/kadm v1.17.1 h1:Bt02Y/RLgnFO2NP2HVP1kd2TFtGRiJZx+fSArjZDtpw=
 | 
			
		||||
github.com/twmb/franz-go/pkg/kadm v1.17.1/go.mod h1:s4duQmrDbloVW9QTMXhs6mViTepze7JLG43xwPcAeTg=
 | 
			
		||||
github.com/twmb/franz-go/pkg/kfake v0.0.0-20250508175730-72e1646135e3 h1:p24opKWPySAy8xSl8NqRgOv7Q+bX7kdrQirBVRJzQfo=
 | 
			
		||||
github.com/twmb/franz-go/pkg/kfake v0.0.0-20250508175730-72e1646135e3/go.mod h1:7uQs3Ae6HkWT1Y9elMbqtAcNFCI0y6+iS+Phw49L49U=
 | 
			
		||||
github.com/twmb/franz-go/pkg/kmsg v1.11.2 h1:hIw75FpwcAjgeyfIGFqivAvwC5uNIOWRGvQgZhH4mhg=
 | 
			
		||||
github.com/twmb/franz-go/pkg/kmsg v1.11.2/go.mod h1:CFfkkLysDNmukPYhGzuUcDtf46gQSqCZHMW1T4Z+wDE=
 | 
			
		||||
github.com/twmb/franz-go/pkg/kmsg v1.12.0 h1:CbatD7ers1KzDNgJqPbKOq0Bz/WLBdsTH75wgzeVaPc=
 | 
			
		||||
github.com/twmb/franz-go/pkg/kmsg v1.12.0/go.mod h1:+DPt4NC8RmI6hqb8G09+3giKObE6uD2Eya6CfqBpeJY=
 | 
			
		||||
go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8=
 | 
			
		||||
go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM=
 | 
			
		||||
go.unistack.org/micro-proto/v4 v4.1.0 h1:qPwL2n/oqh9RE3RTTDgt28XK3QzV597VugQPaw9lKUk=
 | 
			
		||||
go.unistack.org/micro-proto/v4 v4.1.0/go.mod h1:ArmK7o+uFvxSY3dbJhKBBX4Pm1rhWdLEFf3LxBrMtec=
 | 
			
		||||
go.unistack.org/micro/v4 v4.1.21 h1:F9PrbI1BhXSDS0FopwcO5wWrT2Xh38w9VhVZZBHjfg8=
 | 
			
		||||
go.unistack.org/micro/v4 v4.1.21/go.mod h1:nlBXTbx0rQrSZX4HPp2m57PHmpuGPWUd0O+jpUIiPto=
 | 
			
		||||
go.unistack.org/micro/v4 v4.1.24 h1:PbkSWJS3ssB5A0y0tOdOw6u9e2Mk4yombF4yR0Jshvo=
 | 
			
		||||
go.unistack.org/micro/v4 v4.1.24/go.mod h1:nlBXTbx0rQrSZX4HPp2m57PHmpuGPWUd0O+jpUIiPto=
 | 
			
		||||
golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04=
 | 
			
		||||
golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0=
 | 
			
		||||
google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE=
 | 
			
		||||
google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
 | 
			
		||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
 | 
			
		||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
 | 
			
		||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
 | 
			
		||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
 | 
			
		||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										108
									
								
								hook_event.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										108
									
								
								hook_event.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,108 @@
 | 
			
		||||
package kgo
 | 
			
		||||
 | 
			
		||||
import (
 | 
			
		||||
	"context"
 | 
			
		||||
	"net"
 | 
			
		||||
	"sync/atomic"
 | 
			
		||||
	"time"
 | 
			
		||||
 | 
			
		||||
	"github.com/twmb/franz-go/pkg/kgo"
 | 
			
		||||
	"go.unistack.org/micro/v4/logger"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
type hookEvent struct {
 | 
			
		||||
	log          logger.Logger
 | 
			
		||||
	fatalOnError bool
 | 
			
		||||
	connected    *atomic.Uint32
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
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:
 | 
			
		||||
		ctx := context.TODO()
 | 
			
		||||
		logMsg := "kgo.OnGroupManageError"
 | 
			
		||||
 | 
			
		||||
		if m.fatalOnError {
 | 
			
		||||
			m.log.Fatal(ctx, logMsg, err)
 | 
			
		||||
		} else {
 | 
			
		||||
			m.log.Error(ctx, logMsg, err)
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (m *hookEvent) OnBrokerConnect(_ kgo.BrokerMetadata, _ time.Duration, _ net.Conn, err error) {
 | 
			
		||||
	switch {
 | 
			
		||||
	case err == nil || isContextError(err) || kgo.IsRetryableBrokerErr(err):
 | 
			
		||||
		return
 | 
			
		||||
	default:
 | 
			
		||||
		ctx := context.TODO()
 | 
			
		||||
		logMsg := "kgo.OnBrokerConnect"
 | 
			
		||||
 | 
			
		||||
		if m.fatalOnError {
 | 
			
		||||
			m.log.Fatal(ctx, logMsg, err)
 | 
			
		||||
		} else {
 | 
			
		||||
			m.log.Error(ctx, logMsg, 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:
 | 
			
		||||
		ctx := context.TODO()
 | 
			
		||||
		logMsg := "kgo.OnBrokerWrite"
 | 
			
		||||
 | 
			
		||||
		if m.fatalOnError {
 | 
			
		||||
			m.log.Fatal(ctx, logMsg, err)
 | 
			
		||||
		} else {
 | 
			
		||||
			m.log.Error(ctx, logMsg, 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:
 | 
			
		||||
		ctx := context.TODO()
 | 
			
		||||
		logMsg := "kgo.OnBrokerRead"
 | 
			
		||||
 | 
			
		||||
		if m.fatalOnError {
 | 
			
		||||
			m.log.Fatal(ctx, logMsg, err)
 | 
			
		||||
		} else {
 | 
			
		||||
			m.log.Error(ctx, logMsg, err)
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (m *hookEvent) OnProduceRecordUnbuffered(_ *kgo.Record, err error) {
 | 
			
		||||
	switch {
 | 
			
		||||
	case err == nil || isContextError(err) || kgo.IsRetryableBrokerErr(err):
 | 
			
		||||
		return
 | 
			
		||||
	default:
 | 
			
		||||
		ctx := context.TODO()
 | 
			
		||||
		logMsg := "kgo.OnProduceRecordUnbuffered"
 | 
			
		||||
 | 
			
		||||
		if m.fatalOnError {
 | 
			
		||||
			m.log.Fatal(ctx, logMsg, err)
 | 
			
		||||
		} else {
 | 
			
		||||
			m.log.Error(ctx, logMsg, err)
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										471
									
								
								hook_event_test.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										471
									
								
								hook_event_test.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,471 @@
 | 
			
		||||
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/v4/logger"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
func TestHookEvent_OnGroupManageError(t *testing.T) {
 | 
			
		||||
	tests := []struct {
 | 
			
		||||
		name                  string
 | 
			
		||||
		inputErr              error
 | 
			
		||||
		fatalOnError          bool
 | 
			
		||||
		expectedErrorIsCalled bool
 | 
			
		||||
		expectedErrorMsg      string
 | 
			
		||||
		expectedFatalIsCalled bool
 | 
			
		||||
		expectedFatalMsg      string
 | 
			
		||||
	}{
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "error is nil",
 | 
			
		||||
			inputErr:              nil,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "context canceled",
 | 
			
		||||
			inputErr:              context.Canceled,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "context deadline exceeded",
 | 
			
		||||
			inputErr:              context.DeadlineExceeded,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "retryable error: deadline exceeded (os package)",
 | 
			
		||||
			inputErr:              os.ErrDeadlineExceeded,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "retryable error: EOF (io package)",
 | 
			
		||||
			inputErr:              io.EOF,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "retryable error: closed network connection (net package)",
 | 
			
		||||
			inputErr:              net.ErrClosed,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "some error (non-fatal)",
 | 
			
		||||
			inputErr:              errors.New("some error"),
 | 
			
		||||
			fatalOnError:          false,
 | 
			
		||||
			expectedErrorIsCalled: true,
 | 
			
		||||
			expectedErrorMsg:      "kgo.OnGroupManageError",
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "some error (fatal)",
 | 
			
		||||
			inputErr:              errors.New("some error"),
 | 
			
		||||
			fatalOnError:          true,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: true,
 | 
			
		||||
			expectedFatalMsg:      "kgo.OnGroupManageError",
 | 
			
		||||
		},
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	for _, tt := range tests {
 | 
			
		||||
		t.Run(tt.name, func(t *testing.T) {
 | 
			
		||||
			log := &mockLogger{}
 | 
			
		||||
			he := &hookEvent{log: log, fatalOnError: tt.fatalOnError}
 | 
			
		||||
			he.OnGroupManageError(tt.inputErr)
 | 
			
		||||
			require.Equal(t, tt.expectedErrorIsCalled, log.errorIsCalled)
 | 
			
		||||
			require.Equal(t, tt.expectedErrorMsg, log.errorMsg)
 | 
			
		||||
			require.Equal(t, tt.expectedFatalIsCalled, log.fatalIsCalled)
 | 
			
		||||
			require.Equal(t, tt.expectedFatalMsg, log.fatalMsg)
 | 
			
		||||
		})
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func TestHookEvent_OnBrokerConnect(t *testing.T) {
 | 
			
		||||
	tests := []struct {
 | 
			
		||||
		name                  string
 | 
			
		||||
		inputErr              error
 | 
			
		||||
		fatalOnError          bool
 | 
			
		||||
		expectedErrorIsCalled bool
 | 
			
		||||
		expectedErrorMsg      string
 | 
			
		||||
		expectedFatalIsCalled bool
 | 
			
		||||
		expectedFatalMsg      string
 | 
			
		||||
	}{
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "error is nil",
 | 
			
		||||
			inputErr:              nil,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "context canceled",
 | 
			
		||||
			inputErr:              context.Canceled,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "context deadline exceeded",
 | 
			
		||||
			inputErr:              context.DeadlineExceeded,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "retryable error: deadline exceeded (os package)",
 | 
			
		||||
			inputErr:              os.ErrDeadlineExceeded,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "retryable error: EOF (io package)",
 | 
			
		||||
			inputErr:              io.EOF,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "retryable error: closed network connection (net package)",
 | 
			
		||||
			inputErr:              net.ErrClosed,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "some error (non-fatal)",
 | 
			
		||||
			inputErr:              errors.New("some error"),
 | 
			
		||||
			fatalOnError:          false,
 | 
			
		||||
			expectedErrorIsCalled: true,
 | 
			
		||||
			expectedErrorMsg:      "kgo.OnBrokerConnect",
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "some error (fatal)",
 | 
			
		||||
			inputErr:              errors.New("some error"),
 | 
			
		||||
			fatalOnError:          true,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: true,
 | 
			
		||||
			expectedFatalMsg:      "kgo.OnBrokerConnect",
 | 
			
		||||
		},
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	for _, tt := range tests {
 | 
			
		||||
		t.Run(tt.name, func(t *testing.T) {
 | 
			
		||||
			log := &mockLogger{}
 | 
			
		||||
			he := &hookEvent{log: log, fatalOnError: tt.fatalOnError}
 | 
			
		||||
			he.OnBrokerConnect(kgo.BrokerMetadata{}, 0, nil, tt.inputErr)
 | 
			
		||||
			require.Equal(t, tt.expectedErrorIsCalled, log.errorIsCalled)
 | 
			
		||||
			require.Equal(t, tt.expectedErrorMsg, log.errorMsg)
 | 
			
		||||
			require.Equal(t, tt.expectedFatalIsCalled, log.fatalIsCalled)
 | 
			
		||||
			require.Equal(t, tt.expectedFatalMsg, log.fatalMsg)
 | 
			
		||||
		})
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func TestHookEvent_OnBrokerWrite(t *testing.T) {
 | 
			
		||||
	tests := []struct {
 | 
			
		||||
		name                  string
 | 
			
		||||
		inputErr              error
 | 
			
		||||
		fatalOnError          bool
 | 
			
		||||
		expectedErrorIsCalled bool
 | 
			
		||||
		expectedErrorMsg      string
 | 
			
		||||
		expectedFatalIsCalled bool
 | 
			
		||||
		expectedFatalMsg      string
 | 
			
		||||
	}{
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "error is nil",
 | 
			
		||||
			inputErr:              nil,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "context canceled",
 | 
			
		||||
			inputErr:              context.Canceled,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "context deadline exceeded",
 | 
			
		||||
			inputErr:              context.DeadlineExceeded,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "retryable error: deadline exceeded (os package)",
 | 
			
		||||
			inputErr:              os.ErrDeadlineExceeded,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "retryable error: EOF (io package)",
 | 
			
		||||
			inputErr:              io.EOF,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "retryable error: closed network connection (net package)",
 | 
			
		||||
			inputErr:              net.ErrClosed,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "some error (non-fatal)",
 | 
			
		||||
			inputErr:              errors.New("some error"),
 | 
			
		||||
			fatalOnError:          false,
 | 
			
		||||
			expectedErrorIsCalled: true,
 | 
			
		||||
			expectedErrorMsg:      "kgo.OnBrokerWrite",
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "some error (fatal)",
 | 
			
		||||
			inputErr:              errors.New("some error"),
 | 
			
		||||
			fatalOnError:          true,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: true,
 | 
			
		||||
			expectedFatalMsg:      "kgo.OnBrokerWrite",
 | 
			
		||||
		},
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	for _, tt := range tests {
 | 
			
		||||
		t.Run(tt.name, func(t *testing.T) {
 | 
			
		||||
			log := &mockLogger{}
 | 
			
		||||
			he := &hookEvent{log: log, fatalOnError: tt.fatalOnError}
 | 
			
		||||
			he.OnBrokerWrite(kgo.BrokerMetadata{}, 0, 0, 0, 0, tt.inputErr)
 | 
			
		||||
			require.Equal(t, tt.expectedErrorIsCalled, log.errorIsCalled)
 | 
			
		||||
			require.Equal(t, tt.expectedErrorMsg, log.errorMsg)
 | 
			
		||||
			require.Equal(t, tt.expectedFatalIsCalled, log.fatalIsCalled)
 | 
			
		||||
			require.Equal(t, tt.expectedFatalMsg, log.fatalMsg)
 | 
			
		||||
		})
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func TestHookEvent_OnBrokerRead(t *testing.T) {
 | 
			
		||||
	tests := []struct {
 | 
			
		||||
		name                  string
 | 
			
		||||
		inputErr              error
 | 
			
		||||
		fatalOnError          bool
 | 
			
		||||
		expectedErrorIsCalled bool
 | 
			
		||||
		expectedErrorMsg      string
 | 
			
		||||
		expectedFatalIsCalled bool
 | 
			
		||||
		expectedFatalMsg      string
 | 
			
		||||
	}{
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "error is nil",
 | 
			
		||||
			inputErr:              nil,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "context canceled",
 | 
			
		||||
			inputErr:              context.Canceled,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "context deadline exceeded",
 | 
			
		||||
			inputErr:              context.DeadlineExceeded,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "retryable error: deadline exceeded (os package)",
 | 
			
		||||
			inputErr:              os.ErrDeadlineExceeded,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "retryable error: EOF (io package)",
 | 
			
		||||
			inputErr:              io.EOF,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "retryable error: closed network connection (net package)",
 | 
			
		||||
			inputErr:              net.ErrClosed,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "some error (non-fatal)",
 | 
			
		||||
			inputErr:              errors.New("some error"),
 | 
			
		||||
			fatalOnError:          false,
 | 
			
		||||
			expectedErrorIsCalled: true,
 | 
			
		||||
			expectedErrorMsg:      "kgo.OnBrokerRead",
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "some error (fatal)",
 | 
			
		||||
			inputErr:              errors.New("some error"),
 | 
			
		||||
			fatalOnError:          true,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: true,
 | 
			
		||||
			expectedFatalMsg:      "kgo.OnBrokerRead",
 | 
			
		||||
		},
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	for _, tt := range tests {
 | 
			
		||||
		t.Run(tt.name, func(t *testing.T) {
 | 
			
		||||
			log := &mockLogger{}
 | 
			
		||||
			he := &hookEvent{log: log, fatalOnError: tt.fatalOnError}
 | 
			
		||||
			he.OnBrokerRead(kgo.BrokerMetadata{}, 0, 0, 0, 0, tt.inputErr)
 | 
			
		||||
			require.Equal(t, tt.expectedErrorIsCalled, log.errorIsCalled)
 | 
			
		||||
			require.Equal(t, tt.expectedErrorMsg, log.errorMsg)
 | 
			
		||||
			require.Equal(t, tt.expectedFatalIsCalled, log.fatalIsCalled)
 | 
			
		||||
			require.Equal(t, tt.expectedFatalMsg, log.fatalMsg)
 | 
			
		||||
		})
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func TestHookEvent_OnProduceRecordUnbuffered(t *testing.T) {
 | 
			
		||||
	tests := []struct {
 | 
			
		||||
		name                  string
 | 
			
		||||
		inputErr              error
 | 
			
		||||
		fatalOnError          bool
 | 
			
		||||
		expectedErrorIsCalled bool
 | 
			
		||||
		expectedErrorMsg      string
 | 
			
		||||
		expectedFatalIsCalled bool
 | 
			
		||||
		expectedFatalMsg      string
 | 
			
		||||
	}{
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "error is nil",
 | 
			
		||||
			inputErr:              nil,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "context canceled",
 | 
			
		||||
			inputErr:              context.Canceled,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "context deadline exceeded",
 | 
			
		||||
			inputErr:              context.DeadlineExceeded,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "retryable error: deadline exceeded (os package)",
 | 
			
		||||
			inputErr:              os.ErrDeadlineExceeded,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "retryable error: EOF (io package)",
 | 
			
		||||
			inputErr:              io.EOF,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "retryable error: closed network connection (net package)",
 | 
			
		||||
			inputErr:              net.ErrClosed,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "some error (non-fatal)",
 | 
			
		||||
			inputErr:              errors.New("some error"),
 | 
			
		||||
			fatalOnError:          false,
 | 
			
		||||
			expectedErrorIsCalled: true,
 | 
			
		||||
			expectedErrorMsg:      "kgo.OnProduceRecordUnbuffered",
 | 
			
		||||
			expectedFatalIsCalled: false,
 | 
			
		||||
		},
 | 
			
		||||
		{
 | 
			
		||||
			name:                  "some error (fatal)",
 | 
			
		||||
			inputErr:              errors.New("some error"),
 | 
			
		||||
			fatalOnError:          true,
 | 
			
		||||
			expectedErrorIsCalled: false,
 | 
			
		||||
			expectedFatalIsCalled: true,
 | 
			
		||||
			expectedFatalMsg:      "kgo.OnProduceRecordUnbuffered",
 | 
			
		||||
		},
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	for _, tt := range tests {
 | 
			
		||||
		t.Run(tt.name, func(t *testing.T) {
 | 
			
		||||
			log := &mockLogger{}
 | 
			
		||||
			he := &hookEvent{log: log, fatalOnError: tt.fatalOnError}
 | 
			
		||||
			he.OnProduceRecordUnbuffered(&kgo.Record{}, tt.inputErr)
 | 
			
		||||
			require.Equal(t, tt.expectedErrorIsCalled, log.errorIsCalled)
 | 
			
		||||
			require.Equal(t, tt.expectedErrorMsg, log.errorMsg)
 | 
			
		||||
			require.Equal(t, tt.expectedFatalIsCalled, log.fatalIsCalled)
 | 
			
		||||
			require.Equal(t, tt.expectedFatalMsg, log.fatalMsg)
 | 
			
		||||
		})
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// Mocks
 | 
			
		||||
 | 
			
		||||
type mockLogger struct {
 | 
			
		||||
	errorIsCalled bool
 | 
			
		||||
	errorMsg      string
 | 
			
		||||
 | 
			
		||||
	fatalIsCalled bool
 | 
			
		||||
	fatalMsg      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(ctx context.Context, msg string, args ...interface{}) {
 | 
			
		||||
	m.fatalIsCalled = true
 | 
			
		||||
	m.fatalMsg = msg
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
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")
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										65
									
								
								kadmtest.go
									
									
									
									
									
								
							
							
						
						
									
										65
									
								
								kadmtest.go
									
									
									
									
									
								
							@@ -1,65 +0,0 @@
 | 
			
		||||
//go:build ignore
 | 
			
		||||
 | 
			
		||||
package main
 | 
			
		||||
 | 
			
		||||
import (
 | 
			
		||||
	"context"
 | 
			
		||||
	"fmt"
 | 
			
		||||
	"os"
 | 
			
		||||
	"time"
 | 
			
		||||
 | 
			
		||||
	"github.com/twmb/franz-go/pkg/kadm"
 | 
			
		||||
	"github.com/twmb/franz-go/pkg/kgo"
 | 
			
		||||
	"github.com/twmb/franz-go/pkg/kversion"
 | 
			
		||||
 | 
			
		||||
	//"github.com/twmb/franz-go/pkg/sasl/scram"
 | 
			
		||||
	"github.com/twmb/franz-go/pkg/sasl/plain"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
func die(msg string, args ...any) {
 | 
			
		||||
	fmt.Fprintf(os.Stderr, msg, args...)
 | 
			
		||||
	os.Exit(1)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func main() {
 | 
			
		||||
	seeds := []string{"vm-kafka-ump01tn.mbrd.ru:9092", "vm-kafka-ump02tn.mbrd.ru:9092", "vm-kafka-ump03tn.mbrd.ru:9092"}
 | 
			
		||||
 | 
			
		||||
	pass := "XXXXX"
 | 
			
		||||
	user := "XXXXX"
 | 
			
		||||
 | 
			
		||||
	var adminClient *kadm.Client
 | 
			
		||||
	{
 | 
			
		||||
		client, err := kgo.NewClient(
 | 
			
		||||
			kgo.SeedBrokers(seeds...),
 | 
			
		||||
			// kgo.SASL((scram.Auth{User: user, Pass: pass}).AsSha512Mechanism()),
 | 
			
		||||
			kgo.SASL((plain.Auth{User: user, Pass: pass}).AsMechanism()),
 | 
			
		||||
 | 
			
		||||
			// Do not try to send requests newer than 2.4.0 to avoid breaking changes in the request struct.
 | 
			
		||||
			// Sometimes there are breaking changes for newer versions where more properties are required to set.
 | 
			
		||||
			kgo.MaxVersions(kversion.V2_4_0()),
 | 
			
		||||
		)
 | 
			
		||||
		if err != nil {
 | 
			
		||||
			panic(err)
 | 
			
		||||
		}
 | 
			
		||||
		defer client.Close()
 | 
			
		||||
 | 
			
		||||
		adminClient = kadm.NewClient(client)
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
 | 
			
		||||
	defer cancel()
 | 
			
		||||
 | 
			
		||||
	dg, err := adminClient.DescribeGroups(ctx, "interestrate_loader")
 | 
			
		||||
	if err != nil {
 | 
			
		||||
		die("failed to describe group: %v", err)
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	for _, m := range dg["interestrate_loader"].Members {
 | 
			
		||||
		mc, _ := m.Assigned.AsConsumer()
 | 
			
		||||
		for _, mt := range mc.Topics {
 | 
			
		||||
			for _, p := range mt.Partitions {
 | 
			
		||||
				fmt.Printf("client:%s\tpartitions: %d\n", m.ClientID, p)
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										446
									
								
								kgo.go
									
									
									
									
									
								
							
							
						
						
									
										446
									
								
								kgo.go
									
									
									
									
									
								
							@@ -5,29 +5,39 @@ import (
 | 
			
		||||
	"context"
 | 
			
		||||
	"errors"
 | 
			
		||||
	"fmt"
 | 
			
		||||
	"math/rand"
 | 
			
		||||
	"math/rand/v2"
 | 
			
		||||
	"strconv"
 | 
			
		||||
	"strings"
 | 
			
		||||
	"sync"
 | 
			
		||||
	"sync/atomic"
 | 
			
		||||
	"time"
 | 
			
		||||
 | 
			
		||||
	"github.com/google/uuid"
 | 
			
		||||
	"github.com/twmb/franz-go/pkg/kadm"
 | 
			
		||||
	"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"
 | 
			
		||||
	mrand "go.unistack.org/micro/v3/util/rand"
 | 
			
		||||
	"go.unistack.org/micro/v4/broker"
 | 
			
		||||
	"go.unistack.org/micro/v4/codec"
 | 
			
		||||
	"go.unistack.org/micro/v4/logger"
 | 
			
		||||
	"go.unistack.org/micro/v4/metadata"
 | 
			
		||||
	"go.unistack.org/micro/v4/options"
 | 
			
		||||
	"go.unistack.org/micro/v4/semconv"
 | 
			
		||||
	"go.unistack.org/micro/v4/tracer"
 | 
			
		||||
	"go.unistack.org/micro/v4/util/id"
 | 
			
		||||
	mrand "go.unistack.org/micro/v4/util/rand"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
var _ broker.Broker = (*Broker)(nil)
 | 
			
		||||
 | 
			
		||||
var messagePool = sync.Pool{
 | 
			
		||||
	New: func() interface{} {
 | 
			
		||||
		return &kgoMessage{}
 | 
			
		||||
	},
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
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
 | 
			
		||||
	rng := rand.New(rand.NewSource(time.Now().UnixNano()))
 | 
			
		||||
	return func(fails int) time.Duration {
 | 
			
		||||
		const (
 | 
			
		||||
			min = 100 * time.Millisecond
 | 
			
		||||
@@ -43,7 +53,7 @@ var DefaultRetryBackoffFn = func() func(int) time.Duration {
 | 
			
		||||
		backoff := min * time.Duration(1<<(fails-1))
 | 
			
		||||
 | 
			
		||||
		rngMu.Lock()
 | 
			
		||||
		jitter := 0.8 + 0.4*rng.Float64()
 | 
			
		||||
		jitter := 0.8 + 0.4*rand.Float64()
 | 
			
		||||
		rngMu.Unlock()
 | 
			
		||||
 | 
			
		||||
		backoff = time.Duration(float64(backoff) * jitter)
 | 
			
		||||
@@ -56,13 +66,30 @@ var DefaultRetryBackoffFn = func() func(int) time.Duration {
 | 
			
		||||
}()
 | 
			
		||||
 | 
			
		||||
type Broker struct {
 | 
			
		||||
	init      bool
 | 
			
		||||
	funcPublish   broker.FuncPublish
 | 
			
		||||
	funcSubscribe broker.FuncSubscribe
 | 
			
		||||
	c             *kgo.Client
 | 
			
		||||
	connected     *atomic.Uint32
 | 
			
		||||
 | 
			
		||||
	kopts []kgo.Opt
 | 
			
		||||
	connected bool
 | 
			
		||||
	sync.RWMutex
 | 
			
		||||
	subs  []*Subscriber
 | 
			
		||||
 | 
			
		||||
	opts broker.Options
 | 
			
		||||
	subs []*subscriber
 | 
			
		||||
 | 
			
		||||
	mu   sync.RWMutex
 | 
			
		||||
	init bool
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (r *Broker) Live() bool {
 | 
			
		||||
	return r.connected.Load() == 1
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (r *Broker) Ready() bool {
 | 
			
		||||
	return r.connected.Load() == 1
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (r *Broker) Health() bool {
 | 
			
		||||
	return r.connected.Load() == 1
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (k *Broker) Address() string {
 | 
			
		||||
@@ -73,7 +100,79 @@ func (k *Broker) Name() string {
 | 
			
		||||
	return k.opts.Name
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (k *Broker) connect(ctx context.Context, opts ...kgo.Opt) (*kgo.Client, error) {
 | 
			
		||||
func (k *Broker) Client() *kgo.Client {
 | 
			
		||||
	return k.c
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
type kgoMessage struct {
 | 
			
		||||
	c     codec.Codec
 | 
			
		||||
	topic string
 | 
			
		||||
	ctx   context.Context
 | 
			
		||||
	body  []byte
 | 
			
		||||
	hdr   metadata.Metadata
 | 
			
		||||
	opts  broker.MessageOptions
 | 
			
		||||
	ack   bool
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (m *kgoMessage) Ack() error {
 | 
			
		||||
	m.ack = true
 | 
			
		||||
	return nil
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (m *kgoMessage) Body() []byte {
 | 
			
		||||
	return m.body
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (m *kgoMessage) Header() metadata.Metadata {
 | 
			
		||||
	return m.hdr
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (m *kgoMessage) Context() context.Context {
 | 
			
		||||
	return m.ctx
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (m *kgoMessage) Topic() string {
 | 
			
		||||
	return ""
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (m *kgoMessage) Unmarshal(dst interface{}, opts ...codec.Option) error {
 | 
			
		||||
	return m.c.Unmarshal(m.body, dst)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (b *Broker) newCodec(ct string) (codec.Codec, error) {
 | 
			
		||||
	if idx := strings.IndexRune(ct, ';'); idx >= 0 {
 | 
			
		||||
		ct = ct[:idx]
 | 
			
		||||
	}
 | 
			
		||||
	b.mu.RLock()
 | 
			
		||||
	c, ok := b.opts.Codecs[ct]
 | 
			
		||||
	b.mu.RUnlock()
 | 
			
		||||
	if ok {
 | 
			
		||||
		return c, nil
 | 
			
		||||
	}
 | 
			
		||||
	return nil, codec.ErrUnknownContentType
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (b *Broker) NewMessage(ctx context.Context, hdr metadata.Metadata, body interface{}, opts ...broker.MessageOption) (broker.Message, error) {
 | 
			
		||||
	options := broker.NewMessageOptions(opts...)
 | 
			
		||||
	if options.ContentType == "" {
 | 
			
		||||
		options.ContentType = b.opts.ContentType
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	m := &kgoMessage{ctx: ctx, hdr: hdr.Copy(), opts: options}
 | 
			
		||||
	c, err := b.newCodec(m.opts.ContentType)
 | 
			
		||||
	if err == nil {
 | 
			
		||||
		m.body, err = c.Marshal(body)
 | 
			
		||||
	}
 | 
			
		||||
	if err != nil {
 | 
			
		||||
		return nil, err
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	m.hdr.Set(metadata.HeaderContentType, m.opts.ContentType)
 | 
			
		||||
 | 
			
		||||
	return m, nil
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (k *Broker) connect(ctx context.Context, opts ...kgo.Opt) (*kgo.Client, *hookTracer, error) {
 | 
			
		||||
	var c *kgo.Client
 | 
			
		||||
	var err error
 | 
			
		||||
 | 
			
		||||
@@ -90,63 +189,133 @@ func (k *Broker) connect(ctx context.Context, opts ...kgo.Opt) (*kgo.Client, err
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	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(&hookTracer{group: group, clientID: clientID, tracer: k.opts.Tracer}),
 | 
			
		||||
		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, ctx.Err()
 | 
			
		||||
		}
 | 
			
		||||
		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, err
 | 
			
		||||
			}
 | 
			
		||||
			return nil, nil, err
 | 
			
		||||
		}
 | 
			
		||||
		k.connected.Store(1)
 | 
			
		||||
		return c, htracer, nil
 | 
			
		||||
	}
 | 
			
		||||
	return c, nil
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (k *Broker) Connect(ctx context.Context) error {
 | 
			
		||||
	k.RLock()
 | 
			
		||||
	if k.connected {
 | 
			
		||||
		k.RUnlock()
 | 
			
		||||
	if k.connected.Load() == 1 {
 | 
			
		||||
		return nil
 | 
			
		||||
	}
 | 
			
		||||
	k.RUnlock()
 | 
			
		||||
 | 
			
		||||
	nctx := k.opts.Context
 | 
			
		||||
	if ctx != nil {
 | 
			
		||||
		nctx = ctx
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	c, err := k.connect(nctx, k.kopts...)
 | 
			
		||||
	c, _, err := k.connect(nctx, k.kopts...)
 | 
			
		||||
	if err != nil {
 | 
			
		||||
		return err
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	k.Lock()
 | 
			
		||||
	k.mu.Lock()
 | 
			
		||||
	k.c = c
 | 
			
		||||
	k.connected = true
 | 
			
		||||
	k.Unlock()
 | 
			
		||||
	k.connected.Store(1)
 | 
			
		||||
	k.mu.Unlock()
 | 
			
		||||
 | 
			
		||||
	exposeLag := false
 | 
			
		||||
	if k.opts.Context != nil {
 | 
			
		||||
		if v, ok := k.opts.Context.Value(exposeLagKey{}).(bool); ok && v {
 | 
			
		||||
			exposeLag = v
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	if exposeLag {
 | 
			
		||||
		var mu sync.Mutex
 | 
			
		||||
		var lastUpdate time.Time
 | 
			
		||||
		type pl struct {
 | 
			
		||||
			p string
 | 
			
		||||
			l float64
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		lag := make(map[string]map[string]pl) // topic => group => partition => lag
 | 
			
		||||
		ac := kadm.NewClient(k.c)
 | 
			
		||||
 | 
			
		||||
		updateStats := func() {
 | 
			
		||||
			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)
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	return nil
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (k *Broker) Disconnect(ctx context.Context) error {
 | 
			
		||||
	k.RLock()
 | 
			
		||||
	if !k.connected {
 | 
			
		||||
		k.RUnlock()
 | 
			
		||||
	if k.connected.Load() == 0 {
 | 
			
		||||
		return nil
 | 
			
		||||
	}
 | 
			
		||||
	k.RUnlock()
 | 
			
		||||
 | 
			
		||||
	nctx := k.opts.Context
 | 
			
		||||
	if ctx != nil {
 | 
			
		||||
@@ -156,8 +325,8 @@ func (k *Broker) Disconnect(ctx context.Context) error {
 | 
			
		||||
	ctx, span = k.opts.Tracer.Start(ctx, "Disconnect")
 | 
			
		||||
	defer span.Finish()
 | 
			
		||||
 | 
			
		||||
	k.Lock()
 | 
			
		||||
	defer k.Unlock()
 | 
			
		||||
	k.mu.Lock()
 | 
			
		||||
	defer k.mu.Unlock()
 | 
			
		||||
	select {
 | 
			
		||||
	case <-nctx.Done():
 | 
			
		||||
		return nctx.Err()
 | 
			
		||||
@@ -176,13 +345,13 @@ func (k *Broker) Disconnect(ctx context.Context) error {
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	k.connected = false
 | 
			
		||||
	k.connected.Store(0)
 | 
			
		||||
	return nil
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (k *Broker) Init(opts ...broker.Option) error {
 | 
			
		||||
	k.Lock()
 | 
			
		||||
	defer k.Unlock()
 | 
			
		||||
	k.mu.Lock()
 | 
			
		||||
	defer k.mu.Unlock()
 | 
			
		||||
 | 
			
		||||
	if len(opts) == 0 && k.init {
 | 
			
		||||
		return nil
 | 
			
		||||
@@ -211,6 +380,18 @@ func (k *Broker) Init(opts ...broker.Option) error {
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	k.funcPublish = k.fnPublish
 | 
			
		||||
	k.funcSubscribe = k.fnSubscribe
 | 
			
		||||
 | 
			
		||||
	k.opts.Hooks.EachPrev(func(hook options.Hook) {
 | 
			
		||||
		switch h := hook.(type) {
 | 
			
		||||
		case broker.HookPublish:
 | 
			
		||||
			k.funcPublish = h(k.funcPublish)
 | 
			
		||||
		case broker.HookSubscribe:
 | 
			
		||||
			k.funcSubscribe = h(k.funcSubscribe)
 | 
			
		||||
		}
 | 
			
		||||
	})
 | 
			
		||||
 | 
			
		||||
	k.init = true
 | 
			
		||||
 | 
			
		||||
	return nil
 | 
			
		||||
@@ -220,139 +401,178 @@ func (k *Broker) Options() broker.Options {
 | 
			
		||||
	return k.opts
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (k *Broker) BatchPublish(ctx context.Context, msgs []*broker.Message, opts ...broker.PublishOption) error {
 | 
			
		||||
	return k.publish(ctx, msgs, opts...)
 | 
			
		||||
func (b *Broker) Publish(ctx context.Context, topic string, messages ...broker.Message) error {
 | 
			
		||||
	return b.funcPublish(ctx, topic, messages...)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (k *Broker) Publish(ctx context.Context, topic string, msg *broker.Message, opts ...broker.PublishOption) error {
 | 
			
		||||
	msg.Header.Set(metadata.HeaderTopic, topic)
 | 
			
		||||
	return k.publish(ctx, []*broker.Message{msg}, opts...)
 | 
			
		||||
func (b *Broker) fnPublish(ctx context.Context, topic string, messages ...broker.Message) error {
 | 
			
		||||
	return b.publish(ctx, topic, messages...)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (k *Broker) publish(ctx context.Context, msgs []*broker.Message, opts ...broker.PublishOption) error {
 | 
			
		||||
	var span tracer.Span
 | 
			
		||||
	ctx, span = k.opts.Tracer.Start(ctx, "Publish")
 | 
			
		||||
	defer span.Finish()
 | 
			
		||||
func (b *Broker) publish(ctx context.Context, topic string, messages ...broker.Message) error {
 | 
			
		||||
	var records []*kgo.Record
 | 
			
		||||
 | 
			
		||||
	k.Lock()
 | 
			
		||||
	if !k.connected {
 | 
			
		||||
		c, err := k.connect(ctx, k.kopts...)
 | 
			
		||||
		if err != nil {
 | 
			
		||||
			k.Unlock()
 | 
			
		||||
			return err
 | 
			
		||||
		}
 | 
			
		||||
		k.c = c
 | 
			
		||||
		k.connected = true
 | 
			
		||||
	}
 | 
			
		||||
	k.Unlock()
 | 
			
		||||
	for _, msg := range messages {
 | 
			
		||||
 | 
			
		||||
		rec := &kgo.Record{
 | 
			
		||||
			Context: msg.Context(),
 | 
			
		||||
			Topic:   topic,
 | 
			
		||||
			Value:   msg.Body(),
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
	options := broker.NewPublishOptions(opts...)
 | 
			
		||||
	records := make([]*kgo.Record, 0, len(msgs))
 | 
			
		||||
	var errs []string
 | 
			
		||||
	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 rec.Context != nil {
 | 
			
		||||
			if k, ok := rec.Context.Value(messageKey{}).([]byte); ok && k != nil {
 | 
			
		||||
				rec.Key = k
 | 
			
		||||
			}
 | 
			
		||||
		if p, ok := options.Context.Value(publishPromiseKey{}).(func(*kgo.Record, error)); ok && p != nil {
 | 
			
		||||
			if p, ok := rec.Context.Value(messagePromiseKey{}).(func(*kgo.Record, error)); ok && p != nil {
 | 
			
		||||
				promise = p
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
	for _, msg := range msgs {
 | 
			
		||||
		rec := &kgo.Record{Context: ctx, Key: key}
 | 
			
		||||
		rec.Topic, _ = msg.Header.Get(metadata.HeaderTopic)
 | 
			
		||||
		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
 | 
			
		||||
			for k, v := range msg.Header {
 | 
			
		||||
				rec.Headers = append(rec.Headers, kgo.RecordHeader{Key: k, Value: []byte(v)})
 | 
			
		||||
		kmsg, ok := msg.(*kgoMessage)
 | 
			
		||||
		if !ok {
 | 
			
		||||
			continue
 | 
			
		||||
		}
 | 
			
		||||
		} else {
 | 
			
		||||
			rec.Value, err = k.opts.Codec.Marshal(msg)
 | 
			
		||||
			if err != nil {
 | 
			
		||||
				return err
 | 
			
		||||
		if kmsg.opts.Context != nil {
 | 
			
		||||
			if k, ok := kmsg.opts.Context.Value(messageKey{}).([]byte); ok && k != nil {
 | 
			
		||||
				rec.Key = k
 | 
			
		||||
			}
 | 
			
		||||
			if p, ok := kmsg.opts.Context.Value(messagePromiseKey{}).(func(*kgo.Record, error)); ok && p != nil {
 | 
			
		||||
				promise = p
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
		records = append(records, rec)
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
		setHeaders(rec, msg.Header())
 | 
			
		||||
 | 
			
		||||
		if promise != nil {
 | 
			
		||||
			ts := time.Now()
 | 
			
		||||
		for _, rec := range records {
 | 
			
		||||
			k.c.Produce(ctx, rec, func(r *kgo.Record, err error) {
 | 
			
		||||
			b.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", rec.Topic, "topic", rec.Topic).Inc()
 | 
			
		||||
			b.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())
 | 
			
		||||
				b.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", rec.Topic, "topic", rec.Topic).Dec()
 | 
			
		||||
				b.opts.Meter.Summary(semconv.PublishMessageLatencyMicroseconds, "endpoint", rec.Topic, "topic", rec.Topic).Update(te.Seconds())
 | 
			
		||||
				b.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()
 | 
			
		||||
					b.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()
 | 
			
		||||
					b.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", rec.Topic, "topic", rec.Topic, "status", "success").Inc()
 | 
			
		||||
				}
 | 
			
		||||
				promise(r, err)
 | 
			
		||||
			})
 | 
			
		||||
			continue
 | 
			
		||||
		} else {
 | 
			
		||||
			records = append(records, rec)
 | 
			
		||||
		}
 | 
			
		||||
		return nil
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	if len(records) > 0 {
 | 
			
		||||
		var errs []string
 | 
			
		||||
		ts := time.Now()
 | 
			
		||||
	results := k.c.ProduceSync(ctx, records...)
 | 
			
		||||
		b.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", topic, "topic", topic).Set(uint64(len(records)))
 | 
			
		||||
		results := b.c.ProduceSync(ctx, records...)
 | 
			
		||||
		te := time.Since(ts)
 | 
			
		||||
		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()
 | 
			
		||||
			b.opts.Meter.Summary(semconv.PublishMessageLatencyMicroseconds, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Update(te.Seconds())
 | 
			
		||||
			b.opts.Meter.Histogram(semconv.PublishMessageDurationSeconds, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Update(te.Seconds())
 | 
			
		||||
			b.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Dec()
 | 
			
		||||
			if result.Err != nil {
 | 
			
		||||
			k.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", result.Record.Topic, "topic", result.Record.Topic, "status", "failure").Inc()
 | 
			
		||||
				b.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", result.Record.Topic, "topic", result.Record.Topic, "status", "failure").Inc()
 | 
			
		||||
				errs = append(errs, result.Err.Error())
 | 
			
		||||
			} else {
 | 
			
		||||
			k.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", result.Record.Topic, "topic", result.Record.Topic, "status", "success").Inc()
 | 
			
		||||
				b.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", result.Record.Topic, "topic", result.Record.Topic, "status", "success").Inc()
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		if len(errs) > 0 {
 | 
			
		||||
			return fmt.Errorf("publish error: %s", strings.Join(errs, "\n"))
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	return nil
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (k *Broker) BatchSubscribe(ctx context.Context, topic string, handler broker.BatchHandler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
 | 
			
		||||
	return nil, nil
 | 
			
		||||
func (k *Broker) TopicExists(ctx context.Context, topic string) error {
 | 
			
		||||
	mdreq := kmsg.NewMetadataRequest()
 | 
			
		||||
	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 (b *Broker) Subscribe(ctx context.Context, topic string, handler interface{}, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
 | 
			
		||||
	return b.funcSubscribe(ctx, topic, handler, opts...)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (b *Broker) fnSubscribe(ctx context.Context, topic string, handler interface{}, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
 | 
			
		||||
	if err := broker.IsValidHandler(handler); err != nil {
 | 
			
		||||
		return nil, err
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
func (k *Broker) Subscribe(ctx context.Context, topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
 | 
			
		||||
	options := broker.NewSubscribeOptions(opts...)
 | 
			
		||||
 | 
			
		||||
	switch handler.(type) {
 | 
			
		||||
	default:
 | 
			
		||||
		return nil, broker.ErrInvalidHandler
 | 
			
		||||
	case func(broker.Message) error:
 | 
			
		||||
		break
 | 
			
		||||
	case func([]broker.Message) error:
 | 
			
		||||
		break
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	if options.Group == "" {
 | 
			
		||||
		uid, err := uuid.NewRandom()
 | 
			
		||||
		uid, err := id.New()
 | 
			
		||||
		if err != nil {
 | 
			
		||||
			return nil, err
 | 
			
		||||
		}
 | 
			
		||||
		options.Group = uid.String()
 | 
			
		||||
		options.Group = uid
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	commitInterval := DefaultCommitInterval
 | 
			
		||||
	if k.opts.Context != nil {
 | 
			
		||||
		if v, ok := k.opts.Context.Value(commitIntervalKey{}).(time.Duration); ok && v > 0 {
 | 
			
		||||
	if b.opts.Context != nil {
 | 
			
		||||
		if v, ok := b.opts.Context.Value(commitIntervalKey{}).(time.Duration); ok && v > 0 {
 | 
			
		||||
			commitInterval = v
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	sub := &subscriber{
 | 
			
		||||
	var messagePool bool
 | 
			
		||||
	var fatalOnError bool
 | 
			
		||||
	if b.opts.Context != nil {
 | 
			
		||||
		if v, ok := b.opts.Context.Value(fatalOnErrorKey{}).(bool); ok && v {
 | 
			
		||||
			fatalOnError = v
 | 
			
		||||
		}
 | 
			
		||||
		if v, ok := b.opts.Context.Value(subscribeMessagePoolKey{}).(bool); ok && v {
 | 
			
		||||
			messagePool = v
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	if options.Context != nil {
 | 
			
		||||
		if v, ok := options.Context.Value(fatalOnErrorKey{}).(bool); ok && v {
 | 
			
		||||
			fatalOnError = v
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	sub := &Subscriber{
 | 
			
		||||
		topic:        topic,
 | 
			
		||||
		opts:         options,
 | 
			
		||||
		handler:      handler,
 | 
			
		||||
		kopts:     k.opts,
 | 
			
		||||
		kopts:        b.opts,
 | 
			
		||||
		consumers:    make(map[tp]*consumer),
 | 
			
		||||
		done:         make(chan struct{}),
 | 
			
		||||
		fatalOnError: fatalOnError,
 | 
			
		||||
		connected:    b.connected,
 | 
			
		||||
		messagePool:  messagePool,
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	kopts := append(k.kopts,
 | 
			
		||||
	kopts := append(b.kopts,
 | 
			
		||||
		kgo.ConsumerGroup(options.Group),
 | 
			
		||||
		kgo.ConsumeTopics(topic),
 | 
			
		||||
		kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
 | 
			
		||||
@@ -360,7 +580,9 @@ func (k *Broker) Subscribe(ctx context.Context, topic string, handler broker.Han
 | 
			
		||||
		kgo.AutoCommitInterval(commitInterval),
 | 
			
		||||
		kgo.OnPartitionsAssigned(sub.assigned),
 | 
			
		||||
		kgo.OnPartitionsRevoked(sub.revoked),
 | 
			
		||||
		kgo.StopProducerOnDataLossDetected(),
 | 
			
		||||
		kgo.OnPartitionsLost(sub.lost),
 | 
			
		||||
		kgo.AutoCommitCallback(sub.autocommit),
 | 
			
		||||
		kgo.AutoCommitMarks(),
 | 
			
		||||
	)
 | 
			
		||||
 | 
			
		||||
@@ -370,7 +592,7 @@ func (k *Broker) Subscribe(ctx context.Context, topic string, handler broker.Han
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	c, err := k.connect(ctx, kopts...)
 | 
			
		||||
	c, htracer, err := b.connect(ctx, kopts...)
 | 
			
		||||
	if err != nil {
 | 
			
		||||
		return nil, err
 | 
			
		||||
	}
 | 
			
		||||
@@ -388,12 +610,14 @@ func (k *Broker) Subscribe(ctx context.Context, topic string, handler broker.Han
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	sub.c = c
 | 
			
		||||
	sub.htracer = htracer
 | 
			
		||||
 | 
			
		||||
	go sub.poll(ctx)
 | 
			
		||||
 | 
			
		||||
	k.Lock()
 | 
			
		||||
	k.subs = append(k.subs, sub)
 | 
			
		||||
	k.Unlock()
 | 
			
		||||
	b.mu.Lock()
 | 
			
		||||
	b.subs = append(b.subs, sub)
 | 
			
		||||
	b.mu.Unlock()
 | 
			
		||||
 | 
			
		||||
	return sub, nil
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@@ -414,12 +638,13 @@ func NewBroker(opts ...broker.Option) *Broker {
 | 
			
		||||
		kgo.DialTimeout(3 * time.Second),
 | 
			
		||||
		kgo.DisableIdempotentWrite(),
 | 
			
		||||
		kgo.ProducerBatchCompression(kgo.NoCompression()),
 | 
			
		||||
		kgo.WithLogger(&mlogger{l: options.Logger.Clone(logger.WithCallerSkipCount(options.Logger.Options().CallerSkipCount + 2)), ctx: options.Context}),
 | 
			
		||||
		kgo.WithLogger(&mlogger{l: options.Logger.Clone(logger.WithAddCallerSkipCount(2)), ctx: options.Context}),
 | 
			
		||||
		kgo.SeedBrokers(kaddrs...),
 | 
			
		||||
		kgo.RetryBackoffFn(DefaultRetryBackoffFn),
 | 
			
		||||
		kgo.BlockRebalanceOnPoll(),
 | 
			
		||||
		kgo.Balancers(kgo.CooperativeStickyBalancer()),
 | 
			
		||||
		kgo.FetchIsolationLevel(kgo.ReadUncommitted()),
 | 
			
		||||
		kgo.UnknownTopicRetries(1),
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	if options.Context != nil {
 | 
			
		||||
@@ -429,6 +654,7 @@ func NewBroker(opts ...broker.Option) *Broker {
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	return &Broker{
 | 
			
		||||
		connected: &atomic.Uint32{},
 | 
			
		||||
		opts:      options,
 | 
			
		||||
		kopts:     kopts,
 | 
			
		||||
	}
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										170
									
								
								kgo_test.go
									
									
									
									
									
								
							
							
						
						
									
										170
									
								
								kgo_test.go
									
									
									
									
									
								
							@@ -2,39 +2,140 @@ package kgo_test
 | 
			
		||||
 | 
			
		||||
import (
 | 
			
		||||
	"context"
 | 
			
		||||
	"fmt"
 | 
			
		||||
	"os"
 | 
			
		||||
	"strings"
 | 
			
		||||
	"sync/atomic"
 | 
			
		||||
	"testing"
 | 
			
		||||
	"time"
 | 
			
		||||
 | 
			
		||||
	"github.com/twmb/franz-go/pkg/kfake"
 | 
			
		||||
	kg "github.com/twmb/franz-go/pkg/kgo"
 | 
			
		||||
	kgo "go.unistack.org/micro-broker-kgo/v3"
 | 
			
		||||
	"go.unistack.org/micro/v3/broker"
 | 
			
		||||
	"go.unistack.org/micro/v3/logger"
 | 
			
		||||
	"go.unistack.org/micro/v3/metadata"
 | 
			
		||||
	kgo "go.unistack.org/micro-broker-kgo/v4"
 | 
			
		||||
	"go.unistack.org/micro/v4/broker"
 | 
			
		||||
	"go.unistack.org/micro/v4/codec"
 | 
			
		||||
	"go.unistack.org/micro/v4/logger"
 | 
			
		||||
	"go.unistack.org/micro/v4/logger/slog"
 | 
			
		||||
	"go.unistack.org/micro/v4/metadata"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
var (
 | 
			
		||||
	msgcnt   = int64(12000000)
 | 
			
		||||
	msgcnt   = int64(1200)
 | 
			
		||||
	group    = "38"
 | 
			
		||||
	prefill  = false
 | 
			
		||||
	loglevel = logger.InfoLevel
 | 
			
		||||
	prefill  = true
 | 
			
		||||
	loglevel = logger.ErrorLevel
 | 
			
		||||
	cluster  *kfake.Cluster
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
var bm = &broker.Message{
 | 
			
		||||
	Header: map[string]string{"hkey": "hval", metadata.HeaderTopic: "test"},
 | 
			
		||||
	Body:   []byte(`"body"`),
 | 
			
		||||
func TestMain(m *testing.M) {
 | 
			
		||||
	cluster = kfake.MustCluster(
 | 
			
		||||
		kfake.AllowAutoTopicCreation(),
 | 
			
		||||
	)
 | 
			
		||||
	defer cluster.Close()
 | 
			
		||||
	m.Run()
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func TestFail(t *testing.T) {
 | 
			
		||||
	logger.DefaultLogger = slog.NewLogger()
 | 
			
		||||
	if err := logger.DefaultLogger.Init(logger.WithLevel(loglevel)); err != nil {
 | 
			
		||||
		t.Fatal(err)
 | 
			
		||||
	}
 | 
			
		||||
	ctx := context.Background()
 | 
			
		||||
 | 
			
		||||
	b := kgo.NewBroker(
 | 
			
		||||
		broker.ContentType("application/octet-stream"),
 | 
			
		||||
		broker.Codec("application/octet-stream", codec.NewCodec()),
 | 
			
		||||
		broker.Addrs(cluster.ListenAddrs()...),
 | 
			
		||||
		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++ {
 | 
			
		||||
		m, err := b.NewMessage(ctx, metadata.Pairs("hkey", "hval"), []byte(`test`))
 | 
			
		||||
		if err != nil {
 | 
			
		||||
			t.Fatal(err)
 | 
			
		||||
		}
 | 
			
		||||
		msgs = append(msgs, m)
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	go func() {
 | 
			
		||||
		for _, msg := range msgs {
 | 
			
		||||
			//		t.Logf("broker publish")
 | 
			
		||||
			if err := b.Publish(ctx, "test.fail", msg); err != nil {
 | 
			
		||||
				t.Fatal(err)
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
	}()
 | 
			
		||||
	//	t.Skip()
 | 
			
		||||
 | 
			
		||||
	idx := int64(0)
 | 
			
		||||
	fn := func(msg broker.Message) error {
 | 
			
		||||
		atomic.AddInt64(&idx, 1)
 | 
			
		||||
		time.Sleep(100 * time.Millisecond)
 | 
			
		||||
		// t.Logf("ack")
 | 
			
		||||
		return msg.Ack()
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	sub, err := b.Subscribe(ctx, "test.fail", 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
 | 
			
		||||
		}
 | 
			
		||||
		t.Logf("health sleep")
 | 
			
		||||
		time.Sleep(100 * time.Millisecond)
 | 
			
		||||
		if err := b.Disconnect(ctx); err != nil {
 | 
			
		||||
			t.Fatal(err)
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func TestConnect(t *testing.T) {
 | 
			
		||||
	var addrs []string
 | 
			
		||||
	ctx := context.TODO()
 | 
			
		||||
	b := kgo.NewBroker(
 | 
			
		||||
		broker.Addrs(addrs...),
 | 
			
		||||
		broker.ContentType("application/octet-stream"),
 | 
			
		||||
		broker.Codec("application/octet-stream", codec.NewCodec()),
 | 
			
		||||
		broker.Addrs(cluster.ListenAddrs()...),
 | 
			
		||||
		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),
 | 
			
		||||
			kg.AllowAutoTopicCreation(),
 | 
			
		||||
		),
 | 
			
		||||
	)
 | 
			
		||||
	if err := b.Init(); err != nil {
 | 
			
		||||
		t.Fatal(err)
 | 
			
		||||
@@ -46,27 +147,23 @@ func TestConnect(t *testing.T) {
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func TestPubSub(t *testing.T) {
 | 
			
		||||
	if tr := os.Getenv("INTEGRATION_TESTS"); len(tr) > 0 {
 | 
			
		||||
		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)
 | 
			
		||||
	}
 | 
			
		||||
	ctx := context.Background()
 | 
			
		||||
 | 
			
		||||
	var addrs []string
 | 
			
		||||
	if addr := os.Getenv("BROKER_ADDRS"); len(addr) == 0 {
 | 
			
		||||
		addrs = []string{"127.0.0.1:29091", "127.0.0.2:29092", "127.0.0.3:29093"}
 | 
			
		||||
	} else {
 | 
			
		||||
		addrs = strings.Split(addr, ",")
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	b := kgo.NewBroker(
 | 
			
		||||
		broker.Addrs(addrs...),
 | 
			
		||||
		broker.ContentType("application/octet-stream"),
 | 
			
		||||
		broker.Codec("application/octet-stream", codec.NewCodec()),
 | 
			
		||||
		broker.Addrs(cluster.ListenAddrs()...),
 | 
			
		||||
		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),
 | 
			
		||||
			kg.AllowAutoTopicCreation(),
 | 
			
		||||
		),
 | 
			
		||||
	)
 | 
			
		||||
 | 
			
		||||
	if err := b.Init(); err != nil {
 | 
			
		||||
		t.Fatal(err)
 | 
			
		||||
	}
 | 
			
		||||
@@ -81,25 +178,26 @@ func TestPubSub(t *testing.T) {
 | 
			
		||||
		}
 | 
			
		||||
	}()
 | 
			
		||||
	if prefill {
 | 
			
		||||
		msgs := make([]*broker.Message, 0, msgcnt)
 | 
			
		||||
		msgs := make([]broker.Message, 0, msgcnt)
 | 
			
		||||
		for i := int64(0); i < msgcnt; i++ {
 | 
			
		||||
			msgs = append(msgs, bm)
 | 
			
		||||
			m, _ := b.NewMessage(ctx, metadata.Pairs("hkey", "hval"), []byte(`test`))
 | 
			
		||||
			msgs = append(msgs, m)
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		if err := b.BatchPublish(ctx, msgs); err != nil {
 | 
			
		||||
		if err := b.Publish(ctx, "test.pubsub", msgs...); err != nil {
 | 
			
		||||
			t.Fatal(err)
 | 
			
		||||
		}
 | 
			
		||||
		//	t.Skip()
 | 
			
		||||
	}
 | 
			
		||||
	done := make(chan bool, 1)
 | 
			
		||||
	idx := int64(0)
 | 
			
		||||
	fn := func(msg broker.Event) error {
 | 
			
		||||
	fn := func(msg broker.Message) error {
 | 
			
		||||
		atomic.AddInt64(&idx, 1)
 | 
			
		||||
		// time.Sleep(200 * time.Millisecond)
 | 
			
		||||
		return msg.Ack()
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	sub, err := b.Subscribe(ctx, "test", fn,
 | 
			
		||||
	sub, err := b.Subscribe(ctx, "test.pubsub", fn,
 | 
			
		||||
		broker.SubscribeAutoAck(true),
 | 
			
		||||
		broker.SubscribeGroup(group),
 | 
			
		||||
		broker.SubscribeBodyOnly(true))
 | 
			
		||||
@@ -124,7 +222,7 @@ func TestPubSub(t *testing.T) {
 | 
			
		||||
				if prc := atomic.LoadInt64(&idx); prc == msgcnt {
 | 
			
		||||
					close(done)
 | 
			
		||||
				} else {
 | 
			
		||||
					fmt.Printf("processed %v\n", prc)
 | 
			
		||||
					t.Logf("processed %v of %v\n", prc, msgcnt)
 | 
			
		||||
				}
 | 
			
		||||
			case <-ticker.C:
 | 
			
		||||
				close(done)
 | 
			
		||||
 
 | 
			
		||||
@@ -4,7 +4,7 @@ import (
 | 
			
		||||
	"context"
 | 
			
		||||
 | 
			
		||||
	"github.com/twmb/franz-go/pkg/kgo"
 | 
			
		||||
	"go.unistack.org/micro/v3/logger"
 | 
			
		||||
	"go.unistack.org/micro/v4/logger"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
type mlogger struct {
 | 
			
		||||
@@ -28,11 +28,8 @@ func (l *mlogger) Log(lvl kgo.LogLevel, msg string, args ...interface{}) {
 | 
			
		||||
	default:
 | 
			
		||||
		return
 | 
			
		||||
	}
 | 
			
		||||
	if len(args) > 0 {
 | 
			
		||||
		l.l.Log(l.ctx, mlvl, append([]interface{}{msg}, args...)...)
 | 
			
		||||
	} else {
 | 
			
		||||
		l.l.Log(l.ctx, mlvl, msg)
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	l.l.Log(l.ctx, mlvl, msg, args...)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (l *mlogger) Level() kgo.LogLevel {
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										4
									
								
								meter.go
									
									
									
									
									
								
							
							
						
						
									
										4
									
								
								meter.go
									
									
									
									
									
								
							@@ -6,7 +6,7 @@ import (
 | 
			
		||||
	"time"
 | 
			
		||||
 | 
			
		||||
	"github.com/twmb/franz-go/pkg/kgo"
 | 
			
		||||
	"go.unistack.org/micro/v3/meter"
 | 
			
		||||
	"go.unistack.org/micro/v4/meter"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
type hookMeter struct {
 | 
			
		||||
@@ -61,7 +61,7 @@ const (
 | 
			
		||||
	labelTopic   = "topic"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
func (m *hookMeter) OnGroupManageError(err error) {
 | 
			
		||||
func (m *hookMeter) OnGroupManageError(_ error) {
 | 
			
		||||
	m.meter.Counter(metricBrokerGroupErrors).Inc()
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										54
									
								
								options.go
									
									
									
									
									
								
							
							
						
						
									
										54
									
								
								options.go
									
									
									
									
									
								
							@@ -5,8 +5,7 @@ import (
 | 
			
		||||
	"time"
 | 
			
		||||
 | 
			
		||||
	"github.com/twmb/franz-go/pkg/kgo"
 | 
			
		||||
	"go.unistack.org/micro/v3/broker"
 | 
			
		||||
	"go.unistack.org/micro/v3/client"
 | 
			
		||||
	"go.unistack.org/micro/v4/broker"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
var (
 | 
			
		||||
@@ -15,7 +14,7 @@ var (
 | 
			
		||||
	DefaultCommitInterval = 5 * time.Second
 | 
			
		||||
 | 
			
		||||
	// DefaultStatsInterval specifies how fast check consumer lag
 | 
			
		||||
	DefaultStatsInterval = 5 * time.Second
 | 
			
		||||
	DefaultStatsInterval = 30 * time.Second
 | 
			
		||||
 | 
			
		||||
	// DefaultSubscribeMaxInflight specifies how much messages keep inflight
 | 
			
		||||
	DefaultSubscribeMaxInflight = 100
 | 
			
		||||
@@ -28,16 +27,11 @@ func SubscribeContext(ctx context.Context) broker.SubscribeOption {
 | 
			
		||||
	return broker.SetSubscribeOption(subscribeContextKey{}, ctx)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
type publishKey struct{}
 | 
			
		||||
type messageKey struct{}
 | 
			
		||||
 | 
			
		||||
// PublishKey set the kafka message key (broker option)
 | 
			
		||||
func PublishKey(key []byte) broker.PublishOption {
 | 
			
		||||
	return broker.SetPublishOption(publishKey{}, key)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// ClientPublishKey set the kafka message key (client option)
 | 
			
		||||
func ClientPublishKey(key []byte) client.PublishOption {
 | 
			
		||||
	return client.SetPublishOption(publishKey{}, key)
 | 
			
		||||
// MessageKey set the kafka message key (broker option)
 | 
			
		||||
func MessageKey(key []byte) broker.MessageOption {
 | 
			
		||||
	return broker.SetMessageOption(messageKey{}, key)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
type optionsKey struct{}
 | 
			
		||||
@@ -72,6 +66,12 @@ func SubscribeOptions(opts ...kgo.Opt) broker.SubscribeOption {
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
type fatalOnErrorKey struct{}
 | 
			
		||||
 | 
			
		||||
func FatalOnError(b bool) broker.Option {
 | 
			
		||||
	return broker.SetOption(fatalOnErrorKey{}, b)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
type clientIDKey struct{}
 | 
			
		||||
 | 
			
		||||
func ClientID(id string) broker.Option {
 | 
			
		||||
@@ -98,14 +98,28 @@ func SubscribeMaxInFlight(n int) broker.SubscribeOption {
 | 
			
		||||
	return broker.SetSubscribeOption(subscribeMaxInflightKey{}, n)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
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)
 | 
			
		||||
// SubscribeMaxInFlight max queued messages
 | 
			
		||||
func SubscribeFatalOnError(b bool) broker.SubscribeOption {
 | 
			
		||||
	return broker.SetSubscribeOption(fatalOnErrorKey{}, b)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// ClientPublishKey set the kafka message key (client option)
 | 
			
		||||
func ClientPublishPromise(fn func(*kgo.Record, error)) client.PublishOption {
 | 
			
		||||
	return client.SetPublishOption(publishPromiseKey{}, fn)
 | 
			
		||||
type messagePromiseKey struct{}
 | 
			
		||||
 | 
			
		||||
// MessagePromise set the kafka promise func for Produce
 | 
			
		||||
func MessagePromise(fn func(*kgo.Record, error)) broker.MessageOption {
 | 
			
		||||
	return broker.SetMessageOption(messagePromiseKey{}, fn)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
type subscribeMessagePoolKey struct{}
 | 
			
		||||
 | 
			
		||||
// SubscribeMessagePool optionaly enabled/disable message pool
 | 
			
		||||
func SubscribeMessagePool(b bool) broker.SubscribeOption {
 | 
			
		||||
	return broker.SetSubscribeOption(subscribeMessagePoolKey{}, b)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
type exposeLagKey struct{}
 | 
			
		||||
 | 
			
		||||
// ExposeLag enabled subscriber lag via [meter.Meter]
 | 
			
		||||
func ExposeLag(b bool) broker.Option {
 | 
			
		||||
	return broker.SetOption(exposeLagKey{}, b)
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										308
									
								
								subscriber.go
									
									
									
									
									
								
							
							
						
						
									
										308
									
								
								subscriber.go
									
									
									
									
									
								
							@@ -2,16 +2,19 @@ package kgo
 | 
			
		||||
 | 
			
		||||
import (
 | 
			
		||||
	"context"
 | 
			
		||||
	"fmt"
 | 
			
		||||
	"strconv"
 | 
			
		||||
	"sync"
 | 
			
		||||
	"sync/atomic"
 | 
			
		||||
	"time"
 | 
			
		||||
 | 
			
		||||
	"github.com/twmb/franz-go/pkg/kadm"
 | 
			
		||||
	"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"
 | 
			
		||||
	"go.unistack.org/micro/v3/semconv"
 | 
			
		||||
	"github.com/twmb/franz-go/pkg/kmsg"
 | 
			
		||||
	"go.unistack.org/micro/v4/broker"
 | 
			
		||||
	"go.unistack.org/micro/v4/logger"
 | 
			
		||||
	"go.unistack.org/micro/v4/metadata"
 | 
			
		||||
	"go.unistack.org/micro/v4/semconv"
 | 
			
		||||
	"go.unistack.org/micro/v4/tracer"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
type tp struct {
 | 
			
		||||
@@ -20,45 +23,53 @@ type tp struct {
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
type consumer struct {
 | 
			
		||||
	c         *kgo.Client
 | 
			
		||||
	topic       string
 | 
			
		||||
	partition int32
 | 
			
		||||
	opts      broker.SubscribeOptions
 | 
			
		||||
	kopts     broker.Options
 | 
			
		||||
	handler   broker.Handler
 | 
			
		||||
	c           *kgo.Client
 | 
			
		||||
	htracer     *hookTracer
 | 
			
		||||
	quit        chan struct{}
 | 
			
		||||
	done        chan struct{}
 | 
			
		||||
	recs        chan kgo.FetchTopicPartition
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
type subscriber struct {
 | 
			
		||||
	c         *kgo.Client
 | 
			
		||||
	topic     string
 | 
			
		||||
	opts      broker.SubscribeOptions
 | 
			
		||||
	kopts       broker.Options
 | 
			
		||||
	handler   broker.Handler
 | 
			
		||||
	closed    bool
 | 
			
		||||
	done      chan struct{}
 | 
			
		||||
	consumers map[tp]*consumer
 | 
			
		||||
	sync.RWMutex
 | 
			
		||||
	partition   int32
 | 
			
		||||
	opts        broker.SubscribeOptions
 | 
			
		||||
	handler     interface{}
 | 
			
		||||
	connected   *atomic.Uint32
 | 
			
		||||
	messagePool bool
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (s *subscriber) Options() broker.SubscribeOptions {
 | 
			
		||||
type Subscriber struct {
 | 
			
		||||
	consumers    map[tp]*consumer
 | 
			
		||||
	c            *kgo.Client
 | 
			
		||||
	htracer      *hookTracer
 | 
			
		||||
	topic        string
 | 
			
		||||
	messagePool  bool
 | 
			
		||||
	handler      interface{}
 | 
			
		||||
	done         chan struct{}
 | 
			
		||||
	kopts        broker.Options
 | 
			
		||||
	opts         broker.SubscribeOptions
 | 
			
		||||
	connected    *atomic.Uint32
 | 
			
		||||
	mu           sync.RWMutex
 | 
			
		||||
	closed       bool
 | 
			
		||||
	fatalOnError bool
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (s *Subscriber) Client() *kgo.Client {
 | 
			
		||||
	return s.c
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (s *Subscriber) Options() broker.SubscribeOptions {
 | 
			
		||||
	return s.opts
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (s *subscriber) Topic() string {
 | 
			
		||||
func (s *Subscriber) Topic() string {
 | 
			
		||||
	return s.topic
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (s *subscriber) Unsubscribe(ctx context.Context) error {
 | 
			
		||||
func (s *Subscriber) Unsubscribe(ctx context.Context) error {
 | 
			
		||||
	if s.closed {
 | 
			
		||||
		return nil
 | 
			
		||||
	}
 | 
			
		||||
	select {
 | 
			
		||||
	// case <-ctx.Done():
 | 
			
		||||
	//	return ctx.Err()
 | 
			
		||||
	default:
 | 
			
		||||
 | 
			
		||||
	s.c.PauseFetchTopics(s.topic)
 | 
			
		||||
	s.c.CloseAllowingRebalance()
 | 
			
		||||
	kc := make(map[string][]int32)
 | 
			
		||||
@@ -69,52 +80,19 @@ func (s *subscriber) Unsubscribe(ctx context.Context) error {
 | 
			
		||||
	close(s.done)
 | 
			
		||||
	s.closed = true
 | 
			
		||||
	s.c.ResumeFetchTopics(s.topic)
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	return nil
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (s *subscriber) poll(ctx context.Context) {
 | 
			
		||||
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
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	go func() {
 | 
			
		||||
		ac := kadm.NewClient(s.c)
 | 
			
		||||
		ticker := time.NewTicker(DefaultStatsInterval)
 | 
			
		||||
 | 
			
		||||
		for {
 | 
			
		||||
			select {
 | 
			
		||||
			case <-ctx.Done():
 | 
			
		||||
				ticker.Stop()
 | 
			
		||||
				return
 | 
			
		||||
			case <-ticker.C:
 | 
			
		||||
				dgls, err := ac.Lag(ctx, s.opts.Group)
 | 
			
		||||
				if err != nil || !dgls.Ok() {
 | 
			
		||||
					continue
 | 
			
		||||
				}
 | 
			
		||||
 | 
			
		||||
				dgl, ok := dgls[s.opts.Group]
 | 
			
		||||
				if !ok {
 | 
			
		||||
					continue
 | 
			
		||||
				}
 | 
			
		||||
				lmap, ok := dgl.Lag[s.topic]
 | 
			
		||||
				if !ok {
 | 
			
		||||
					continue
 | 
			
		||||
				}
 | 
			
		||||
 | 
			
		||||
				for tp := range s.consumers {
 | 
			
		||||
					if v, ok := lmap[tp.p]; ok {
 | 
			
		||||
						s.kopts.Meter.Counter(semconv.BrokerGroupLag, "topic", s.topic, "group", s.opts.Group, "partition", strconv.Itoa(int(tp.p)), "lag", strconv.Itoa(int(v.Lag)))
 | 
			
		||||
					}
 | 
			
		||||
				}
 | 
			
		||||
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
	}()
 | 
			
		||||
 | 
			
		||||
	for {
 | 
			
		||||
		select {
 | 
			
		||||
		case <-ctx.Done():
 | 
			
		||||
@@ -129,164 +107,182 @@ func (s *subscriber) poll(ctx context.Context) {
 | 
			
		||||
				return
 | 
			
		||||
			}
 | 
			
		||||
			fetches.EachError(func(t string, p int32, err error) {
 | 
			
		||||
				s.kopts.Logger.Fatalf(ctx, "[kgo] fetch topic %s partition %d err: %v", t, p, err)
 | 
			
		||||
				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) {
 | 
			
		||||
				tp := tp{p.Topic, p.Partition}
 | 
			
		||||
				s.consumers[tp].recs <- p
 | 
			
		||||
				tps := tp{p.Topic, p.Partition}
 | 
			
		||||
				s.mu.Lock()
 | 
			
		||||
				c := s.consumers[tps]
 | 
			
		||||
				s.mu.Unlock()
 | 
			
		||||
				if c != nil {
 | 
			
		||||
					c.recs <- p
 | 
			
		||||
				}
 | 
			
		||||
			})
 | 
			
		||||
			s.c.AllowRebalance()
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (s *subscriber) killConsumers(ctx context.Context, lost map[string][]int32) {
 | 
			
		||||
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 {
 | 
			
		||||
			tp := tp{topic, partition}
 | 
			
		||||
			pc := s.consumers[tp]
 | 
			
		||||
			delete(s.consumers, tp)
 | 
			
		||||
			tps := tp{topic, partition}
 | 
			
		||||
			s.mu.Lock()
 | 
			
		||||
			pc, ok := s.consumers[tps]
 | 
			
		||||
			s.mu.Unlock()
 | 
			
		||||
			if !ok {
 | 
			
		||||
				continue
 | 
			
		||||
			}
 | 
			
		||||
			s.mu.Lock()
 | 
			
		||||
			delete(s.consumers, tps)
 | 
			
		||||
			s.mu.Unlock()
 | 
			
		||||
			close(pc.quit)
 | 
			
		||||
			s.kopts.Logger.Debugf(ctx, "[kgo] waiting for work to finish topic %s partition %d", topic, partition)
 | 
			
		||||
			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) lost(ctx context.Context, _ *kgo.Client, lost map[string][]int32) {
 | 
			
		||||
	s.kopts.Logger.Debugf(ctx, "[kgo] lost %#+v", lost)
 | 
			
		||||
	s.killConsumers(ctx, lost)
 | 
			
		||||
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) revoked(ctx context.Context, c *kgo.Client, revoked map[string][]int32) {
 | 
			
		||||
	s.kopts.Logger.Debugf(ctx, "[kgo] revoked %#+v", revoked)
 | 
			
		||||
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.Errorf(ctx, "[kgo] revoked CommitMarkedOffsets err: %v", err)
 | 
			
		||||
		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) {
 | 
			
		||||
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,
 | 
			
		||||
				messagePool: s.messagePool,
 | 
			
		||||
				kopts:       s.kopts,
 | 
			
		||||
				opts:        s.opts,
 | 
			
		||||
				connected:   s.connected,
 | 
			
		||||
			}
 | 
			
		||||
			s.mu.Lock()
 | 
			
		||||
			s.consumers[tp{topic, partition}] = pc
 | 
			
		||||
			s.mu.Unlock()
 | 
			
		||||
			go pc.consume()
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (pc *consumer) consume() {
 | 
			
		||||
	defer close(pc.done)
 | 
			
		||||
	pc.kopts.Logger.Debugf(pc.kopts.Context, "starting, topic %s partition %d", pc.topic, pc.partition)
 | 
			
		||||
	defer pc.kopts.Logger.Debugf(pc.kopts.Context, "killing, topic %s partition %d", pc.topic, pc.partition)
 | 
			
		||||
	var err error
 | 
			
		||||
 | 
			
		||||
	eh := pc.kopts.ErrorHandler
 | 
			
		||||
	if pc.opts.ErrorHandler != nil {
 | 
			
		||||
		eh = pc.opts.ErrorHandler
 | 
			
		||||
	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))
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	var pm *kgoMessage
 | 
			
		||||
 | 
			
		||||
	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))
 | 
			
		||||
 | 
			
		||||
				if pc.messagePool {
 | 
			
		||||
					pm = messagePool.Get().(*kgoMessage)
 | 
			
		||||
				} else {
 | 
			
		||||
					pm = &kgoMessage{}
 | 
			
		||||
				}
 | 
			
		||||
				pm.body = record.Value
 | 
			
		||||
				pm.topic = record.Topic
 | 
			
		||||
				pm.ack = false
 | 
			
		||||
				pm.hdr = metadata.New(len(record.Headers))
 | 
			
		||||
				pm.ctx = ctx
 | 
			
		||||
				for _, hdr := range record.Headers {
 | 
			
		||||
					p.msg.Header.Set(hdr.Key, string(hdr.Value))
 | 
			
		||||
					pm.hdr.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 err := pc.kopts.Codec.Unmarshal(record.Value, p.msg); err != nil {
 | 
			
		||||
						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)
 | 
			
		||||
				pm.hdr.Set("Micro-Offset", strconv.FormatInt(record.Offset, 10))
 | 
			
		||||
				pm.hdr.Set("Micro-Partition", strconv.FormatInt(int64(record.Partition), 10))
 | 
			
		||||
				pm.hdr.Set("Micro-Topic", record.Topic)
 | 
			
		||||
				pm.hdr.Set("Micro-Key", string(record.Key))
 | 
			
		||||
				pm.hdr.Set("Micro-Timestamp", strconv.FormatInt(record.Timestamp.Unix(), 10))
 | 
			
		||||
				switch h := pc.handler.(type) {
 | 
			
		||||
				case func(broker.Message) error:
 | 
			
		||||
					err = h(pm)
 | 
			
		||||
				case func([]broker.Message) error:
 | 
			
		||||
					err = h([]broker.Message{pm})
 | 
			
		||||
				}
 | 
			
		||||
 | 
			
		||||
				pc.kopts.Meter.Counter(semconv.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Dec()
 | 
			
		||||
							if p.ack {
 | 
			
		||||
				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()
 | 
			
		||||
				} else if pc.opts.AutoAck {
 | 
			
		||||
					pm.ack = true
 | 
			
		||||
				}
 | 
			
		||||
 | 
			
		||||
				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())
 | 
			
		||||
 | 
			
		||||
				ack := pm.ack
 | 
			
		||||
				if pc.messagePool {
 | 
			
		||||
					messagePool.Put(p)
 | 
			
		||||
				}
 | 
			
		||||
				if ack {
 | 
			
		||||
					pc.c.MarkCommitRecords(record)
 | 
			
		||||
				} else {
 | 
			
		||||
								eventPool.Put(p)
 | 
			
		||||
								pc.kopts.Logger.Fatalf(pc.kopts.Context, "[kgo] ErrLostMessage wtf?")
 | 
			
		||||
					if sp != nil {
 | 
			
		||||
						sp.Finish()
 | 
			
		||||
					}
 | 
			
		||||
					//					pc.connected.Store(0)
 | 
			
		||||
					pc.kopts.Logger.Fatal(pc.kopts.Context, "[kgo] message not commited")
 | 
			
		||||
					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 {
 | 
			
		||||
							if pc.kopts.Logger.V(logger.ErrorLevel) {
 | 
			
		||||
								pc.kopts.Logger.Errorf(pc.kopts.Context, "[kgo]: failed to unmarshal: %v", 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.kopts.Logger.Fatalf(pc.kopts.Context, "[kgo] Unmarshal err not handled wtf?")
 | 
			
		||||
						return
 | 
			
		||||
					}
 | 
			
		||||
				}
 | 
			
		||||
				err := pc.handler(p)
 | 
			
		||||
				if err == nil {
 | 
			
		||||
					pc.kopts.Meter.Counter(semconv.SubscribeMessageTotal, "endpoint", record.Topic, "topic", record.Topic, "status", "success").Inc()
 | 
			
		||||
				} else {
 | 
			
		||||
					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 {
 | 
			
		||||
						_ = eh(p)
 | 
			
		||||
					} else {
 | 
			
		||||
						if pc.kopts.Logger.V(logger.ErrorLevel) {
 | 
			
		||||
							pc.kopts.Logger.Errorf(pc.kopts.Context, "[kgo]: subscriber error: %v", 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.kopts.Logger.Fatalf(pc.kopts.Context, "[kgo] ErrLostMessage wtf?")
 | 
			
		||||
					return
 | 
			
		||||
				if sp != nil {
 | 
			
		||||
					sp.Finish()
 | 
			
		||||
				}
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										138
									
								
								tracer.go
									
									
									
									
									
								
							
							
						
						
									
										138
									
								
								tracer.go
									
									
									
									
									
								
							@@ -2,56 +2,29 @@ package kgo
 | 
			
		||||
 | 
			
		||||
import (
 | 
			
		||||
	"context"
 | 
			
		||||
	"net"
 | 
			
		||||
	"time"
 | 
			
		||||
	"unicode/utf8"
 | 
			
		||||
 | 
			
		||||
	"github.com/twmb/franz-go/pkg/kgo"
 | 
			
		||||
	semconv "go.opentelemetry.io/otel/semconv/v1.18.0"
 | 
			
		||||
	"go.unistack.org/micro/v3/tracer"
 | 
			
		||||
	"go.unistack.org/micro/v4/metadata"
 | 
			
		||||
	"go.unistack.org/micro/v4/tracer"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
type hookTracer struct {
 | 
			
		||||
	tracer   tracer.Tracer
 | 
			
		||||
	clientID string
 | 
			
		||||
	group    string
 | 
			
		||||
	tracer   tracer.Tracer
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
var messagingSystem = semconv.MessagingSystemKey.String("kafka")
 | 
			
		||||
 | 
			
		||||
var (
 | 
			
		||||
	_ kgo.HookBrokerConnect       = &hookTracer{}
 | 
			
		||||
	_ kgo.HookBrokerDisconnect    = &hookTracer{}
 | 
			
		||||
	_ kgo.HookBrokerRead          = &hookTracer{}
 | 
			
		||||
	_ kgo.HookBrokerThrottle      = &hookTracer{}
 | 
			
		||||
	_ kgo.HookBrokerWrite         = &hookTracer{}
 | 
			
		||||
	_ kgo.HookFetchBatchRead      = &hookTracer{}
 | 
			
		||||
	_ kgo.HookProduceBatchWritten = &hookTracer{}
 | 
			
		||||
	_ kgo.HookGroupManageError    = &hookTracer{}
 | 
			
		||||
	_ kgo.HookProduceRecordBuffered   = (*hookTracer)(nil)
 | 
			
		||||
	_ kgo.HookProduceRecordUnbuffered = (*hookTracer)(nil)
 | 
			
		||||
	_ kgo.HookFetchRecordBuffered     = (*hookTracer)(nil)
 | 
			
		||||
	_ kgo.HookFetchRecordUnbuffered   = (*hookTracer)(nil)
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
func (m *hookTracer) OnGroupManageError(err error) {
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (m *hookTracer) OnBrokerConnect(meta kgo.BrokerMetadata, _ time.Duration, _ net.Conn, err error) {
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (m *hookTracer) OnBrokerDisconnect(meta kgo.BrokerMetadata, _ net.Conn) {
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (m *hookTracer) OnBrokerWrite(meta kgo.BrokerMetadata, _ int16, bytesWritten int, writeWait, timeToWrite time.Duration, err error) {
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (m *hookTracer) OnBrokerRead(meta kgo.BrokerMetadata, _ int16, bytesRead int, readWait, timeToRead time.Duration, err error) {
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (m *hookTracer) OnBrokerThrottle(meta kgo.BrokerMetadata, throttleInterval time.Duration, _ bool) {
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (m *hookTracer) OnProduceBatchWritten(meta kgo.BrokerMetadata, topic string, _ int32, kmetrics kgo.ProduceBatchMetrics) {
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (m *hookTracer) OnFetchBatchRead(meta kgo.BrokerMetadata, topic string, _ int32, kmetrics kgo.FetchBatchMetrics) {
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// OnProduceRecordBuffered starts a new span for the "publish" operation on a
 | 
			
		||||
// buffered record.
 | 
			
		||||
//
 | 
			
		||||
@@ -59,9 +32,12 @@ func (m *hookTracer) OnFetchBatchRead(meta kgo.BrokerMetadata, topic string, _ i
 | 
			
		||||
// 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{}{
 | 
			
		||||
		semconv.MessagingSystemKey.String("kafka"),
 | 
			
		||||
		messagingSystem,
 | 
			
		||||
		semconv.MessagingDestinationKindTopic,
 | 
			
		||||
		semconv.MessagingDestinationName(r.Topic),
 | 
			
		||||
		semconv.MessagingOperationPublish,
 | 
			
		||||
@@ -74,12 +50,28 @@ func (m *hookTracer) OnProduceRecordBuffered(r *kgo.Record) {
 | 
			
		||||
		tracer.WithSpanLabels(attrs...),
 | 
			
		||||
		tracer.WithSpanKind(tracer.SpanKindProducer),
 | 
			
		||||
	}
 | 
			
		||||
	// Start the "publish" span.
 | 
			
		||||
	ctx, _ := m.tracer.Start(r.Context, r.Topic+" publish", opts...)
 | 
			
		||||
	// Inject the span context into the record.
 | 
			
		||||
	// t.propagators.Inject(ctx, NewRecordCarrier(r))
 | 
			
		||||
	// Update the record context.
 | 
			
		||||
	r.Context = ctx
 | 
			
		||||
 | 
			
		||||
	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
 | 
			
		||||
@@ -88,17 +80,18 @@ func (m *hookTracer) OnProduceRecordBuffered(r *kgo.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) {
 | 
			
		||||
	span, ok := tracer.SpanFromContext(r.Context)
 | 
			
		||||
	if !ok {
 | 
			
		||||
	if !m.tracer.Enabled() {
 | 
			
		||||
		return
 | 
			
		||||
	}
 | 
			
		||||
	defer span.Finish()
 | 
			
		||||
	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
 | 
			
		||||
@@ -109,9 +102,12 @@ func (m *hookTracer) OnProduceRecordUnbuffered(r *kgo.Record, err error) {
 | 
			
		||||
// 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{}{
 | 
			
		||||
		semconv.MessagingSystemKey.String("kafka"),
 | 
			
		||||
		messagingSystem,
 | 
			
		||||
		semconv.MessagingSourceKindTopic,
 | 
			
		||||
		semconv.MessagingSourceName(r.Topic),
 | 
			
		||||
		semconv.MessagingOperationReceive,
 | 
			
		||||
@@ -132,20 +128,33 @@ func (m *hookTracer) OnFetchRecordBuffered(r *kgo.Record) {
 | 
			
		||||
	if r.Context == nil {
 | 
			
		||||
		r.Context = context.Background()
 | 
			
		||||
	}
 | 
			
		||||
	// Extract the span context from the record.
 | 
			
		||||
	// ctx := t.propagators.Extract(r.Context, NewRecordCarrier(r))
 | 
			
		||||
	// Start the "receive" span.
 | 
			
		||||
	newCtx, _ := m.tracer.Start(r.Context, r.Topic+" receive", opts...)
 | 
			
		||||
	// Update the record context.
 | 
			
		||||
	r.Context = newCtx
 | 
			
		||||
	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 span, ok := tracer.SpanFromContext(r.Context); ok {
 | 
			
		||||
		defer span.Finish()
 | 
			
		||||
	if !m.tracer.Enabled() {
 | 
			
		||||
		return
 | 
			
		||||
	}
 | 
			
		||||
	span, _ := tracer.SpanFromContext(r.Context)
 | 
			
		||||
	span.Finish()
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// WithProcessSpan starts a new span for the "process" operation on a consumer
 | 
			
		||||
@@ -158,9 +167,16 @@ func (m *hookTracer) OnFetchRecordUnbuffered(r *kgo.Record, _ bool) {
 | 
			
		||||
// 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{}{
 | 
			
		||||
		semconv.MessagingSystemKey.String("kafka"),
 | 
			
		||||
		messagingSystem,
 | 
			
		||||
		semconv.MessagingSourceKindTopic,
 | 
			
		||||
		semconv.MessagingSourceName(r.Topic),
 | 
			
		||||
		semconv.MessagingOperationProcess,
 | 
			
		||||
@@ -182,8 +198,16 @@ func (m *hookTracer) WithProcessSpan(r *kgo.Record) (context.Context, tracer.Spa
 | 
			
		||||
	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, r.Topic+" process", opts...)
 | 
			
		||||
	return m.tracer.Start(r.Context, "sdk.broker", opts...)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func maybeKeyAttr(attrs []interface{}, r *kgo.Record) []interface{} {
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user