Compare commits
167 Commits
Author | SHA1 | Date | |
---|---|---|---|
90365a455c | |||
6a218ca7b2 | |||
ba9b88c650 | |||
aedd60ea87 | |||
ea2ac477be | |||
c1fa2f639d | |||
8e3f2c67d7 | |||
e66194695e | |||
894d6f4f20 | |||
d404fa31ab | |||
88777a29ad | |||
23c2903c21 | |||
8fcc23f639 | |||
25dda1f34c | |||
fe66086c40 | |||
7329bc23bc | |||
c240631cdb | |||
6a68533824 | |||
058b6354c0 | |||
1f4cf11afe | |||
39177da1d0 | |||
d559db4050 | |||
aa946c469a | |||
9c4d88bb69 | |||
56288f46b1 | |||
81dcef8b28 | |||
ec7a22b2dc | |||
d2ac0c1360 | |||
69dd8c4eea | |||
27a6a923cd | |||
0a395235d6 | |||
23f0ad0f2f | |||
4fcbe0a770 | |||
28c9865121 | |||
697413d829 | |||
8a64e8c5cc | |||
2c8ca8d14f | |||
769ac6322f | |||
52318d68b8 | |||
5c4332ffc4 | |||
3a86d4c0f4 | |||
8bbcc30d04 | |||
221b248b1f | |||
a9b13378f3 | |||
adb5c9bfc9 | |||
|
92bf44e543 | ||
e48ded17ee | |||
|
7753ecd14f | ||
7766fbf312 | |||
|
6916724a8b | ||
e584100c18 | |||
|
63cc0c1cc6 | ||
396e71e9f7 | |||
|
4709eaf769 | ||
366bdea3d0 | |||
|
947fca7cd5 | ||
97c55fa16b | |||
|
c845a00697 | ||
|
dbee3ac120 | ||
|
740926d262 | ||
|
03d78ef2ff | ||
|
90063ef841 | ||
7faf1dfbc8 | |||
|
5a80d798c6 | ||
0323c5fccc | |||
|
80e7f6b19f | ||
9a4cc96640 | |||
|
4a67d63e4e | ||
f69d96756e | |||
|
67dbeb2c57 | ||
328d15311b | |||
|
2899b963c4 | ||
|
78f07ac959 | ||
dc1ebd45be | |||
|
6925f0291d | ||
5d8a72fa86 | |||
|
f7096e71cf | ||
|
ab10ca9658 | ||
|
bb269b5879 | ||
24a6b4045e | |||
|
09b1b526b8 | ||
af9bca00a1 | |||
|
1c2cc611ef | ||
|
d6e18b5163 | ||
|
37d571076f | ||
|
ddba046c77 | ||
7390973672 | |||
6360f5e78f | |||
|
9a69314c25 | ||
|
a4eb047a58 | ||
|
7ad74ea1fc | ||
821b12484e | |||
893794dbf4 | |||
ea629d6e34 | |||
585c94ad65 | |||
1d100aee63 | |||
6ccc996fe6 | |||
0d8c5d3a86 | |||
203266aaea | |||
|
a7fed3241d | ||
|
d0dbb58f4b | ||
71de5058a7 | |||
|
0e0762180d | ||
80523cf9bb | |||
|
9c4f7d65d2 | ||
|
4b4add52a6 | ||
|
61003dd396 | ||
|
12bee708a0 | ||
|
f4a0c3e5de | ||
|
2e065f49c0 | ||
2a91aba7bf | |||
|
fe4cf8a492 | ||
|
cbf92e21e0 | ||
|
ce096a23c0 | ||
|
105faed19f | ||
d6ff088e1f | |||
|
a33b7c1ccb | ||
87b5b3dd9f | |||
3081e902d2 | |||
|
204cd9608c | ||
caefafeea7 | |||
|
05b0ede365 | ||
b3e8eeb6ff | |||
|
1a1e359a4e | ||
b7a77d4038 | |||
|
d1b6d2187a | ||
a4a88c1aad | |||
|
3a9c961474 | ||
0f0e095629 | |||
|
70a4aa1982 | ||
7cfe5bcd98 | |||
|
7ad07bd79e | ||
9d4aa6ce53 | |||
|
8f500ef92c | ||
f6bad32a6a | |||
|
dc30c68388 | ||
|
b099c2d0e0 | ||
|
389736e131 | ||
|
e774a716c5 | ||
|
f208bf9272 | ||
|
a0a86ef4f6 | ||
|
3a5716419d | ||
|
10188f073b | ||
|
df5999629c | ||
|
6b051b3fd8 | ||
|
d856988a16 | ||
bc0d2026ad | |||
1fc59df95b | |||
ff82f9f960 | |||
|
221f07ca97 | ||
44b9a59aab | |||
|
81cd4c1ec6 | ||
50d1343adb | |||
|
4c6b057a90 | ||
06acad41fe | |||
|
0ac121099f | ||
d30f3d200b | |||
4373f485ce | |||
|
9faac6a407 | ||
02134eacc2 | |||
|
be302e0816 | ||
cfd4fb611e | |||
|
619d9d0d70 | ||
ebad3e1369 | |||
|
485de5136f | ||
6ce9ed8e84 | |||
2c74b3232b |
20
.github/workflows/autoapprove.yml
vendored
Normal file
20
.github/workflows/autoapprove.yml
vendored
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
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
Normal file
21
.github/workflows/automerge.yml
vendored
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
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}}
|
13
.github/workflows/build.yml
vendored
13
.github/workflows/build.yml
vendored
@ -3,19 +3,20 @@ on:
|
|||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- master
|
||||||
|
- v3
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
name: test
|
name: test
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: setup
|
- name: setup
|
||||||
uses: actions/setup-go@v2
|
uses: actions/setup-go@v3
|
||||||
with:
|
with:
|
||||||
go-version: 1.16
|
go-version: 1.17
|
||||||
- name: checkout
|
- name: checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v3
|
||||||
- name: cache
|
- name: cache
|
||||||
uses: actions/cache@v2
|
uses: actions/cache@v3
|
||||||
with:
|
with:
|
||||||
path: ~/go/pkg/mod
|
path: ~/go/pkg/mod
|
||||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||||
@ -31,9 +32,9 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: checkout
|
- name: checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v3
|
||||||
- name: lint
|
- name: lint
|
||||||
uses: golangci/golangci-lint-action@v2
|
uses: golangci/golangci-lint-action@v3.4.0
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
with:
|
with:
|
||||||
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
||||||
|
29
.github/workflows/codeql-analysis.yml
vendored
29
.github/workflows/codeql-analysis.yml
vendored
@ -9,7 +9,7 @@
|
|||||||
# the `language` matrix defined below to confirm you have the correct set of
|
# the `language` matrix defined below to confirm you have the correct set of
|
||||||
# supported CodeQL languages.
|
# supported CodeQL languages.
|
||||||
#
|
#
|
||||||
name: "CodeQL"
|
name: "codeql"
|
||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_run:
|
workflow_run:
|
||||||
@ -17,16 +17,16 @@ on:
|
|||||||
types:
|
types:
|
||||||
- completed
|
- completed
|
||||||
push:
|
push:
|
||||||
branches: [ master ]
|
branches: [ master, v3 ]
|
||||||
pull_request:
|
pull_request:
|
||||||
# The branches below must be a subset of the branches above
|
# The branches below must be a subset of the branches above
|
||||||
branches: [ master ]
|
branches: [ master, v3 ]
|
||||||
schedule:
|
schedule:
|
||||||
- cron: '34 1 * * 0'
|
- cron: '34 1 * * 0'
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
analyze:
|
analyze:
|
||||||
name: Analyze
|
name: analyze
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
permissions:
|
||||||
actions: read
|
actions: read
|
||||||
@ -42,12 +42,15 @@ jobs:
|
|||||||
# 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
|
# 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:
|
steps:
|
||||||
- name: Checkout repository
|
- name: checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v3
|
||||||
|
- name: setup
|
||||||
|
uses: actions/setup-go@v3
|
||||||
|
with:
|
||||||
|
go-version: 1.17
|
||||||
# Initializes the CodeQL tools for scanning.
|
# Initializes the CodeQL tools for scanning.
|
||||||
- name: Initialize CodeQL
|
- name: init
|
||||||
uses: github/codeql-action/init@v1
|
uses: github/codeql-action/init@v2
|
||||||
with:
|
with:
|
||||||
languages: ${{ matrix.language }}
|
languages: ${{ matrix.language }}
|
||||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||||
@ -57,8 +60,8 @@ jobs:
|
|||||||
|
|
||||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
# 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)
|
# If this step fails, then you should remove it and run the build manually (see below)
|
||||||
- name: Autobuild
|
- name: autobuild
|
||||||
uses: github/codeql-action/autobuild@v1
|
uses: github/codeql-action/autobuild@v2
|
||||||
|
|
||||||
# ℹ️ Command-line programs to run using the OS shell.
|
# ℹ️ Command-line programs to run using the OS shell.
|
||||||
# 📚 https://git.io/JvXDl
|
# 📚 https://git.io/JvXDl
|
||||||
@ -71,5 +74,5 @@ jobs:
|
|||||||
# make bootstrap
|
# make bootstrap
|
||||||
# make release
|
# make release
|
||||||
|
|
||||||
- name: Perform CodeQL Analysis
|
- name: analyze
|
||||||
uses: github/codeql-action/analyze@v1
|
uses: github/codeql-action/analyze@v2
|
||||||
|
73
.github/workflows/dependabot-automerge.yml
vendored
73
.github/workflows/dependabot-automerge.yml
vendored
@ -1,66 +1,27 @@
|
|||||||
name: "prautomerge"
|
name: "dependabot-automerge"
|
||||||
|
|
||||||
on:
|
on:
|
||||||
workflow_run:
|
pull_request_target:
|
||||||
workflows: ["prbuild"]
|
types: [assigned, opened, synchronize, reopened]
|
||||||
types:
|
|
||||||
- completed
|
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
|
||||||
pull-requests: write
|
pull-requests: write
|
||||||
|
contents: write
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
Dependabot-Automerge:
|
automerge:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
# Contains workaround to execute if dependabot updates the PR by checking for the base branch in the linked PR
|
if: github.actor == 'dependabot[bot]'
|
||||||
# The the github.event.workflow_run.event value is 'push' and not 'pull_request'
|
|
||||||
# dont work with multiple workflows when last returns success
|
|
||||||
if: >-
|
|
||||||
github.event.workflow_run.conclusion == 'success'
|
|
||||||
&& github.actor == 'dependabot[bot]'
|
|
||||||
&& github.event.sender.login == 'dependabot[bot]'
|
|
||||||
&& github.event.sender.type == 'Bot'
|
|
||||||
&& (github.event.workflow_run.event == 'pull_request'
|
|
||||||
|| (github.event.workflow_run.event == 'push' && github.event.workflow_run.pull_requests[0].base.ref == github.event.repository.default_branch ))
|
|
||||||
steps:
|
steps:
|
||||||
- name: Approve Changes and Merge changes if label 'dependencies' is set
|
- name: metadata
|
||||||
uses: actions/github-script@v5
|
id: metadata
|
||||||
|
uses: dependabot/fetch-metadata@v1.3.6
|
||||||
with:
|
with:
|
||||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
github-token: "${{ secrets.TOKEN }}"
|
||||||
script: |
|
- name: merge
|
||||||
console.log(context.payload.workflow_run);
|
id: merge
|
||||||
|
if: ${{contains(steps.metadata.outputs.dependency-names, 'go.unistack.org')}}
|
||||||
var labelNames = await github.paginate(
|
run: gh pr merge --auto --merge "$PR_URL"
|
||||||
github.issues.listLabelsOnIssue,
|
env:
|
||||||
{
|
PR_URL: ${{github.event.pull_request.html_url}}
|
||||||
repo: context.repo.repo,
|
GITHUB_TOKEN: ${{secrets.TOKEN}}
|
||||||
owner: context.repo.owner,
|
|
||||||
issue_number: context.payload.workflow_run.pull_requests[0].number,
|
|
||||||
},
|
|
||||||
(response) => response.data.map(
|
|
||||||
(label) => label.name
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
console.log(labelNames);
|
|
||||||
|
|
||||||
if (labelNames.includes('dependencies')) {
|
|
||||||
console.log('Found label');
|
|
||||||
|
|
||||||
await github.pulls.createReview({
|
|
||||||
repo: context.repo.repo,
|
|
||||||
owner: context.repo.owner,
|
|
||||||
pull_number: context.payload.workflow_run.pull_requests[0].number,
|
|
||||||
event: 'APPROVE'
|
|
||||||
});
|
|
||||||
console.log('Approved PR');
|
|
||||||
|
|
||||||
await github.pulls.merge({
|
|
||||||
repo: context.repo.repo,
|
|
||||||
owner: context.repo.owner,
|
|
||||||
pull_number: context.payload.workflow_run.pull_requests[0].number,
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log('Merged PR');
|
|
||||||
}
|
|
||||||
|
13
.github/workflows/pr.yml
vendored
13
.github/workflows/pr.yml
vendored
@ -3,19 +3,20 @@ on:
|
|||||||
pull_request:
|
pull_request:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- master
|
||||||
|
- v3
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
name: test
|
name: test
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: setup
|
- name: setup
|
||||||
uses: actions/setup-go@v2
|
uses: actions/setup-go@v3
|
||||||
with:
|
with:
|
||||||
go-version: 1.16
|
go-version: 1.17
|
||||||
- name: checkout
|
- name: checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v3
|
||||||
- name: cache
|
- name: cache
|
||||||
uses: actions/cache@v2
|
uses: actions/cache@v3
|
||||||
with:
|
with:
|
||||||
path: ~/go/pkg/mod
|
path: ~/go/pkg/mod
|
||||||
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
|
||||||
@ -31,9 +32,9 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: checkout
|
- name: checkout
|
||||||
uses: actions/checkout@v2
|
uses: actions/checkout@v3
|
||||||
- name: lint
|
- name: lint
|
||||||
uses: golangci/golangci-lint-action@v2
|
uses: golangci/golangci-lint-action@v3.4.0
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
with:
|
with:
|
||||||
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
|
||||||
|
6
.gitignore
vendored
6
.gitignore
vendored
@ -13,3 +13,9 @@
|
|||||||
|
|
||||||
# Dependency directories (remove the comment below to include it)
|
# Dependency directories (remove the comment below to include it)
|
||||||
# vendor/
|
# vendor/
|
||||||
|
|
||||||
|
# General
|
||||||
|
.DS_Store
|
||||||
|
.idea
|
||||||
|
.vscode
|
||||||
|
bin/
|
||||||
|
@ -1,2 +1,2 @@
|
|||||||
# micro-broker-kgo
|
# broker-kgo
|
||||||
yet another micro kafka broker alternative
|
|
||||||
|
76
carrier.go
Normal file
76
carrier.go
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
package kgo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/twmb/franz-go/pkg/kgo"
|
||||||
|
"go.unistack.org/micro/v3/metadata"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RecordCarrier injects and extracts traces from a kgo.Record.
|
||||||
|
//
|
||||||
|
// This type exists to satisfy the otel/propagation.TextMapCarrier interface.
|
||||||
|
type RecordCarrier struct {
|
||||||
|
record *kgo.Record
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewRecordCarrier creates a new RecordCarrier.
|
||||||
|
func NewRecordCarrier(record *kgo.Record) RecordCarrier {
|
||||||
|
return RecordCarrier{record: record}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get retrieves a single value for a given key if it exists.
|
||||||
|
func (c RecordCarrier) Get(key string) string {
|
||||||
|
for _, h := range c.record.Headers {
|
||||||
|
if h.Key == key {
|
||||||
|
return string(h.Value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set sets a header.
|
||||||
|
func (c RecordCarrier) Set(key, val string) {
|
||||||
|
// Check if key already exists.
|
||||||
|
for i, h := range c.record.Headers {
|
||||||
|
if h.Key == key {
|
||||||
|
// Key exist, update the value.
|
||||||
|
c.record.Headers[i].Value = []byte(val)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Key does not exist, append new header.
|
||||||
|
c.record.Headers = append(c.record.Headers, kgo.RecordHeader{
|
||||||
|
Key: key,
|
||||||
|
Value: []byte(val),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keys returns a slice of all key identifiers in the carrier.
|
||||||
|
func (c RecordCarrier) Keys() []string {
|
||||||
|
out := make([]string, len(c.record.Headers))
|
||||||
|
for i, h := range c.record.Headers {
|
||||||
|
out[i] = h.Key
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func setHeaders(r *kgo.Record, md metadata.Metadata) {
|
||||||
|
seen := make(map[string]struct{})
|
||||||
|
loop:
|
||||||
|
for k, v := range md {
|
||||||
|
for i := 0; i < len(r.Headers); i++ {
|
||||||
|
if r.Headers[i].Key == k {
|
||||||
|
// Key exist, update the value.
|
||||||
|
r.Headers[i].Value = []byte(v)
|
||||||
|
continue loop
|
||||||
|
} else if _, ok := seen[k]; ok {
|
||||||
|
continue loop
|
||||||
|
}
|
||||||
|
// Key does not exist, append new header.
|
||||||
|
r.Headers = append(r.Headers, kgo.RecordHeader{
|
||||||
|
Key: k,
|
||||||
|
Value: []byte(v),
|
||||||
|
})
|
||||||
|
seen[k] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
48
event.go
Normal file
48
event.go
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
package kgo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"go.unistack.org/micro/v3/broker"
|
||||||
|
)
|
||||||
|
|
||||||
|
type event struct {
|
||||||
|
ctx context.Context
|
||||||
|
topic string
|
||||||
|
err error
|
||||||
|
sync.RWMutex
|
||||||
|
msg *broker.Message
|
||||||
|
ack bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *event) Context() context.Context {
|
||||||
|
return p.ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *event) Topic() string {
|
||||||
|
return p.topic
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *event) Message() *broker.Message {
|
||||||
|
return p.msg
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *event) Ack() error {
|
||||||
|
p.ack = true
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *event) Error() error {
|
||||||
|
return p.err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *event) SetError(err error) {
|
||||||
|
p.err = err
|
||||||
|
}
|
||||||
|
|
||||||
|
var eventPool = sync.Pool{
|
||||||
|
New: func() interface{} {
|
||||||
|
return &event{msg: &broker.Message{}}
|
||||||
|
},
|
||||||
|
}
|
25
go.mod
25
go.mod
@ -1,10 +1,25 @@
|
|||||||
module go.unistack.org/micro-broker-kgo/v3
|
module go.unistack.org/micro-broker-kgo/v3
|
||||||
|
|
||||||
go 1.16
|
go 1.22.7
|
||||||
|
|
||||||
|
toolchain go1.23.3
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/klauspost/compress v1.13.6 // indirect
|
github.com/google/uuid v1.6.0
|
||||||
github.com/twmb/franz-go v1.1.2
|
github.com/twmb/franz-go v1.18.0
|
||||||
github.com/twmb/franz-go/pkg/kmsg v0.0.0-20210930203137-7fbfd17de279
|
github.com/twmb/franz-go/pkg/kadm v1.14.0
|
||||||
go.unistack.org/micro/v3 v3.8.0
|
github.com/twmb/franz-go/pkg/kmsg v1.9.0
|
||||||
|
go.opentelemetry.io/otel v1.32.0
|
||||||
|
go.unistack.org/micro/v3 v3.11.0
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/klauspost/compress v1.17.11 // indirect
|
||||||
|
github.com/pierrec/lz4/v4 v4.1.21 // indirect
|
||||||
|
go.unistack.org/micro-proto/v3 v3.4.1 // indirect
|
||||||
|
golang.org/x/crypto v0.29.0 // indirect
|
||||||
|
golang.org/x/sys v0.27.0 // indirect
|
||||||
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20241202173237-19429a94021a // indirect
|
||||||
|
google.golang.org/grpc v1.68.0 // indirect
|
||||||
|
google.golang.org/protobuf v1.35.2 // indirect
|
||||||
)
|
)
|
||||||
|
95
go.sum
95
go.sum
@ -1,67 +1,28 @@
|
|||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
github.com/ef-ds/deque v1.0.4/go.mod h1:gXDnTC3yqvBcHbq2lcExjtAcVrOnJCbMcZXmuj8Z4tg=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/golang-jwt/jwt/v4 v4.1.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg=
|
github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=
|
||||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=
|
||||||
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
github.com/pierrec/lz4/v4 v4.1.21 h1:yOVMLb6qSIDP67pl/5F7RepeKYu/VmTyEXvuMI5d9mQ=
|
||||||
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
|
github.com/pierrec/lz4/v4 v4.1.21/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
|
||||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
github.com/twmb/franz-go v1.18.0 h1:25FjMZfdozBywVX+5xrWC2W+W76i0xykKjTdEeD2ejw=
|
||||||
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
|
github.com/twmb/franz-go v1.18.0/go.mod h1:zXCGy74M0p5FbXsLeASdyvfLFsBvTubVqctIaa5wQ+I=
|
||||||
github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
|
github.com/twmb/franz-go/pkg/kadm v1.14.0 h1:nAn1co1lXzJQocpzyIyOFOjUBf4WHWs5/fTprXy2IZs=
|
||||||
github.com/hashicorp/go-uuid v1.0.2/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
|
github.com/twmb/franz-go/pkg/kadm v1.14.0/go.mod h1:XjOPz6ZaXXjrW2jVCfLuucP8H1w2TvD6y3PT2M+aAM4=
|
||||||
github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA=
|
github.com/twmb/franz-go/pkg/kmsg v1.9.0 h1:JojYUph2TKAau6SBtErXpXGC7E3gg4vGZMv9xFU/B6M=
|
||||||
github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs=
|
github.com/twmb/franz-go/pkg/kmsg v1.9.0/go.mod h1:CMbfazviCyY6HM0SXuG5t9vOwYDHRCSrJJyBAe5paqg=
|
||||||
github.com/jcmturner/dnsutils/v2 v2.0.0/go.mod h1:b0TnjGOvI/n42bZa+hmXL+kFJZsFT7G4t3HTlQ184QM=
|
go.opentelemetry.io/otel v1.32.0 h1:WnBN+Xjcteh0zdk01SVqV55d/m62NJLJdIyb4y/WO5U=
|
||||||
github.com/jcmturner/gofork v1.0.0/go.mod h1:MK8+TM0La+2rjBD4jE12Kj1pCCxK7d2LK/UM3ncEo0o=
|
go.opentelemetry.io/otel v1.32.0/go.mod h1:00DCVSB0RQcnzlwyTfqtxSm+DRr9hpYrHjNGiBHVQIg=
|
||||||
github.com/jcmturner/goidentity/v6 v6.0.1/go.mod h1:X1YW3bgtvwAXju7V3LCIMpY0Gbxyjn/mY9zx4tFonSg=
|
go.unistack.org/micro-proto/v3 v3.4.1 h1:UTjLSRz2YZuaHk9iSlVqqsA50JQNAEK2ZFboGqtEa9Q=
|
||||||
github.com/jcmturner/gokrb5/v8 v8.4.2/go.mod h1:sb+Xq/fTY5yktf/VxLsE3wlfPqQjp0aWNYyvBVK62bc=
|
go.unistack.org/micro-proto/v3 v3.4.1/go.mod h1:okx/cnOhzuCX0ggl/vToatbCupi0O44diiiLLsZ93Zo=
|
||||||
github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc=
|
go.unistack.org/micro/v3 v3.11.0 h1:usQ+8wQuOWpQd4+DGhFXSgZ+e+wOBjuT3W5GJZ02bSs=
|
||||||
github.com/klauspost/compress v1.13.5/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
|
go.unistack.org/micro/v3 v3.11.0/go.mod h1:YzMldzHN9Ei+zy5t/Psu7RUWDZwUfrNYiStSQtTz90g=
|
||||||
github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc=
|
golang.org/x/crypto v0.29.0 h1:L5SG1JTTXupVV3n6sUqMTeWbjAyfPwoda2DLX8J8FrQ=
|
||||||
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
|
golang.org/x/crypto v0.29.0/go.mod h1:+F4F4N5hv6v38hfeYwTdx20oUvLLc+QfrE9Ax9HtgRg=
|
||||||
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
|
golang.org/x/sys v0.27.0 h1:wBqf8DvsY9Y/2P8gAfPDEYNuS30J4lPHJxXSb/nJZ+s=
|
||||||
github.com/pierrec/lz4/v4 v4.1.8 h1:ieHkV+i2BRzngO4Wd/3HGowuZStgq6QkPsD1eolNAO4=
|
golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
github.com/pierrec/lz4/v4 v4.1.8/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20241202173237-19429a94021a h1:hgh8P4EuoxpsuKMXX/To36nOFD7vixReXgn8lPGnt+o=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
google.golang.org/genproto/googleapis/rpc v0.0.0-20241202173237-19429a94021a/go.mod h1:5uTbfoYQed2U9p3KIj2/Zzm02PYhndfdmML0qC3q3FU=
|
||||||
github.com/silas/dag v0.0.0-20210626123444-3804bac2d6d4/go.mod h1:7RTUFBdIRC9nZ7/3RyRNH1bdqIShrDejd1YbLwgPS+I=
|
google.golang.org/grpc v1.68.0 h1:aHQeeJbo8zAkAa3pRzrVjZlbz6uSfeOXlJNQM0RAbz0=
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
google.golang.org/grpc v1.68.0/go.mod h1:fmSPC5AsjSBCK54MyHRx48kpOti1/jRfOlwEWywNjWA=
|
||||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
google.golang.org/protobuf v1.35.2 h1:8Ar7bF+apOIoThw1EdZl0p1oWvMqTHmpA2fRTyZO8io=
|
||||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
google.golang.org/protobuf v1.35.2/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
|
||||||
github.com/twmb/franz-go v1.1.2 h1:i9lCDEcXWpRd3YXFlffIc/koBl+JijI13F5sg69NPRk=
|
|
||||||
github.com/twmb/franz-go v1.1.2/go.mod h1:KerrVhzNpasYrWJLr2Yj6Cui43f1BxH4U9SJEDVOjqQ=
|
|
||||||
github.com/twmb/franz-go/pkg/kmsg v0.0.0-20210914042331-106aef61b693/go.mod h1:SxG/xJKhgPu25SamAq0rrucfp7lbzCpEXOC+vH/ELrY=
|
|
||||||
github.com/twmb/franz-go/pkg/kmsg v0.0.0-20210930203137-7fbfd17de279 h1:58GX0Ju/PCG1zWVdsLEE5OUu70KlfOrxY7djPszuqiw=
|
|
||||||
github.com/twmb/franz-go/pkg/kmsg v0.0.0-20210930203137-7fbfd17de279/go.mod h1:SxG/xJKhgPu25SamAq0rrucfp7lbzCpEXOC+vH/ELrY=
|
|
||||||
github.com/twmb/go-rbtree v1.0.0 h1:KxN7dXJ8XaZ4cvmHV1qqXTshxX3EBvX/toG5+UR49Mg=
|
|
||||||
github.com/twmb/go-rbtree v1.0.0/go.mod h1:UlIAI8gu3KRPkXSobZnmJfVwCJgEhD/liWzT5ppzIyc=
|
|
||||||
github.com/unistack-org/micro-proto v0.0.9 h1:KrWLS4FUX7UAWNAilQf70uad6ZPf/0EudeddCXllRVc=
|
|
||||||
github.com/unistack-org/micro-proto v0.0.9/go.mod h1:Cckwmzd89gvS7ThxzZp9kQR/EOdksFQcsTAtDDyKwrg=
|
|
||||||
go.unistack.org/micro/v3 v3.8.0 h1:9k6C40xdJf65VW6cVB8sOJVSJhyz1UfFOhX7/II2ivo=
|
|
||||||
go.unistack.org/micro/v3 v3.8.0/go.mod h1:Tkteri0wiiybbH6aPqay26pZHFIAwL9LXJc2x1Jkakk=
|
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
|
||||||
golang.org/x/crypto v0.0.0-20201112155050-0c6587e931a9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
|
||||||
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
|
||||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
|
||||||
golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
|
||||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
|
||||||
golang.org/x/net v0.0.0-20210913180222-943fd674d43e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
|
||||||
golang.org/x/net v0.0.0-20210928044308-7d9f5e0b762b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
|
||||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
|
||||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
|
||||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
|
||||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
|
||||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
|
||||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
|
||||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
|
||||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
|
||||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
|
||||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
|
||||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
|
|
||||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
|
||||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
|
||||||
google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ=
|
|
||||||
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
|
||||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
|
||||||
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
|
||||||
|
65
kadmtest.go
Normal file
65
kadmtest.go
Normal file
@ -0,0 +1,65 @@
|
|||||||
|
//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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
488
kgo.go
488
kgo.go
@ -1,204 +1,210 @@
|
|||||||
// Package kgo provides a kafka broker using kgo
|
// Package kgo provides a kafka broker using kgo
|
||||||
package kgo // import "go.unistack.org/micro-broker-kgo/v3"
|
package kgo
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"math/rand"
|
||||||
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/twmb/franz-go/pkg/kerr"
|
"github.com/google/uuid"
|
||||||
kgo "github.com/twmb/franz-go/pkg/kgo"
|
"github.com/twmb/franz-go/pkg/kgo"
|
||||||
"github.com/twmb/franz-go/pkg/kmsg"
|
"github.com/twmb/franz-go/pkg/kmsg"
|
||||||
"github.com/twmb/franz-go/pkg/kversion"
|
|
||||||
"go.unistack.org/micro/v3/broker"
|
"go.unistack.org/micro/v3/broker"
|
||||||
"go.unistack.org/micro/v3/logger"
|
"go.unistack.org/micro/v3/logger"
|
||||||
"go.unistack.org/micro/v3/metadata"
|
"go.unistack.org/micro/v3/metadata"
|
||||||
"go.unistack.org/micro/v3/util/id"
|
"go.unistack.org/micro/v3/semconv"
|
||||||
|
"go.unistack.org/micro/v3/tracer"
|
||||||
mrand "go.unistack.org/micro/v3/util/rand"
|
mrand "go.unistack.org/micro/v3/util/rand"
|
||||||
)
|
)
|
||||||
|
|
||||||
var _ broker.Broker = &kBroker{}
|
var _ broker.Broker = (*Broker)(nil)
|
||||||
|
|
||||||
type kBroker struct {
|
var ErrLostMessage = errors.New("message not marked for offsets commit and will be lost in next iteration")
|
||||||
writer *kgo.Client // used only to push messages
|
|
||||||
kopts []kgo.Opt
|
var DefaultRetryBackoffFn = func() func(int) time.Duration {
|
||||||
connected bool
|
var rngMu sync.Mutex
|
||||||
|
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||||
|
return func(fails int) time.Duration {
|
||||||
|
const (
|
||||||
|
min = 100 * time.Millisecond
|
||||||
|
max = time.Second
|
||||||
|
)
|
||||||
|
if fails <= 0 {
|
||||||
|
return min
|
||||||
|
}
|
||||||
|
if fails > 10 {
|
||||||
|
return max
|
||||||
|
}
|
||||||
|
|
||||||
|
backoff := min * time.Duration(1<<(fails-1))
|
||||||
|
|
||||||
|
rngMu.Lock()
|
||||||
|
jitter := 0.8 + 0.4*rng.Float64()
|
||||||
|
rngMu.Unlock()
|
||||||
|
|
||||||
|
backoff = time.Duration(float64(backoff) * jitter)
|
||||||
|
|
||||||
|
if backoff > max {
|
||||||
|
return max
|
||||||
|
}
|
||||||
|
return backoff
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
type Broker struct {
|
||||||
init bool
|
init bool
|
||||||
|
c *kgo.Client
|
||||||
|
kopts []kgo.Opt
|
||||||
|
connected *atomic.Uint32
|
||||||
sync.RWMutex
|
sync.RWMutex
|
||||||
opts broker.Options
|
opts broker.Options
|
||||||
subs []*subscriber
|
subs []*Subscriber
|
||||||
}
|
}
|
||||||
|
|
||||||
type subscriber struct {
|
func (r *Broker) Live() bool {
|
||||||
reader *kgo.Client // used only to pull messages
|
return r.connected.Load() == 1
|
||||||
topic string
|
|
||||||
opts broker.SubscribeOptions
|
|
||||||
kopts broker.Options
|
|
||||||
handler broker.Handler
|
|
||||||
batchhandler broker.BatchHandler
|
|
||||||
closed bool
|
|
||||||
done chan struct{}
|
|
||||||
consumers map[string]map[int32]worker
|
|
||||||
sync.RWMutex
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type publication struct {
|
func (r *Broker) Ready() bool {
|
||||||
topic string
|
return r.connected.Load() == 1
|
||||||
err error
|
|
||||||
sync.RWMutex
|
|
||||||
msg *broker.Message
|
|
||||||
ack bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *publication) Topic() string {
|
func (r *Broker) Health() bool {
|
||||||
return p.topic
|
return r.connected.Load() == 1
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *publication) Message() *broker.Message {
|
func (k *Broker) Address() string {
|
||||||
return p.msg
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *publication) Ack() error {
|
|
||||||
p.ack = true
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *publication) Error() error {
|
|
||||||
return p.err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *publication) SetError(err error) {
|
|
||||||
p.err = err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *subscriber) Options() broker.SubscribeOptions {
|
|
||||||
return s.opts
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *subscriber) Topic() string {
|
|
||||||
return s.topic
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *subscriber) Unsubscribe(ctx context.Context) error {
|
|
||||||
if s.closed {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
return ctx.Err()
|
|
||||||
default:
|
|
||||||
close(s.done)
|
|
||||||
s.closed = true
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (k *kBroker) Address() string {
|
|
||||||
return strings.Join(k.opts.Addrs, ",")
|
return strings.Join(k.opts.Addrs, ",")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (k *kBroker) Name() string {
|
func (k *Broker) Name() string {
|
||||||
return k.opts.Name
|
return k.opts.Name
|
||||||
}
|
}
|
||||||
|
|
||||||
func (k *kBroker) Connect(ctx context.Context) error {
|
func (k *Broker) Client() *kgo.Client {
|
||||||
k.RLock()
|
return k.c
|
||||||
if k.connected {
|
}
|
||||||
k.RUnlock()
|
|
||||||
|
func (k *Broker) connect(ctx context.Context, opts ...kgo.Opt) (*kgo.Client, *hookTracer, error) {
|
||||||
|
var c *kgo.Client
|
||||||
|
var err error
|
||||||
|
|
||||||
|
sp, _ := tracer.SpanFromContext(ctx)
|
||||||
|
|
||||||
|
clientID := "kgo"
|
||||||
|
group := ""
|
||||||
|
if k.opts.Context != nil {
|
||||||
|
if id, ok := k.opts.Context.Value(clientIDKey{}).(string); ok {
|
||||||
|
clientID = id
|
||||||
|
}
|
||||||
|
if id, ok := k.opts.Context.Value(groupKey{}).(string); ok {
|
||||||
|
group = id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
htracer := &hookTracer{group: group, clientID: clientID, tracer: k.opts.Tracer}
|
||||||
|
opts = append(opts,
|
||||||
|
kgo.WithHooks(&hookMeter{meter: k.opts.Meter}),
|
||||||
|
kgo.WithHooks(htracer),
|
||||||
|
)
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
if sp != nil {
|
||||||
|
sp.SetStatus(tracer.SpanStatusError, ctx.Err().Error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, nil, ctx.Err()
|
||||||
|
default:
|
||||||
|
c, err = kgo.NewClient(opts...)
|
||||||
|
if err == nil {
|
||||||
|
err = c.Ping(ctx) // check connectivity to cluster
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
if sp != nil {
|
||||||
|
sp.SetStatus(tracer.SpanStatusError, err.Error())
|
||||||
|
}
|
||||||
|
return nil, nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return c, htracer, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (k *Broker) Connect(ctx context.Context) error {
|
||||||
|
if k.connected.Load() == 1 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
k.RUnlock()
|
|
||||||
|
|
||||||
nctx := k.opts.Context
|
nctx := k.opts.Context
|
||||||
if ctx != nil {
|
if ctx != nil {
|
||||||
nctx = ctx
|
nctx = ctx
|
||||||
}
|
}
|
||||||
|
|
||||||
kaddrs := k.opts.Addrs
|
c, _, err := k.connect(nctx, k.kopts...)
|
||||||
|
|
||||||
// shuffle addrs
|
|
||||||
var rng mrand.Rand
|
|
||||||
rng.Shuffle(len(kaddrs), func(i, j int) {
|
|
||||||
kaddrs[i], kaddrs[j] = kaddrs[j], kaddrs[i]
|
|
||||||
})
|
|
||||||
|
|
||||||
kopts := append(k.kopts, kgo.SeedBrokers(kaddrs...))
|
|
||||||
|
|
||||||
select {
|
|
||||||
case <-nctx.Done():
|
|
||||||
return nctx.Err()
|
|
||||||
default:
|
|
||||||
c, err := kgo.NewClient(kopts...)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Request versions in order to guess Kafka Cluster version
|
|
||||||
versionsReq := kmsg.NewApiVersionsRequest()
|
|
||||||
versionsRes, err := versionsReq.RequestWith(ctx, c)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to request api versions: %w", err)
|
|
||||||
}
|
|
||||||
err = kerr.ErrorForCode(versionsRes.ErrorCode)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to request api versions. Inner kafka error: %w", err)
|
|
||||||
}
|
|
||||||
versions := kversion.FromApiVersionsResponse(versionsRes)
|
|
||||||
|
|
||||||
if k.opts.Logger.V(logger.InfoLevel) {
|
|
||||||
logger.Infof(ctx, "[kgo] connected to to kafka cluster version %v", versions.VersionGuess())
|
|
||||||
}
|
|
||||||
|
|
||||||
k.Lock()
|
k.Lock()
|
||||||
k.connected = true
|
k.c = c
|
||||||
k.writer = c
|
k.connected.Store(1)
|
||||||
k.Unlock()
|
k.Unlock()
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (k *kBroker) Disconnect(ctx context.Context) error {
|
func (k *Broker) Disconnect(ctx context.Context) error {
|
||||||
k.RLock()
|
if k.connected.Load() == 0 {
|
||||||
if !k.connected {
|
|
||||||
k.RUnlock()
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
k.RUnlock()
|
|
||||||
|
|
||||||
k.Lock()
|
|
||||||
defer k.Unlock()
|
|
||||||
|
|
||||||
nctx := k.opts.Context
|
nctx := k.opts.Context
|
||||||
if ctx != nil {
|
if ctx != nil {
|
||||||
nctx = ctx
|
nctx = ctx
|
||||||
}
|
}
|
||||||
|
var span tracer.Span
|
||||||
|
ctx, span = k.opts.Tracer.Start(ctx, "Disconnect")
|
||||||
|
defer span.Finish()
|
||||||
|
|
||||||
|
k.Lock()
|
||||||
|
defer k.Unlock()
|
||||||
select {
|
select {
|
||||||
case <-nctx.Done():
|
case <-nctx.Done():
|
||||||
return nctx.Err()
|
return nctx.Err()
|
||||||
default:
|
default:
|
||||||
for _, sub := range k.subs {
|
for _, sub := range k.subs {
|
||||||
|
if sub.closed {
|
||||||
|
continue
|
||||||
|
}
|
||||||
if err := sub.Unsubscribe(ctx); err != nil {
|
if err := sub.Unsubscribe(ctx); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
k.writer.Close()
|
if k.c != nil {
|
||||||
|
k.c.CloseAllowingRebalance()
|
||||||
|
// k.c.Close()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
k.connected = false
|
k.connected.Store(0)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (k *kBroker) Init(opts ...broker.Option) error {
|
func (k *Broker) Init(opts ...broker.Option) error {
|
||||||
k.Lock()
|
k.Lock()
|
||||||
defer k.Unlock()
|
defer k.Unlock()
|
||||||
|
|
||||||
if len(opts) == 0 && k.init {
|
if len(opts) == 0 && k.init {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, o := range opts {
|
for _, o := range opts {
|
||||||
o(&k.opts)
|
o(&k.opts)
|
||||||
}
|
}
|
||||||
@ -222,41 +228,62 @@ func (k *kBroker) Init(opts ...broker.Option) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// kgo.RecordPartitioner(),
|
|
||||||
|
|
||||||
k.init = true
|
k.init = true
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (k *kBroker) Options() broker.Options {
|
func (k *Broker) Options() broker.Options {
|
||||||
return k.opts
|
return k.opts
|
||||||
}
|
}
|
||||||
|
|
||||||
func (k *kBroker) BatchPublish(ctx context.Context, msgs []*broker.Message, opts ...broker.PublishOption) error {
|
func (k *Broker) BatchPublish(ctx context.Context, msgs []*broker.Message, opts ...broker.PublishOption) error {
|
||||||
return k.publish(ctx, msgs, opts...)
|
return k.publish(ctx, msgs, opts...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (k *kBroker) Publish(ctx context.Context, topic string, msg *broker.Message, opts ...broker.PublishOption) error {
|
func (k *Broker) Publish(ctx context.Context, topic string, msg *broker.Message, opts ...broker.PublishOption) error {
|
||||||
msg.Header.Set(metadata.HeaderTopic, topic)
|
msg.Header.Set(metadata.HeaderTopic, topic)
|
||||||
return k.publish(ctx, []*broker.Message{msg}, opts...)
|
return k.publish(ctx, []*broker.Message{msg}, opts...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (k *kBroker) publish(ctx context.Context, msgs []*broker.Message, opts ...broker.PublishOption) error {
|
func (k *Broker) publish(ctx context.Context, msgs []*broker.Message, opts ...broker.PublishOption) error {
|
||||||
|
k.Lock()
|
||||||
|
if k.connected.Load() == 0 {
|
||||||
|
c, _, err := k.connect(ctx, k.kopts...)
|
||||||
|
if err != nil {
|
||||||
|
k.Unlock()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
k.c = c
|
||||||
|
k.connected.Store(1)
|
||||||
|
}
|
||||||
|
k.Unlock()
|
||||||
|
|
||||||
options := broker.NewPublishOptions(opts...)
|
options := broker.NewPublishOptions(opts...)
|
||||||
records := make([]*kgo.Record, 0, len(msgs))
|
records := make([]*kgo.Record, 0, len(msgs))
|
||||||
var errs []string
|
var errs []string
|
||||||
var err error
|
var err error
|
||||||
|
var key []byte
|
||||||
|
var promise func(*kgo.Record, error)
|
||||||
|
|
||||||
|
if options.Context != nil {
|
||||||
|
if k, ok := options.Context.Value(publishKey{}).([]byte); ok && k != nil {
|
||||||
|
key = k
|
||||||
|
}
|
||||||
|
if p, ok := options.Context.Value(publishPromiseKey{}).(func(*kgo.Record, error)); ok && p != nil {
|
||||||
|
promise = p
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
for _, msg := range msgs {
|
for _, msg := range msgs {
|
||||||
rec := &kgo.Record{}
|
rec := &kgo.Record{Context: ctx, Key: key}
|
||||||
rec.Topic, _ = msg.Header.Get(metadata.HeaderTopic)
|
rec.Topic, _ = msg.Header.Get(metadata.HeaderTopic)
|
||||||
if options.BodyOnly {
|
msg.Header.Del(metadata.HeaderTopic)
|
||||||
rec.Value = msg.Body
|
k.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", rec.Topic, "topic", rec.Topic).Inc()
|
||||||
} else if k.opts.Codec.String() == "noop" {
|
if options.BodyOnly || k.opts.Codec.String() == "noop" {
|
||||||
rec.Value = msg.Body
|
rec.Value = msg.Body
|
||||||
for k, v := range msg.Header {
|
for k, v := range msg.Header {
|
||||||
rec.Headers = append(rec.Headers, kgo.RecordHeader{Key: k, Value: []byte(v)})
|
rec.Headers = append(rec.Headers, kgo.RecordHeader{Key: http.CanonicalHeaderKey(k), Value: []byte(v)})
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
rec.Value, err = k.opts.Codec.Marshal(msg)
|
rec.Value, err = k.opts.Codec.Marshal(msg)
|
||||||
@ -267,12 +294,39 @@ func (k *kBroker) publish(ctx context.Context, msgs []*broker.Message, opts ...b
|
|||||||
records = append(records, rec)
|
records = append(records, rec)
|
||||||
}
|
}
|
||||||
|
|
||||||
results := k.writer.ProduceSync(ctx, records...)
|
if promise != nil {
|
||||||
|
ts := time.Now()
|
||||||
|
for _, rec := range records {
|
||||||
|
k.c.Produce(ctx, rec, func(r *kgo.Record, err error) {
|
||||||
|
te := time.Since(ts)
|
||||||
|
k.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", rec.Topic, "topic", rec.Topic).Dec()
|
||||||
|
k.opts.Meter.Summary(semconv.PublishMessageLatencyMicroseconds, "endpoint", rec.Topic, "topic", rec.Topic).Update(te.Seconds())
|
||||||
|
k.opts.Meter.Histogram(semconv.PublishMessageDurationSeconds, "endpoint", rec.Topic, "topic", rec.Topic).Update(te.Seconds())
|
||||||
|
if err != nil {
|
||||||
|
k.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", rec.Topic, "topic", rec.Topic, "status", "failure").Inc()
|
||||||
|
} else {
|
||||||
|
k.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", rec.Topic, "topic", rec.Topic, "status", "success").Inc()
|
||||||
|
}
|
||||||
|
promise(r, err)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
ts := time.Now()
|
||||||
|
results := k.c.ProduceSync(ctx, records...)
|
||||||
|
te := time.Since(ts)
|
||||||
for _, result := range results {
|
for _, result := range results {
|
||||||
|
k.opts.Meter.Summary(semconv.PublishMessageLatencyMicroseconds, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Update(te.Seconds())
|
||||||
|
k.opts.Meter.Histogram(semconv.PublishMessageDurationSeconds, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Update(te.Seconds())
|
||||||
|
k.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Dec()
|
||||||
if result.Err != nil {
|
if result.Err != nil {
|
||||||
|
k.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", result.Record.Topic, "topic", result.Record.Topic, "status", "failure").Inc()
|
||||||
errs = append(errs, result.Err.Error())
|
errs = append(errs, result.Err.Error())
|
||||||
|
} else {
|
||||||
|
k.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", result.Record.Topic, "topic", result.Record.Topic, "status", "success").Inc()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(errs) > 0 {
|
if len(errs) > 0 {
|
||||||
return fmt.Errorf("publish error: %s", strings.Join(errs, "\n"))
|
return fmt.Errorf("publish error: %s", strings.Join(errs, "\n"))
|
||||||
}
|
}
|
||||||
@ -280,111 +334,92 @@ func (k *kBroker) publish(ctx context.Context, msgs []*broker.Message, opts ...b
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type mlogger struct {
|
func (k *Broker) TopicExists(ctx context.Context, topic string) error {
|
||||||
l logger.Logger
|
mdreq := kmsg.NewMetadataRequest()
|
||||||
ctx context.Context
|
mdreq.Topics = []kmsg.MetadataRequestTopic{
|
||||||
|
{Topic: &topic},
|
||||||
|
}
|
||||||
|
|
||||||
|
mdrsp, err := mdreq.RequestWith(ctx, k.c)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
} else if mdrsp.Topics[0].ErrorCode != 0 {
|
||||||
|
return fmt.Errorf("topic %s not exists or permission error", topic)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *mlogger) Log(lvl kgo.LogLevel, msg string, args ...interface{}) {
|
func (k *Broker) BatchSubscribe(ctx context.Context, topic string, handler broker.BatchHandler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
|
||||||
var mlvl logger.Level
|
|
||||||
switch lvl {
|
|
||||||
case kgo.LogLevelNone:
|
|
||||||
return
|
|
||||||
case kgo.LogLevelError:
|
|
||||||
mlvl = logger.ErrorLevel
|
|
||||||
case kgo.LogLevelWarn:
|
|
||||||
mlvl = logger.WarnLevel
|
|
||||||
case kgo.LogLevelInfo:
|
|
||||||
mlvl = logger.InfoLevel
|
|
||||||
case kgo.LogLevelDebug:
|
|
||||||
mlvl = logger.DebugLevel
|
|
||||||
default:
|
|
||||||
return
|
|
||||||
}
|
|
||||||
fields := make(map[string]interface{}, int(len(args)/2))
|
|
||||||
for i := 0; i < len(args)/2; i += 2 {
|
|
||||||
fields[fmt.Sprintf("%v", args[i])] = args[i+1]
|
|
||||||
}
|
|
||||||
l.l.Fields(fields).Log(l.ctx, mlvl, msg)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *mlogger) Level() kgo.LogLevel {
|
|
||||||
switch l.l.Options().Level {
|
|
||||||
case logger.ErrorLevel:
|
|
||||||
return kgo.LogLevelError
|
|
||||||
case logger.WarnLevel:
|
|
||||||
return kgo.LogLevelWarn
|
|
||||||
case logger.InfoLevel:
|
|
||||||
return kgo.LogLevelInfo
|
|
||||||
case logger.DebugLevel, logger.TraceLevel:
|
|
||||||
return kgo.LogLevelDebug
|
|
||||||
}
|
|
||||||
return kgo.LogLevelNone
|
|
||||||
}
|
|
||||||
|
|
||||||
func (k *kBroker) BatchSubscribe(ctx context.Context, topic string, handler broker.BatchHandler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
|
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (k *kBroker) Subscribe(ctx context.Context, topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
|
func (k *Broker) Subscribe(ctx context.Context, topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
|
||||||
options := broker.NewSubscribeOptions(opts...)
|
options := broker.NewSubscribeOptions(opts...)
|
||||||
|
|
||||||
if options.Group == "" {
|
if options.Group == "" {
|
||||||
uid, err := id.New()
|
uid, err := uuid.NewRandom()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
options.Group = uid
|
options.Group = uid.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
kaddrs := k.opts.Addrs
|
commitInterval := DefaultCommitInterval
|
||||||
|
|
||||||
// shuffle addrs
|
|
||||||
var rng mrand.Rand
|
|
||||||
rng.Shuffle(len(kaddrs), func(i, j int) {
|
|
||||||
kaddrs[i], kaddrs[j] = kaddrs[j], kaddrs[i]
|
|
||||||
})
|
|
||||||
|
|
||||||
td := DefaultCommitInterval
|
|
||||||
if k.opts.Context != nil {
|
if k.opts.Context != nil {
|
||||||
if v, ok := k.opts.Context.Value(commitIntervalKey{}).(time.Duration); ok && v > 0 {
|
if v, ok := k.opts.Context.Value(commitIntervalKey{}).(time.Duration); ok && v > 0 {
|
||||||
td = v
|
commitInterval = v
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
sub := &subscriber{
|
sub := &Subscriber{
|
||||||
topic: topic,
|
topic: topic,
|
||||||
done: make(chan struct{}),
|
|
||||||
opts: options,
|
opts: options,
|
||||||
handler: handler,
|
handler: handler,
|
||||||
kopts: k.opts,
|
kopts: k.opts,
|
||||||
consumers: make(map[string]map[int32]worker),
|
consumers: make(map[tp]*consumer),
|
||||||
|
done: make(chan struct{}),
|
||||||
}
|
}
|
||||||
|
|
||||||
kopts := append(k.kopts,
|
kopts := append(k.kopts,
|
||||||
kgo.SeedBrokers(kaddrs...),
|
|
||||||
kgo.ConsumerGroup(options.Group),
|
kgo.ConsumerGroup(options.Group),
|
||||||
kgo.ConsumeTopics(topic),
|
kgo.ConsumeTopics(topic),
|
||||||
kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
|
kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
|
||||||
kgo.FetchMaxWait(1*time.Second),
|
kgo.FetchMaxWait(1*time.Second),
|
||||||
// kgo.KeepControlRecords(),
|
kgo.AutoCommitInterval(commitInterval),
|
||||||
kgo.Balancers(kgo.CooperativeStickyBalancer(), kgo.StickyBalancer()),
|
|
||||||
kgo.FetchIsolationLevel(kgo.ReadUncommitted()),
|
|
||||||
kgo.WithHooks(&metrics{meter: k.opts.Meter}),
|
|
||||||
kgo.AutoCommitMarks(),
|
|
||||||
kgo.AutoCommitInterval(td),
|
|
||||||
kgo.OnPartitionsAssigned(sub.assigned),
|
kgo.OnPartitionsAssigned(sub.assigned),
|
||||||
kgo.OnPartitionsRevoked(sub.revoked),
|
kgo.OnPartitionsRevoked(sub.revoked),
|
||||||
kgo.OnPartitionsLost(sub.revoked),
|
kgo.OnPartitionsLost(sub.lost),
|
||||||
|
kgo.AutoCommitMarks(),
|
||||||
)
|
)
|
||||||
|
|
||||||
reader, err := kgo.NewClient(kopts...)
|
if options.Context != nil {
|
||||||
|
if v, ok := options.Context.Value(optionsKey{}).([]kgo.Opt); ok && len(v) > 0 {
|
||||||
|
kopts = append(kopts, v...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
c, htracer, err := k.connect(ctx, kopts...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
sub.reader = reader
|
mdreq := kmsg.NewMetadataRequest()
|
||||||
go sub.run(ctx)
|
mdreq.Topics = []kmsg.MetadataRequestTopic{
|
||||||
|
{Topic: &topic},
|
||||||
|
}
|
||||||
|
|
||||||
|
mdrsp, err := mdreq.RequestWith(ctx, c)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
} else if mdrsp.Topics[0].ErrorCode != 0 {
|
||||||
|
return nil, fmt.Errorf("topic %s not exists or permission error", topic)
|
||||||
|
}
|
||||||
|
|
||||||
|
sub.c = c
|
||||||
|
sub.htracer = htracer
|
||||||
|
|
||||||
|
go sub.poll(ctx)
|
||||||
|
|
||||||
k.Lock()
|
k.Lock()
|
||||||
k.subs = append(k.subs, sub)
|
k.subs = append(k.subs, sub)
|
||||||
@ -392,45 +427,30 @@ func (k *kBroker) Subscribe(ctx context.Context, topic string, handler broker.Ha
|
|||||||
return sub, nil
|
return sub, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (k *kBroker) String() string {
|
func (k *Broker) String() string {
|
||||||
return "kgo"
|
return "kgo"
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewBroker(opts ...broker.Option) *kBroker {
|
func NewBroker(opts ...broker.Option) *Broker {
|
||||||
options := broker.NewOptions(opts...)
|
options := broker.NewOptions(opts...)
|
||||||
if options.Codec.String() != "noop" {
|
|
||||||
options.Logger.Infof(options.Context, "broker codec not noop, disable plain kafka headers usage")
|
kaddrs := options.Addrs
|
||||||
}
|
// shuffle addrs
|
||||||
|
var rng mrand.Rand
|
||||||
|
rng.Shuffle(len(kaddrs), func(i, j int) {
|
||||||
|
kaddrs[i], kaddrs[j] = kaddrs[j], kaddrs[i]
|
||||||
|
})
|
||||||
kopts := []kgo.Opt{
|
kopts := []kgo.Opt{
|
||||||
|
kgo.DialTimeout(3 * time.Second),
|
||||||
kgo.DisableIdempotentWrite(),
|
kgo.DisableIdempotentWrite(),
|
||||||
kgo.ProducerBatchCompression(kgo.NoCompression()),
|
kgo.ProducerBatchCompression(kgo.NoCompression()),
|
||||||
kgo.WithLogger(&mlogger{l: options.Logger, ctx: options.Context}),
|
kgo.WithLogger(&mlogger{l: options.Logger.Clone(logger.WithAddCallerSkipCount(2)), ctx: options.Context}),
|
||||||
kgo.RetryBackoffFn(
|
kgo.SeedBrokers(kaddrs...),
|
||||||
func() func(int) time.Duration {
|
kgo.RetryBackoffFn(DefaultRetryBackoffFn),
|
||||||
var rng mrand.Rand
|
kgo.BlockRebalanceOnPoll(),
|
||||||
return func(fails int) time.Duration {
|
kgo.Balancers(kgo.CooperativeStickyBalancer()),
|
||||||
const (
|
kgo.FetchIsolationLevel(kgo.ReadUncommitted()),
|
||||||
min = 250 * time.Millisecond
|
kgo.UnknownTopicRetries(0),
|
||||||
max = 2 * time.Second
|
|
||||||
)
|
|
||||||
if fails <= 0 {
|
|
||||||
return min
|
|
||||||
}
|
|
||||||
if fails > 10 {
|
|
||||||
return max
|
|
||||||
}
|
|
||||||
|
|
||||||
backoff := min * time.Duration(1<<(fails-1))
|
|
||||||
jitter := 0.8 + 0.4*rng.Float64()
|
|
||||||
backoff = time.Duration(float64(backoff) * jitter)
|
|
||||||
|
|
||||||
if backoff > max {
|
|
||||||
return max
|
|
||||||
}
|
|
||||||
return backoff
|
|
||||||
}
|
|
||||||
}(),
|
|
||||||
),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if options.Context != nil {
|
if options.Context != nil {
|
||||||
@ -439,7 +459,7 @@ func NewBroker(opts ...broker.Option) *kBroker {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return &kBroker{
|
return &Broker{
|
||||||
opts: options,
|
opts: options,
|
||||||
kopts: kopts,
|
kopts: kopts,
|
||||||
}
|
}
|
||||||
|
19
kgo_test.go
19
kgo_test.go
@ -28,12 +28,29 @@ var bm = &broker.Message{
|
|||||||
Body: []byte(`"body"`),
|
Body: []byte(`"body"`),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestConnect(t *testing.T) {
|
||||||
|
var addrs []string
|
||||||
|
ctx := context.TODO()
|
||||||
|
b := kgo.NewBroker(
|
||||||
|
broker.Addrs(addrs...),
|
||||||
|
kgo.CommitInterval(5*time.Second),
|
||||||
|
kgo.Options(kg.ClientID("test"), kg.FetchMaxBytes(10*1024*1024)),
|
||||||
|
)
|
||||||
|
if err := b.Init(); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := b.Connect(ctx); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestPubSub(t *testing.T) {
|
func TestPubSub(t *testing.T) {
|
||||||
if tr := os.Getenv("INTEGRATION_TESTS"); len(tr) > 0 {
|
if tr := os.Getenv("INTEGRATION_TESTS"); len(tr) > 0 {
|
||||||
t.Skip()
|
t.Skip()
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := logger.DefaultLogger.Init(logger.WithLevel(loglevel), logger.WithCallerSkipCount(3)); err != nil {
|
if err := logger.DefaultLogger.Init(logger.WithLevel(loglevel)); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
47
logger.go
Normal file
47
logger.go
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
package kgo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
"github.com/twmb/franz-go/pkg/kgo"
|
||||||
|
"go.unistack.org/micro/v3/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
type mlogger struct {
|
||||||
|
l logger.Logger
|
||||||
|
ctx context.Context
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *mlogger) Log(lvl kgo.LogLevel, msg string, args ...interface{}) {
|
||||||
|
var mlvl logger.Level
|
||||||
|
switch lvl {
|
||||||
|
case kgo.LogLevelNone:
|
||||||
|
return
|
||||||
|
case kgo.LogLevelError:
|
||||||
|
mlvl = logger.ErrorLevel
|
||||||
|
case kgo.LogLevelWarn:
|
||||||
|
mlvl = logger.WarnLevel
|
||||||
|
case kgo.LogLevelInfo:
|
||||||
|
mlvl = logger.InfoLevel
|
||||||
|
case kgo.LogLevelDebug:
|
||||||
|
mlvl = logger.DebugLevel
|
||||||
|
default:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
l.l.Log(l.ctx, mlvl, msg, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *mlogger) Level() kgo.LogLevel {
|
||||||
|
switch l.l.Options().Level {
|
||||||
|
case logger.ErrorLevel:
|
||||||
|
return kgo.LogLevelError
|
||||||
|
case logger.WarnLevel:
|
||||||
|
return kgo.LogLevelWarn
|
||||||
|
case logger.InfoLevel:
|
||||||
|
return kgo.LogLevelInfo
|
||||||
|
case logger.DebugLevel, logger.TraceLevel:
|
||||||
|
return kgo.LogLevelDebug
|
||||||
|
}
|
||||||
|
return kgo.LogLevelNone
|
||||||
|
}
|
@ -9,19 +9,26 @@ import (
|
|||||||
"go.unistack.org/micro/v3/meter"
|
"go.unistack.org/micro/v3/meter"
|
||||||
)
|
)
|
||||||
|
|
||||||
type metrics struct {
|
type hookMeter struct {
|
||||||
meter meter.Meter
|
meter meter.Meter
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
_ kgo.HookBrokerConnect = &metrics{}
|
_ kgo.HookBrokerConnect = &hookMeter{}
|
||||||
_ kgo.HookBrokerDisconnect = &metrics{}
|
_ kgo.HookBrokerDisconnect = &hookMeter{}
|
||||||
_ kgo.HookBrokerRead = &metrics{}
|
// HookBrokerE2E
|
||||||
_ kgo.HookBrokerThrottle = &metrics{}
|
_ kgo.HookBrokerRead = &hookMeter{}
|
||||||
_ kgo.HookBrokerWrite = &metrics{}
|
_ kgo.HookBrokerThrottle = &hookMeter{}
|
||||||
_ kgo.HookFetchBatchRead = &metrics{}
|
_ kgo.HookBrokerWrite = &hookMeter{}
|
||||||
_ kgo.HookProduceBatchWritten = &metrics{}
|
_ kgo.HookFetchBatchRead = &hookMeter{}
|
||||||
_ kgo.HookGroupManageError = &metrics{}
|
// HookFetchRecordBuffered
|
||||||
|
// HookFetchRecordUnbuffered
|
||||||
|
_ kgo.HookGroupManageError = &hookMeter{}
|
||||||
|
// HookNewClient
|
||||||
|
_ kgo.HookProduceBatchWritten = &hookMeter{}
|
||||||
|
// HookProduceRecordBuffered
|
||||||
|
// HookProduceRecordPartitioned
|
||||||
|
// HookProduceRecordUnbuffered
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -54,11 +61,11 @@ const (
|
|||||||
labelTopic = "topic"
|
labelTopic = "topic"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (m *metrics) OnGroupManageError(err error) {
|
func (m *hookMeter) OnGroupManageError(err error) {
|
||||||
m.meter.Counter(metricBrokerGroupErrors).Inc()
|
m.meter.Counter(metricBrokerGroupErrors).Inc()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *metrics) OnBrokerConnect(meta kgo.BrokerMetadata, _ time.Duration, _ net.Conn, err error) {
|
func (m *hookMeter) OnBrokerConnect(meta kgo.BrokerMetadata, _ time.Duration, _ net.Conn, err error) {
|
||||||
node := strconv.Itoa(int(meta.NodeID))
|
node := strconv.Itoa(int(meta.NodeID))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
m.meter.Counter(metricBrokerConnects, labelNode, node, labelStatus, labelFaulure).Inc()
|
m.meter.Counter(metricBrokerConnects, labelNode, node, labelStatus, labelFaulure).Inc()
|
||||||
@ -67,12 +74,12 @@ func (m *metrics) OnBrokerConnect(meta kgo.BrokerMetadata, _ time.Duration, _ ne
|
|||||||
m.meter.Counter(metricBrokerConnects, labelNode, node, labelStatus, labelSuccess).Inc()
|
m.meter.Counter(metricBrokerConnects, labelNode, node, labelStatus, labelSuccess).Inc()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *metrics) OnBrokerDisconnect(meta kgo.BrokerMetadata, _ net.Conn) {
|
func (m *hookMeter) OnBrokerDisconnect(meta kgo.BrokerMetadata, _ net.Conn) {
|
||||||
node := strconv.Itoa(int(meta.NodeID))
|
node := strconv.Itoa(int(meta.NodeID))
|
||||||
m.meter.Counter(metricBrokerDisconnects, labelNode, node).Inc()
|
m.meter.Counter(metricBrokerDisconnects, labelNode, node).Inc()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *metrics) OnBrokerWrite(meta kgo.BrokerMetadata, _ int16, bytesWritten int, writeWait, timeToWrite time.Duration, err error) {
|
func (m *hookMeter) OnBrokerWrite(meta kgo.BrokerMetadata, _ int16, bytesWritten int, writeWait, timeToWrite time.Duration, err error) {
|
||||||
node := strconv.Itoa(int(meta.NodeID))
|
node := strconv.Itoa(int(meta.NodeID))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
m.meter.Counter(metricBrokerWriteErrors, labelNode, node).Inc()
|
m.meter.Counter(metricBrokerWriteErrors, labelNode, node).Inc()
|
||||||
@ -83,7 +90,7 @@ func (m *metrics) OnBrokerWrite(meta kgo.BrokerMetadata, _ int16, bytesWritten i
|
|||||||
m.meter.Histogram(metricBrokerWriteLatencies, labelNode, node).Update(timeToWrite.Seconds())
|
m.meter.Histogram(metricBrokerWriteLatencies, labelNode, node).Update(timeToWrite.Seconds())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *metrics) OnBrokerRead(meta kgo.BrokerMetadata, _ int16, bytesRead int, readWait, timeToRead time.Duration, err error) {
|
func (m *hookMeter) OnBrokerRead(meta kgo.BrokerMetadata, _ int16, bytesRead int, readWait, timeToRead time.Duration, err error) {
|
||||||
node := strconv.Itoa(int(meta.NodeID))
|
node := strconv.Itoa(int(meta.NodeID))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
m.meter.Counter(metricBrokerReadErrors, labelNode, node).Inc()
|
m.meter.Counter(metricBrokerReadErrors, labelNode, node).Inc()
|
||||||
@ -95,18 +102,18 @@ func (m *metrics) OnBrokerRead(meta kgo.BrokerMetadata, _ int16, bytesRead int,
|
|||||||
m.meter.Histogram(metricBrokerReadLatencies, labelNode, node).Update(timeToRead.Seconds())
|
m.meter.Histogram(metricBrokerReadLatencies, labelNode, node).Update(timeToRead.Seconds())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *metrics) OnBrokerThrottle(meta kgo.BrokerMetadata, throttleInterval time.Duration, _ bool) {
|
func (m *hookMeter) OnBrokerThrottle(meta kgo.BrokerMetadata, throttleInterval time.Duration, _ bool) {
|
||||||
node := strconv.Itoa(int(meta.NodeID))
|
node := strconv.Itoa(int(meta.NodeID))
|
||||||
m.meter.Histogram(metricBrokerThrottleLatencies, labelNode, node).Update(throttleInterval.Seconds())
|
m.meter.Histogram(metricBrokerThrottleLatencies, labelNode, node).Update(throttleInterval.Seconds())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *metrics) OnProduceBatchWritten(meta kgo.BrokerMetadata, topic string, _ int32, kmetrics kgo.ProduceBatchMetrics) {
|
func (m *hookMeter) OnProduceBatchWritten(meta kgo.BrokerMetadata, topic string, _ int32, kmetrics kgo.ProduceBatchMetrics) {
|
||||||
node := strconv.Itoa(int(meta.NodeID))
|
node := strconv.Itoa(int(meta.NodeID))
|
||||||
m.meter.Counter(metricBrokerProduceBytesUncompressed, labelNode, node, labelTopic, topic).Add(kmetrics.UncompressedBytes)
|
m.meter.Counter(metricBrokerProduceBytesUncompressed, labelNode, node, labelTopic, topic).Add(kmetrics.UncompressedBytes)
|
||||||
m.meter.Counter(metricBrokerProduceBytesCompressed, labelNode, node, labelTopic, topic).Add(kmetrics.CompressedBytes)
|
m.meter.Counter(metricBrokerProduceBytesCompressed, labelNode, node, labelTopic, topic).Add(kmetrics.CompressedBytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *metrics) OnFetchBatchRead(meta kgo.BrokerMetadata, topic string, _ int32, kmetrics kgo.FetchBatchMetrics) {
|
func (m *hookMeter) OnFetchBatchRead(meta kgo.BrokerMetadata, topic string, _ int32, kmetrics kgo.FetchBatchMetrics) {
|
||||||
node := strconv.Itoa(int(meta.NodeID))
|
node := strconv.Itoa(int(meta.NodeID))
|
||||||
m.meter.Counter(metricBrokerFetchBytesUncompressed, labelNode, node, labelTopic, topic).Add(kmetrics.UncompressedBytes)
|
m.meter.Counter(metricBrokerFetchBytesUncompressed, labelNode, node, labelTopic, topic).Add(kmetrics.UncompressedBytes)
|
||||||
m.meter.Counter(metricBrokerFetchBytesCompressed, labelNode, node, labelTopic, topic).Add(kmetrics.CompressedBytes)
|
m.meter.Counter(metricBrokerFetchBytesCompressed, labelNode, node, labelTopic, topic).Add(kmetrics.CompressedBytes)
|
58
options.go
58
options.go
@ -4,13 +4,22 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
kgo "github.com/twmb/franz-go/pkg/kgo"
|
"github.com/twmb/franz-go/pkg/kgo"
|
||||||
"go.unistack.org/micro/v3/broker"
|
"go.unistack.org/micro/v3/broker"
|
||||||
"go.unistack.org/micro/v3/client"
|
"go.unistack.org/micro/v3/client"
|
||||||
)
|
)
|
||||||
|
|
||||||
// DefaultCommitInterval specifies how fast send commit offsets to kafka
|
var (
|
||||||
var DefaultCommitInterval = 5 * time.Second
|
|
||||||
|
// DefaultCommitInterval specifies how fast send commit offsets to kafka
|
||||||
|
DefaultCommitInterval = 5 * time.Second
|
||||||
|
|
||||||
|
// DefaultStatsInterval specifies how fast check consumer lag
|
||||||
|
DefaultStatsInterval = 5 * time.Second
|
||||||
|
|
||||||
|
// DefaultSubscribeMaxInflight specifies how much messages keep inflight
|
||||||
|
DefaultSubscribeMaxInflight = 100
|
||||||
|
)
|
||||||
|
|
||||||
type subscribeContextKey struct{}
|
type subscribeContextKey struct{}
|
||||||
|
|
||||||
@ -48,6 +57,33 @@ func Options(opts ...kgo.Opt) broker.Option {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SubscribeOptions pass additional options to broker in Subscribe
|
||||||
|
func SubscribeOptions(opts ...kgo.Opt) broker.SubscribeOption {
|
||||||
|
return func(o *broker.SubscribeOptions) {
|
||||||
|
if o.Context == nil {
|
||||||
|
o.Context = context.Background()
|
||||||
|
}
|
||||||
|
options, ok := o.Context.Value(optionsKey{}).([]kgo.Opt)
|
||||||
|
if !ok {
|
||||||
|
options = make([]kgo.Opt, 0, len(opts))
|
||||||
|
}
|
||||||
|
options = append(options, opts...)
|
||||||
|
o.Context = context.WithValue(o.Context, optionsKey{}, options)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type clientIDKey struct{}
|
||||||
|
|
||||||
|
func ClientID(id string) broker.Option {
|
||||||
|
return broker.SetOption(clientIDKey{}, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
type groupKey struct{}
|
||||||
|
|
||||||
|
func Group(id string) broker.Option {
|
||||||
|
return broker.SetOption(groupKey{}, id)
|
||||||
|
}
|
||||||
|
|
||||||
type commitIntervalKey struct{}
|
type commitIntervalKey struct{}
|
||||||
|
|
||||||
// CommitInterval specifies interval to send commits
|
// CommitInterval specifies interval to send commits
|
||||||
@ -55,11 +91,21 @@ func CommitInterval(td time.Duration) broker.Option {
|
|||||||
return broker.SetOption(commitIntervalKey{}, td)
|
return broker.SetOption(commitIntervalKey{}, td)
|
||||||
}
|
}
|
||||||
|
|
||||||
var DefaultSubscribeMaxInflight = 1000
|
|
||||||
|
|
||||||
type subscribeMaxInflightKey struct{}
|
type subscribeMaxInflightKey struct{}
|
||||||
|
|
||||||
// SubscribeMaxInFlight specifies interval to send commits
|
// SubscribeMaxInFlight max queued messages
|
||||||
func SubscribeMaxInFlight(n int) broker.SubscribeOption {
|
func SubscribeMaxInFlight(n int) broker.SubscribeOption {
|
||||||
return broker.SetSubscribeOption(subscribeMaxInflightKey{}, n)
|
return broker.SetSubscribeOption(subscribeMaxInflightKey{}, n)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type publishPromiseKey struct{}
|
||||||
|
|
||||||
|
// PublishPromise set the kafka promise func for Produce
|
||||||
|
func PublishPromise(fn func(*kgo.Record, error)) broker.PublishOption {
|
||||||
|
return broker.SetPublishOption(publishPromiseKey{}, fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClientPublishKey set the kafka message key (client option)
|
||||||
|
func ClientPublishPromise(fn func(*kgo.Record, error)) client.PublishOption {
|
||||||
|
return client.SetPublishOption(publishPromiseKey{}, fn)
|
||||||
|
}
|
||||||
|
325
subscriber.go
Normal file
325
subscriber.go
Normal file
@ -0,0 +1,325 @@
|
|||||||
|
package kgo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"strconv"
|
||||||
|
"sync"
|
||||||
|
"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"
|
||||||
|
"go.unistack.org/micro/v3/tracer"
|
||||||
|
)
|
||||||
|
|
||||||
|
type tp struct {
|
||||||
|
t string
|
||||||
|
p int32
|
||||||
|
}
|
||||||
|
|
||||||
|
type consumer struct {
|
||||||
|
c *kgo.Client
|
||||||
|
topic string
|
||||||
|
partition int32
|
||||||
|
htracer *hookTracer
|
||||||
|
opts broker.SubscribeOptions
|
||||||
|
kopts broker.Options
|
||||||
|
handler broker.Handler
|
||||||
|
quit chan struct{}
|
||||||
|
done chan struct{}
|
||||||
|
recs chan kgo.FetchTopicPartition
|
||||||
|
}
|
||||||
|
|
||||||
|
type Subscriber struct {
|
||||||
|
c *kgo.Client
|
||||||
|
topic string
|
||||||
|
htracer *hookTracer
|
||||||
|
opts broker.SubscribeOptions
|
||||||
|
kopts broker.Options
|
||||||
|
handler broker.Handler
|
||||||
|
closed bool
|
||||||
|
done chan struct{}
|
||||||
|
consumers map[tp]*consumer
|
||||||
|
sync.RWMutex
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Subscriber) Client() *kgo.Client {
|
||||||
|
return s.c
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Subscriber) Options() broker.SubscribeOptions {
|
||||||
|
return s.opts
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Subscriber) Topic() string {
|
||||||
|
return s.topic
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Subscriber) Unsubscribe(ctx context.Context) error {
|
||||||
|
if s.closed {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
// case <-ctx.Done():
|
||||||
|
// return ctx.Err()
|
||||||
|
default:
|
||||||
|
s.c.PauseFetchTopics(s.topic)
|
||||||
|
s.c.CloseAllowingRebalance()
|
||||||
|
kc := make(map[string][]int32)
|
||||||
|
for ctp := range s.consumers {
|
||||||
|
kc[ctp.t] = append(kc[ctp.t], ctp.p)
|
||||||
|
}
|
||||||
|
s.killConsumers(ctx, kc)
|
||||||
|
close(s.done)
|
||||||
|
s.closed = true
|
||||||
|
s.c.ResumeFetchTopics(s.topic)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Subscriber) poll(ctx context.Context) {
|
||||||
|
maxInflight := DefaultSubscribeMaxInflight
|
||||||
|
if s.opts.Context != nil {
|
||||||
|
if n, ok := s.opts.Context.Value(subscribeMaxInflightKey{}).(int); n > 0 && ok {
|
||||||
|
maxInflight = n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
s.Lock()
|
||||||
|
for p, l := range lmap {
|
||||||
|
s.kopts.Meter.Counter(semconv.BrokerGroupLag, "topic", s.topic, "group", s.opts.Group, "partition", strconv.Itoa(int(p)), "lag", strconv.Itoa(int(l.Lag)))
|
||||||
|
}
|
||||||
|
s.Unlock()
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
s.c.CloseAllowingRebalance()
|
||||||
|
return
|
||||||
|
case <-s.done:
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
fetches := s.c.PollRecords(ctx, maxInflight)
|
||||||
|
if !s.closed && fetches.IsClientClosed() {
|
||||||
|
s.closed = true
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fetches.EachError(func(t string, p int32, err error) {
|
||||||
|
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
|
||||||
|
})
|
||||||
|
s.c.AllowRebalance()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Subscriber) killConsumers(ctx context.Context, lost map[string][]int32) {
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
defer wg.Wait()
|
||||||
|
|
||||||
|
for topic, partitions := range lost {
|
||||||
|
for _, partition := range partitions {
|
||||||
|
tp := tp{topic, partition}
|
||||||
|
pc := s.consumers[tp]
|
||||||
|
delete(s.consumers, tp)
|
||||||
|
close(pc.quit)
|
||||||
|
if s.kopts.Logger.V(logger.DebugLevel) {
|
||||||
|
s.kopts.Logger.Debug(ctx, fmt.Sprintf("[kgo] waiting for work to finish topic %s partition %d", topic, partition))
|
||||||
|
}
|
||||||
|
wg.Add(1)
|
||||||
|
go func() { <-pc.done; wg.Done() }()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Subscriber) lost(ctx context.Context, _ *kgo.Client, lost map[string][]int32) {
|
||||||
|
if s.kopts.Logger.V(logger.DebugLevel) {
|
||||||
|
s.kopts.Logger.Debug(ctx, fmt.Sprintf("[kgo] lost %#+v", lost))
|
||||||
|
}
|
||||||
|
s.killConsumers(ctx, lost)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Subscriber) revoked(ctx context.Context, c *kgo.Client, revoked map[string][]int32) {
|
||||||
|
if s.kopts.Logger.V(logger.DebugLevel) {
|
||||||
|
s.kopts.Logger.Debug(ctx, fmt.Sprintf("[kgo] revoked %#+v", revoked))
|
||||||
|
}
|
||||||
|
s.killConsumers(ctx, revoked)
|
||||||
|
if err := c.CommitMarkedOffsets(ctx); err != nil {
|
||||||
|
s.kopts.Logger.Error(ctx, "[kgo] revoked CommitMarkedOffsets error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Subscriber) assigned(_ context.Context, c *kgo.Client, assigned map[string][]int32) {
|
||||||
|
for topic, partitions := range assigned {
|
||||||
|
for _, partition := range partitions {
|
||||||
|
pc := &consumer{
|
||||||
|
c: c,
|
||||||
|
topic: topic,
|
||||||
|
partition: partition,
|
||||||
|
htracer: s.htracer,
|
||||||
|
quit: make(chan struct{}),
|
||||||
|
done: make(chan struct{}),
|
||||||
|
recs: make(chan kgo.FetchTopicPartition, 100),
|
||||||
|
handler: s.handler,
|
||||||
|
kopts: s.kopts,
|
||||||
|
opts: s.opts,
|
||||||
|
}
|
||||||
|
s.Lock()
|
||||||
|
s.consumers[tp{topic, partition}] = pc
|
||||||
|
s.Unlock()
|
||||||
|
go pc.consume()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (pc *consumer) consume() {
|
||||||
|
defer close(pc.done)
|
||||||
|
if pc.kopts.Logger.V(logger.DebugLevel) {
|
||||||
|
pc.kopts.Logger.Debug(pc.kopts.Context, fmt.Sprintf("starting, topic %s partition %d", pc.topic, pc.partition))
|
||||||
|
defer pc.kopts.Logger.Debug(pc.kopts.Context, fmt.Sprintf("killing, topic %s partition %d", pc.topic, pc.partition))
|
||||||
|
}
|
||||||
|
|
||||||
|
eh := pc.kopts.ErrorHandler
|
||||||
|
if pc.opts.ErrorHandler != nil {
|
||||||
|
eh = pc.opts.ErrorHandler
|
||||||
|
}
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-pc.quit:
|
||||||
|
return
|
||||||
|
case p := <-pc.recs:
|
||||||
|
for _, record := range p.Records {
|
||||||
|
ctx, sp := pc.htracer.WithProcessSpan(record)
|
||||||
|
ts := time.Now()
|
||||||
|
pc.kopts.Meter.Counter(semconv.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Inc()
|
||||||
|
p := eventPool.Get().(*event)
|
||||||
|
p.msg.Header = nil
|
||||||
|
p.msg.Body = nil
|
||||||
|
p.topic = record.Topic
|
||||||
|
p.err = nil
|
||||||
|
p.ack = false
|
||||||
|
p.msg.Header = metadata.New(len(record.Headers))
|
||||||
|
p.ctx = ctx
|
||||||
|
for _, hdr := range record.Headers {
|
||||||
|
p.msg.Header.Set(hdr.Key, string(hdr.Value))
|
||||||
|
}
|
||||||
|
if pc.kopts.Codec.String() == "noop" {
|
||||||
|
p.msg.Body = record.Value
|
||||||
|
} else if pc.opts.BodyOnly {
|
||||||
|
p.msg.Body = record.Value
|
||||||
|
} else {
|
||||||
|
sp.AddEvent("codec unmarshal start")
|
||||||
|
err := pc.kopts.Codec.Unmarshal(record.Value, p.msg)
|
||||||
|
sp.AddEvent("codec unmarshal stop")
|
||||||
|
if err != nil {
|
||||||
|
sp.SetStatus(tracer.SpanStatusError, err.Error())
|
||||||
|
pc.kopts.Meter.Counter(semconv.SubscribeMessageTotal, "endpoint", record.Topic, "topic", record.Topic, "status", "failure").Inc()
|
||||||
|
p.err = err
|
||||||
|
p.msg.Body = record.Value
|
||||||
|
if eh != nil {
|
||||||
|
_ = eh(p)
|
||||||
|
pc.kopts.Meter.Counter(semconv.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Dec()
|
||||||
|
if p.ack {
|
||||||
|
pc.c.MarkCommitRecords(record)
|
||||||
|
} else {
|
||||||
|
eventPool.Put(p)
|
||||||
|
pc.kopts.Logger.Fatal(pc.kopts.Context, "[kgo] ErrLostMessage wtf?")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
eventPool.Put(p)
|
||||||
|
te := time.Since(ts)
|
||||||
|
pc.kopts.Meter.Summary(semconv.SubscribeMessageLatencyMicroseconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds())
|
||||||
|
pc.kopts.Meter.Histogram(semconv.SubscribeMessageDurationSeconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds())
|
||||||
|
continue
|
||||||
|
} else {
|
||||||
|
pc.kopts.Logger.Error(pc.kopts.Context, "[kgo]: unmarshal error", err)
|
||||||
|
}
|
||||||
|
te := time.Since(ts)
|
||||||
|
pc.kopts.Meter.Counter(semconv.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Dec()
|
||||||
|
pc.kopts.Meter.Summary(semconv.SubscribeMessageLatencyMicroseconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds())
|
||||||
|
pc.kopts.Meter.Histogram(semconv.SubscribeMessageDurationSeconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds())
|
||||||
|
eventPool.Put(p)
|
||||||
|
pc.kopts.Logger.Fatal(pc.kopts.Context, "[kgo] Unmarshal err not handled wtf?")
|
||||||
|
sp.Finish()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sp.AddEvent("handler start")
|
||||||
|
err := pc.handler(p)
|
||||||
|
sp.AddEvent("handler stop")
|
||||||
|
if err == nil {
|
||||||
|
pc.kopts.Meter.Counter(semconv.SubscribeMessageTotal, "endpoint", record.Topic, "topic", record.Topic, "status", "success").Inc()
|
||||||
|
} else {
|
||||||
|
sp.SetStatus(tracer.SpanStatusError, err.Error())
|
||||||
|
pc.kopts.Meter.Counter(semconv.SubscribeMessageTotal, "endpoint", record.Topic, "topic", record.Topic, "status", "failure").Inc()
|
||||||
|
}
|
||||||
|
pc.kopts.Meter.Counter(semconv.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Dec()
|
||||||
|
if err == nil && pc.opts.AutoAck {
|
||||||
|
p.ack = true
|
||||||
|
} else if err != nil {
|
||||||
|
p.err = err
|
||||||
|
if eh != nil {
|
||||||
|
sp.AddEvent("error handler start")
|
||||||
|
_ = eh(p)
|
||||||
|
sp.AddEvent("error handler stop")
|
||||||
|
} else {
|
||||||
|
if pc.kopts.Logger.V(logger.ErrorLevel) {
|
||||||
|
pc.kopts.Logger.Error(pc.kopts.Context, "[kgo]: subscriber error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
te := time.Since(ts)
|
||||||
|
pc.kopts.Meter.Summary(semconv.SubscribeMessageLatencyMicroseconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds())
|
||||||
|
pc.kopts.Meter.Histogram(semconv.SubscribeMessageDurationSeconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds())
|
||||||
|
if p.ack {
|
||||||
|
eventPool.Put(p)
|
||||||
|
pc.c.MarkCommitRecords(record)
|
||||||
|
} else {
|
||||||
|
eventPool.Put(p)
|
||||||
|
pc.kopts.Logger.Fatal(pc.kopts.Context, "[kgo] ErrLostMessage wtf?")
|
||||||
|
sp.SetStatus(tracer.SpanStatusError, "ErrLostMessage")
|
||||||
|
sp.Finish()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
sp.Finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
204
tracer.go
Normal file
204
tracer.go
Normal file
@ -0,0 +1,204 @@
|
|||||||
|
package kgo
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"github.com/twmb/franz-go/pkg/kgo"
|
||||||
|
semconv "go.opentelemetry.io/otel/semconv/v1.18.0"
|
||||||
|
"go.unistack.org/micro/v3/metadata"
|
||||||
|
"go.unistack.org/micro/v3/tracer"
|
||||||
|
)
|
||||||
|
|
||||||
|
type hookTracer struct {
|
||||||
|
clientID string
|
||||||
|
group string
|
||||||
|
tracer tracer.Tracer
|
||||||
|
}
|
||||||
|
|
||||||
|
var messagingSystem = semconv.MessagingSystemKey.String("kafka")
|
||||||
|
|
||||||
|
var (
|
||||||
|
_ kgo.HookProduceRecordBuffered = (*hookTracer)(nil)
|
||||||
|
_ kgo.HookProduceRecordUnbuffered = (*hookTracer)(nil)
|
||||||
|
_ kgo.HookFetchRecordBuffered = (*hookTracer)(nil)
|
||||||
|
_ kgo.HookFetchRecordUnbuffered = (*hookTracer)(nil)
|
||||||
|
)
|
||||||
|
|
||||||
|
// OnProduceRecordBuffered starts a new span for the "publish" operation on a
|
||||||
|
// buffered record.
|
||||||
|
//
|
||||||
|
// It sets span options and injects the span context into record and updates
|
||||||
|
// the record's context, so it can be ended in the OnProduceRecordUnbuffered
|
||||||
|
// hook.
|
||||||
|
func (m *hookTracer) OnProduceRecordBuffered(r *kgo.Record) {
|
||||||
|
// Set up span options.
|
||||||
|
attrs := []interface{}{
|
||||||
|
messagingSystem,
|
||||||
|
semconv.MessagingDestinationKindTopic,
|
||||||
|
semconv.MessagingDestinationName(r.Topic),
|
||||||
|
semconv.MessagingOperationPublish,
|
||||||
|
}
|
||||||
|
attrs = maybeKeyAttr(attrs, r)
|
||||||
|
if m.clientID != "" {
|
||||||
|
attrs = append(attrs, semconv.MessagingKafkaClientIDKey.String(m.clientID))
|
||||||
|
}
|
||||||
|
opts := []tracer.SpanOption{
|
||||||
|
tracer.WithSpanLabels(attrs...),
|
||||||
|
tracer.WithSpanKind(tracer.SpanKindProducer),
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.Context == nil {
|
||||||
|
r.Context = context.Background()
|
||||||
|
}
|
||||||
|
|
||||||
|
omd, ok := metadata.FromOutgoingContext(r.Context)
|
||||||
|
if !ok {
|
||||||
|
omd = metadata.New(len(r.Headers))
|
||||||
|
}
|
||||||
|
|
||||||
|
md := metadata.Copy(omd)
|
||||||
|
for _, h := range r.Headers {
|
||||||
|
md.Set(h.Key, string(h.Value))
|
||||||
|
}
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
r.Context, _ = m.tracer.Start(metadata.NewOutgoingContext(r.Context, md), "sdk.broker", opts...)
|
||||||
|
} else {
|
||||||
|
r.Context, _ = m.tracer.Start(r.Context, "sdk.broker", opts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
setHeaders(r, omd)
|
||||||
|
}
|
||||||
|
|
||||||
|
// OnProduceRecordUnbuffered continues and ends the "publish" span for an
|
||||||
|
// unbuffered record.
|
||||||
|
//
|
||||||
|
// It sets attributes with values unset when producing and records any error
|
||||||
|
// that occurred during the publish operation.
|
||||||
|
func (m *hookTracer) OnProduceRecordUnbuffered(r *kgo.Record, err error) {
|
||||||
|
if span, ok := tracer.SpanFromContext(r.Context); ok {
|
||||||
|
span.AddLabels(
|
||||||
|
semconv.MessagingKafkaDestinationPartition(int(r.Partition)),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
span.SetStatus(tracer.SpanStatusError, err.Error())
|
||||||
|
}
|
||||||
|
span.Finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// OnFetchRecordBuffered starts a new span for the "receive" operation on a
|
||||||
|
// buffered record.
|
||||||
|
//
|
||||||
|
// It sets the span options and extracts the span context from the record,
|
||||||
|
// updates the record's context to ensure it can be ended in the
|
||||||
|
// OnFetchRecordUnbuffered hook and can be used in downstream consumer
|
||||||
|
// processing.
|
||||||
|
func (m *hookTracer) OnFetchRecordBuffered(r *kgo.Record) {
|
||||||
|
// Set up the span options.
|
||||||
|
attrs := []interface{}{
|
||||||
|
messagingSystem,
|
||||||
|
semconv.MessagingSourceKindTopic,
|
||||||
|
semconv.MessagingSourceName(r.Topic),
|
||||||
|
semconv.MessagingOperationReceive,
|
||||||
|
semconv.MessagingKafkaSourcePartition(int(r.Partition)),
|
||||||
|
}
|
||||||
|
attrs = maybeKeyAttr(attrs, r)
|
||||||
|
if m.clientID != "" {
|
||||||
|
attrs = append(attrs, semconv.MessagingKafkaClientIDKey.String(m.clientID))
|
||||||
|
}
|
||||||
|
if m.group != "" {
|
||||||
|
attrs = append(attrs, semconv.MessagingKafkaConsumerGroupKey.String(m.group))
|
||||||
|
}
|
||||||
|
opts := []tracer.SpanOption{
|
||||||
|
tracer.WithSpanLabels(attrs...),
|
||||||
|
tracer.WithSpanKind(tracer.SpanKindConsumer),
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.Context == nil {
|
||||||
|
r.Context = context.Background()
|
||||||
|
}
|
||||||
|
omd, ok := metadata.FromIncomingContext(r.Context)
|
||||||
|
if !ok {
|
||||||
|
omd = metadata.New(len(r.Headers))
|
||||||
|
}
|
||||||
|
|
||||||
|
md := metadata.Copy(omd)
|
||||||
|
for _, h := range r.Headers {
|
||||||
|
md.Set(h.Key, string(h.Value))
|
||||||
|
}
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
r.Context, _ = m.tracer.Start(metadata.NewIncomingContext(r.Context, md), "sdk.broker", opts...)
|
||||||
|
} else {
|
||||||
|
r.Context, _ = m.tracer.Start(r.Context, "sdk.broker", opts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
setHeaders(r, omd)
|
||||||
|
}
|
||||||
|
|
||||||
|
// OnFetchRecordUnbuffered continues and ends the "receive" span for an
|
||||||
|
// unbuffered record.
|
||||||
|
func (m *hookTracer) OnFetchRecordUnbuffered(r *kgo.Record, _ bool) {
|
||||||
|
span, _ := tracer.SpanFromContext(r.Context)
|
||||||
|
span.Finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithProcessSpan starts a new span for the "process" operation on a consumer
|
||||||
|
// record.
|
||||||
|
//
|
||||||
|
// It sets up the span options. The user's application code is responsible for
|
||||||
|
// ending the span.
|
||||||
|
//
|
||||||
|
// This should only ever be called within a polling loop of a consumed record and
|
||||||
|
// not a record which has been created for producing, so call this at the start of each
|
||||||
|
// iteration of your processing for the record.
|
||||||
|
func (m *hookTracer) WithProcessSpan(r *kgo.Record) (context.Context, tracer.Span) {
|
||||||
|
// Set up the span options.
|
||||||
|
attrs := []interface{}{
|
||||||
|
messagingSystem,
|
||||||
|
semconv.MessagingSourceKindTopic,
|
||||||
|
semconv.MessagingSourceName(r.Topic),
|
||||||
|
semconv.MessagingOperationProcess,
|
||||||
|
semconv.MessagingKafkaSourcePartition(int(r.Partition)),
|
||||||
|
semconv.MessagingKafkaMessageOffset(int(r.Offset)),
|
||||||
|
}
|
||||||
|
attrs = maybeKeyAttr(attrs, r)
|
||||||
|
if m.clientID != "" {
|
||||||
|
attrs = append(attrs, semconv.MessagingKafkaClientIDKey.String(m.clientID))
|
||||||
|
}
|
||||||
|
if m.group != "" {
|
||||||
|
attrs = append(attrs, semconv.MessagingKafkaConsumerGroupKey.String(m.group))
|
||||||
|
}
|
||||||
|
opts := []tracer.SpanOption{
|
||||||
|
tracer.WithSpanLabels(attrs...),
|
||||||
|
tracer.WithSpanKind(tracer.SpanKindConsumer),
|
||||||
|
}
|
||||||
|
|
||||||
|
if r.Context == nil {
|
||||||
|
r.Context = context.Background()
|
||||||
|
}
|
||||||
|
md, ok := metadata.FromIncomingContext(r.Context)
|
||||||
|
if !ok {
|
||||||
|
md = metadata.New(len(r.Headers))
|
||||||
|
}
|
||||||
|
for _, h := range r.Headers {
|
||||||
|
md.Set(h.Key, string(h.Value))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start a new span using the provided context and options.
|
||||||
|
return m.tracer.Start(r.Context, "sdk.broker", opts...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func maybeKeyAttr(attrs []interface{}, r *kgo.Record) []interface{} {
|
||||||
|
if r.Key == nil {
|
||||||
|
return attrs
|
||||||
|
}
|
||||||
|
var keykey string
|
||||||
|
if !utf8.Valid(r.Key) {
|
||||||
|
return attrs
|
||||||
|
}
|
||||||
|
keykey = string(r.Key)
|
||||||
|
return append(attrs, semconv.MessagingKafkaMessageKeyKey.String(keykey))
|
||||||
|
}
|
220
util.go
220
util.go
@ -1,220 +0,0 @@
|
|||||||
package kgo
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
kgo "github.com/twmb/franz-go/pkg/kgo"
|
|
||||||
"go.unistack.org/micro/v3/broker"
|
|
||||||
"go.unistack.org/micro/v3/logger"
|
|
||||||
"go.unistack.org/micro/v3/metadata"
|
|
||||||
)
|
|
||||||
|
|
||||||
var ErrLostMessage = errors.New("message not marked for offsets commit and will be lost in next iteration")
|
|
||||||
|
|
||||||
var pPool = sync.Pool{
|
|
||||||
New: func() interface{} {
|
|
||||||
return &publication{msg: broker.NewMessage("")}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
type worker struct {
|
|
||||||
done chan struct{}
|
|
||||||
recs chan []*kgo.Record
|
|
||||||
cherr chan error
|
|
||||||
handler broker.Handler
|
|
||||||
batchHandler broker.BatchHandler
|
|
||||||
opts broker.SubscribeOptions
|
|
||||||
kopts broker.Options
|
|
||||||
tpmap map[string][]int32
|
|
||||||
maxInflight int
|
|
||||||
reader *kgo.Client
|
|
||||||
ctx context.Context
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *subscriber) run(ctx context.Context) {
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
return
|
|
||||||
case <-s.kopts.Context.Done():
|
|
||||||
return
|
|
||||||
default:
|
|
||||||
fetches := s.reader.PollFetches(ctx)
|
|
||||||
if fetches.IsClientClosed() {
|
|
||||||
// TODO: fatal ?
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if len(fetches.Errors()) > 0 {
|
|
||||||
for _, err := range fetches.Errors() {
|
|
||||||
s.kopts.Logger.Fatalf(ctx, "fetch err topic %s partition %d: %v", err.Topic, err.Partition, err.Err)
|
|
||||||
}
|
|
||||||
// TODO: fatal ?
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
fetches.EachPartition(func(p kgo.FetchTopicPartition) {
|
|
||||||
s.Lock()
|
|
||||||
consumers := s.consumers[p.Topic]
|
|
||||||
s.Unlock()
|
|
||||||
if consumers == nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
w, ok := consumers[p.Partition]
|
|
||||||
if !ok {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
select {
|
|
||||||
case err := <-w.cherr:
|
|
||||||
s.kopts.Logger.Fatalf(ctx, "handle err: %v", err)
|
|
||||||
return
|
|
||||||
case w.recs <- p.Records:
|
|
||||||
case <-w.done:
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *subscriber) assigned(ctx context.Context, _ *kgo.Client, assigned map[string][]int32) {
|
|
||||||
maxInflight := DefaultSubscribeMaxInflight
|
|
||||||
|
|
||||||
if s.opts.Context != nil {
|
|
||||||
if n, ok := s.opts.Context.Value(subscribeMaxInflightKey{}).(int); n > 0 && ok {
|
|
||||||
maxInflight = n
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
s.Lock()
|
|
||||||
for topic, partitions := range assigned {
|
|
||||||
if s.consumers[topic] == nil {
|
|
||||||
s.consumers[topic] = make(map[int32]worker)
|
|
||||||
}
|
|
||||||
for _, partition := range partitions {
|
|
||||||
w := worker{
|
|
||||||
done: make(chan struct{}),
|
|
||||||
recs: make(chan []*kgo.Record),
|
|
||||||
cherr: make(chan error),
|
|
||||||
kopts: s.kopts,
|
|
||||||
opts: s.opts,
|
|
||||||
ctx: ctx,
|
|
||||||
tpmap: map[string][]int32{topic: []int32{partition}},
|
|
||||||
reader: s.reader,
|
|
||||||
handler: s.handler,
|
|
||||||
batchHandler: s.batchhandler,
|
|
||||||
maxInflight: maxInflight,
|
|
||||||
}
|
|
||||||
s.consumers[topic][partition] = w
|
|
||||||
go w.handle()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
s.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *subscriber) revoked(_ context.Context, _ *kgo.Client, revoked map[string][]int32) {
|
|
||||||
s.Lock()
|
|
||||||
for topic, partitions := range revoked {
|
|
||||||
ptopics := s.consumers[topic]
|
|
||||||
for _, partition := range partitions {
|
|
||||||
w := ptopics[partition]
|
|
||||||
delete(ptopics, partition)
|
|
||||||
if len(ptopics) == 0 {
|
|
||||||
delete(s.consumers, topic)
|
|
||||||
}
|
|
||||||
close(w.done)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
s.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *worker) handle() {
|
|
||||||
var err error
|
|
||||||
|
|
||||||
eh := w.kopts.ErrorHandler
|
|
||||||
if w.opts.ErrorHandler != nil {
|
|
||||||
eh = w.opts.ErrorHandler
|
|
||||||
}
|
|
||||||
|
|
||||||
paused := false
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-w.ctx.Done():
|
|
||||||
w.cherr <- w.ctx.Err()
|
|
||||||
return
|
|
||||||
case <-w.done:
|
|
||||||
return
|
|
||||||
case recs := <-w.recs:
|
|
||||||
if len(recs) >= w.maxInflight {
|
|
||||||
paused = true
|
|
||||||
w.reader.PauseFetchPartitions(w.tpmap)
|
|
||||||
}
|
|
||||||
for _, record := range recs {
|
|
||||||
p := pPool.Get().(*publication)
|
|
||||||
p.msg.Header = nil
|
|
||||||
p.msg.Body = nil
|
|
||||||
p.topic = record.Topic
|
|
||||||
p.err = nil
|
|
||||||
p.ack = false
|
|
||||||
if w.opts.BodyOnly {
|
|
||||||
p.msg.Body = record.Value
|
|
||||||
} else if w.kopts.Codec.String() == "noop" {
|
|
||||||
p.msg.Body = record.Value
|
|
||||||
p.msg.Header = metadata.New(len(record.Headers))
|
|
||||||
for _, h := range record.Headers {
|
|
||||||
p.msg.Header.Set(h.Key, string(h.Value))
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if err := w.kopts.Codec.Unmarshal(record.Value, p.msg); err != nil {
|
|
||||||
p.err = err
|
|
||||||
p.msg.Body = record.Value
|
|
||||||
if eh != nil {
|
|
||||||
_ = eh(p)
|
|
||||||
if p.ack {
|
|
||||||
w.reader.MarkCommitRecords(record)
|
|
||||||
} else {
|
|
||||||
w.cherr <- ErrLostMessage
|
|
||||||
pPool.Put(p)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
pPool.Put(p)
|
|
||||||
continue
|
|
||||||
} else {
|
|
||||||
if w.kopts.Logger.V(logger.ErrorLevel) {
|
|
||||||
w.kopts.Logger.Errorf(w.kopts.Context, "[kgo]: failed to unmarshal: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pPool.Put(p)
|
|
||||||
w.cherr <- err
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
err = w.handler(p)
|
|
||||||
if err == nil && w.opts.AutoAck {
|
|
||||||
p.ack = true
|
|
||||||
} else if err != nil {
|
|
||||||
p.err = err
|
|
||||||
if eh != nil {
|
|
||||||
_ = eh(p)
|
|
||||||
} else {
|
|
||||||
if w.kopts.Logger.V(logger.ErrorLevel) {
|
|
||||||
w.kopts.Logger.Errorf(w.kopts.Context, "[kgo]: subscriber error: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if p.ack {
|
|
||||||
pPool.Put(p)
|
|
||||||
w.reader.MarkCommitRecords(record)
|
|
||||||
} else {
|
|
||||||
pPool.Put(p)
|
|
||||||
w.cherr <- ErrLostMessage
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if paused {
|
|
||||||
paused = false
|
|
||||||
w.reader.ResumeFetchPartitions(w.tpmap)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
Loading…
Reference in New Issue
Block a user