Compare commits

...

73 Commits

Author SHA1 Message Date
e34f57a515 new kgo version
All checks were successful
sync / sync (push) Has been skipped
coverage / build (push) Successful in 4m56s
test / test (push) Successful in 4m59s
update deps

fixup race conditions

add kfake usage

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2025-05-11 01:49:38 +03:00
ccd912adb2 dont modify connected state on errors
Some checks failed
coverage / build (push) Failing after 1m1s
test / test (push) Successful in 5m12s
sync / sync (push) Has been skipped
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2025-05-02 19:08:54 +03:00
db97b24904 improve sync
All checks were successful
sync / sync (push) Successful in 47s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2025-04-27 21:02:58 +03:00
7410408fc4 update deps
Some checks failed
coverage / build (push) Failing after 1m8s
test / test (push) Successful in 3m27s
sync / sync (push) Successful in 10s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2025-04-27 16:12:32 +03:00
4d28a6ebb2 update actions
Some checks failed
coverage / build (push) Failing after 1m24s
sync / sync (push) Successful in 13s
test / test (push) Successful in 2m8s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2025-04-27 16:09:17 +03:00
f73d9d7347 fixup group lag metric
All checks were successful
test / test (push) Successful in 3m49s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2025-04-23 10:51:39 +03:00
53f72f1246 fixup panic
All checks were successful
test / test (push) Successful in 1m57s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2025-03-12 20:34:30 +03:00
ac454693a6 update to v4
All checks were successful
test / test (push) Successful in 3m29s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2025-03-12 16:57:25 +03:00
f4f8793686 fixup connected status
All checks were successful
test / test (push) Successful in 2m25s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2025-03-07 11:45:36 +03:00
ec4922ad8b fixup connected status
Some checks failed
test / test (push) Has been cancelled
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2025-03-07 11:44:56 +03:00
eaea14e5a8 fixup connected status
All checks were successful
test / test (push) Successful in 3m3s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2025-03-07 11:26:34 +03:00
f6f7139d2f fixup panic
All checks were successful
test / test (push) Successful in 2m4s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2025-03-03 10:43:41 +03:00
51e4118dfc cleanup
All checks were successful
test / test (push) Successful in 2m19s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2025-02-27 12:41:42 +03:00
aaf8c43e04 add ability to fail probes and fatal on broker errors
All checks were successful
test / test (push) Successful in 3m12s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2025-02-26 11:06:11 +03:00
cfecb4afd0 export broker state
All checks were successful
test / test (push) Successful in 3m16s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2025-02-25 17:30:48 +03:00
ae4ae64694 added set ct for records && updated setHeaders (#150)
All checks were successful
test / test (push) Successful in 3m45s
Reviewed-on: #150
Co-authored-by: Evstigneev Denis <danteevstigneev@yandex.ru>
Co-committed-by: Evstigneev Denis <danteevstigneev@yandex.ru>
2025-01-21 15:29:02 +03:00
2ca4e5c74e Merge pull request 'update gomod' (#149) from devstigneev/micro-broker-kgo:v3 into v3
All checks were successful
test / test (push) Successful in 3m26s
Reviewed-on: #149
2025-01-16 16:15:13 +03:00
2809ebcaeb update gomod
All checks were successful
lint / lint (pull_request) Successful in 2m11s
test / test (pull_request) Successful in 4m8s
2025-01-16 16:13:05 +03:00
3f04403319 Merge pull request 'update deps && structs && hooks' (#147) from devstigneev/micro-broker-kgo:v3 into v3
All checks were successful
test / test (push) Successful in 3m47s
Reviewed-on: #147
2024-12-20 00:02:24 +03:00
8edfc11eef rebase v3
All checks were successful
lint / lint (pull_request) Successful in 1m7s
test / test (pull_request) Successful in 2m49s
2024-12-19 23:42:51 +03:00
cb5ef75e09 Merge remote-tracking branch 'origin/v3' into v3
# Conflicts:
#	go.sum
#	subscriber.go
2024-12-19 23:42:16 +03:00
d5bd105cc6 undo comments 2024-12-19 23:41:57 +03:00
1ba02ed8ad resolve conflict 2024-12-19 23:41:55 +03:00
7c5da60556 update deps && structs && hooks 2024-12-19 23:39:40 +03:00
07fa36d704 update go.mod
All checks were successful
test / test (push) Successful in 4m32s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-12-19 21:58:34 +03:00
849bbd7a09 undo comments
Some checks failed
test / test (pull_request) Failing after 1m17s
lint / lint (pull_request) Successful in 1m52s
2024-12-19 13:42:25 +03:00
f461bb6876 resolve conflict
Some checks failed
lint / lint (pull_request) Has been cancelled
test / test (pull_request) Has been cancelled
2024-12-19 13:36:55 +03:00
201d22d1c4 Merge remote-tracking branch 'fork/v3' into v3
# Conflicts:
#	.gitignore
#	event.go
#	go.mod
#	go.sum
#	kgo.go
#	kgo_test.go
#	subscriber.go
2024-12-19 13:33:40 +03:00
ff6a272594 update deps && structs && hooks 2024-12-19 13:31:34 +03:00
1018abe7bd update deps && structs && hooks
Some checks failed
codeql / analyze (go) (pull_request) Has been cancelled
prbuild / test (pull_request) Has been cancelled
prbuild / lint (pull_request) Has been cancelled
2024-12-19 13:22:30 +03:00
398c3c81cb Merge pull request 'Upd workflows' (#146) from atolstikhin/micro-broker-kgo:v3 into v3
All checks were successful
test / test (push) Successful in 12m59s
Reviewed-on: #146
2024-12-11 23:12:57 +03:00
Aleksandr Tolstikhin
786d03b521 Upd workflows
Some checks failed
autoapprove / autoapprove (pull_request) Successful in 16s
automerge / automerge (pull_request) Has been skipped
lint / lint (pull_request) Failing after 1m19s
test / test (pull_request) Successful in 1m15s
dependabot-automerge / automerge (pull_request) Failing after 14m40s
2024-12-11 22:17:33 +07:00
937c9d5720 Merge pull request 'Update script of jobs' (#142) from atolstikhin/micro-broker-kgo:v3 into v3
Some checks failed
codeql / analyze (go) (push) Failing after 46s
test / test (push) Failing after 5m33s
Reviewed-on: #142
2024-12-09 19:20:31 +03:00
Aleksandr Tolstikhin
951fba55fa Merge remote-tracking branch 'rem/v3' into v3
Some checks failed
automerge / automerge (pull_request) Has been skipped
dependabot-automerge / automerge (pull_request) Has been skipped
autoapprove / autoapprove (pull_request) Successful in 11s
codeql / analyze (go) (pull_request) Failing after 49s
test / test (pull_request) Failing after 5m38s
lint / lint (pull_request) Failing after 15m2s
2024-12-09 22:21:40 +07:00
Aleksandr Tolstikhin
ec5238ed14 Fix by code review 2024-12-09 22:17:44 +07:00
d8f44a924e Merge pull request 'Update workflows' (#141) from atolstikhin/micro-broker-kgo:v3 into v3
Some checks failed
codeql / analyze (go) (push) Failing after 48s
test / test (push) Failing after 13m41s
Reviewed-on: #141
2024-12-09 16:25:10 +03:00
Aleksandr Tolstikhin
ffe9e5d952 Update workflows
Some checks failed
automerge / automerge (pull_request) Has been skipped
dependabot-automerge / automerge (pull_request) Has been skipped
autoapprove / autoapprove (pull_request) Successful in 6s
codeql / analyze (go) (pull_request) Failing after 52s
lint / lint (pull_request) Failing after 10m30s
test / test (pull_request) Has been cancelled
2024-12-09 18:35:02 +07:00
8c362fd6ae fixup panic
Some checks failed
codeql / analyze (go) (push) Failing after 49s
build / test (push) Failing after 4m53s
build / lint (push) Successful in 9m29s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-12-05 09:53:40 +03:00
90365a455c update for latest micro
Some checks failed
build / test (push) Failing after 2s
build / lint (push) Failing after 1s
codeql / analyze (go) (push) Failing after 2s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-12-04 14:54:13 +03:00
6a218ca7b2 Merge pull request 'add copied metadata && update deps' (#137) from devstigneev/micro-broker-kgo:fix_copymd into v3
Some checks failed
build / test (push) Failing after 1s
build / lint (push) Failing after 0s
codeql / analyze (go) (push) Failing after 0s
Reviewed-on: #137
2024-11-22 12:56:23 +03:00
ba9b88c650 add copied metadata && update deps
Some checks failed
automerge / automerge (pull_request) Has been skipped
autoapprove / autoapprove (pull_request) Successful in 5s
dependabot-automerge / automerge (pull_request) Has been skipped
codeql / analyze (go) (pull_request) Has been cancelled
prbuild / test (pull_request) Has been cancelled
prbuild / lint (pull_request) Has been cancelled
2024-11-21 22:22:26 +03:00
aedd60ea87 update for latest micro logger changes
Some checks failed
codeql / analyze (go) (push) Failing after 40s
build / test (push) Failing after 4m52s
build / lint (push) Successful in 9m31s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-10-12 12:45:53 +03:00
ea2ac477be set UnknownTopicRetries with 0
Some checks failed
codeql / analyze (go) (push) Failing after 38s
build / test (push) Failing after 4m52s
build / lint (push) Successful in 9m28s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-10-06 13:53:30 +03:00
c1fa2f639d minimize memory usage, name all traces with sdk.broker
Some checks failed
build / lint (push) Failing after 8s
build / test (push) Failing after 7s
codeql / analyze (go) (push) Failing after 11s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-09-27 13:28:17 +03:00
8e3f2c67d7 update deps
Some checks failed
build / test (push) Failing after 7s
build / lint (push) Failing after 8s
codeql / analyze (go) (push) Failing after 10s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-09-20 18:05:20 +03:00
e66194695e improve tracing
Some checks failed
build / test (push) Failing after 25s
build / lint (push) Successful in 22s
codeql / analyze (go) (push) Failing after 46s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-07-22 23:45:23 +03:00
894d6f4f20 tracing fixes
Some checks failed
build / lint (push) Successful in 27s
build / test (push) Failing after 29s
codeql / analyze (go) (push) Failing after 50s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-07-22 01:11:33 +03:00
d404fa31ab export Subscriber
Some checks failed
build / test (push) Failing after 1m38s
codeql / analyze (go) (push) Failing after 1m59s
build / lint (push) Successful in 9m15s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-05-22 18:28:51 +03:00
88777a29ad add helper funcs
Some checks failed
build / test (push) Failing after 1m39s
codeql / analyze (go) (push) Failing after 2m8s
build / lint (push) Successful in 9m13s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-05-22 17:49:36 +03:00
23c2903c21 fixup tracing
Some checks failed
build / test (push) Failing after 1m36s
codeql / analyze (go) (push) Failing after 1m42s
build / lint (push) Successful in 9m13s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-05-06 08:20:27 +03:00
8fcc23f639 fixup tracing
Some checks failed
build / test (push) Failing after 1m46s
codeql / analyze (go) (push) Failing after 1m45s
build / lint (push) Successful in 9m12s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-05-06 07:30:17 +03:00
25dda1f34c fixup tracing
Some checks failed
build / test (push) Failing after 1m31s
codeql / analyze (go) (push) Failing after 1m49s
build / lint (push) Successful in 9m17s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-05-05 20:20:34 +03:00
fe66086c40 fixup tracing
Some checks failed
build / test (push) Failing after 2m10s
codeql / analyze (go) (push) Failing after 2m7s
build / lint (push) Successful in 9m15s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-05-05 16:20:05 +03:00
7329bc23bc export lag for all partition, not only owned
Some checks failed
build / test (push) Failing after 1m14s
build / lint (push) Successful in 9m28s
codeql / analyze (go) (push) Failing after 14m55s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-05-02 23:01:04 +03:00
c240631cdb fixup panic
Some checks failed
build / test (push) Failing after 1m32s
codeql / analyze (go) (push) Failing after 2m37s
build / lint (push) Successful in 9m31s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-05-02 10:32:33 +03:00
Кирилл Горбунов
6a68533824 #133 fix race. (#134)
Some checks failed
build / test (push) Has been cancelled
build / lint (push) Has been cancelled
codeql / analyze (go) (push) Has been cancelled
Co-authored-by: Gorbunov Kirill Andreevich <kgorbunov@mtsbank.ru>
Reviewed-on: #134
Co-authored-by: Кирилл Горбунов <kirya_gorbunov_2015@mail.ru>
Co-committed-by: Кирилл Горбунов <kirya_gorbunov_2015@mail.ru>
2024-04-19 19:26:06 +03:00
058b6354c0 fixup tracing
Some checks failed
build / test (push) Failing after 1m27s
codeql / analyze (go) (push) Failing after 1m43s
build / lint (push) Successful in 9m20s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-04-14 23:17:38 +03:00
1f4cf11afe fix group lag exporter
Some checks failed
build / test (push) Failing after 1m36s
codeql / analyze (go) (push) Failing after 1m37s
build / lint (push) Successful in 9m14s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-04-13 02:40:45 +03:00
39177da1d0 massive meter usage
Some checks failed
build / test (push) Failing after 1m33s
codeql / analyze (go) (push) Failing after 1m39s
build / lint (push) Successful in 9m15s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-04-13 02:24:16 +03:00
d559db4050 fixup logger caller skip count
Some checks failed
build / test (push) Failing after 1m17s
codeql / analyze (go) (push) Failing after 8m52s
build / lint (push) Successful in 9m15s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-04-13 00:53:09 +03:00
aa946c469a fixup logger caller skip count
Some checks failed
codeql / analyze (go) (push) Failing after 1m51s
build / test (push) Failing after 1m55s
build / lint (push) Successful in 9m14s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-04-13 00:40:12 +03:00
9c4d88bb69 fixup for attrs
Some checks failed
build / test (push) Failing after 1m31s
codeql / analyze (go) (push) Failing after 1m53s
build / lint (push) Successful in 9m15s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-03-15 09:38:31 +03:00
56288f46b1 cleanup tracing
Some checks failed
build / test (push) Failing after 1m30s
codeql / analyze (go) (push) Failing after 1m57s
build / lint (push) Successful in 9m19s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-03-14 23:25:19 +03:00
81dcef8b28 fixup tracer span labels
Some checks failed
build / test (push) Failing after 1m29s
codeql / analyze (go) (push) Failing after 1m53s
build / lint (push) Successful in 9m15s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-03-14 16:47:44 +03:00
ec7a22b2dc fix double init
Some checks failed
build / test (push) Failing after 1m34s
codeql / analyze (go) (push) Failing after 2m5s
build / lint (push) Successful in 9m15s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-03-07 09:06:33 +03:00
d2ac0c1360 update deps
Some checks failed
build / test (push) Failing after 1m49s
codeql / analyze (go) (push) Failing after 2m6s
build / lint (push) Successful in 9m18s
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-03-07 00:46:24 +03:00
69dd8c4eea fixup fields again
Some checks failed
build / test (push) Has been cancelled
build / lint (push) Has been cancelled
codeql / analyze (go) (push) Has been cancelled
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-02-22 09:04:02 +03:00
27a6a923cd gomod
Some checks are pending
build / test (push) Waiting to run
build / lint (push) Waiting to run
codeql / analyze (go) (push) Waiting to run
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-02-21 15:45:13 +03:00
0a395235d6 backport
Some checks are pending
build / test (push) Waiting to run
build / lint (push) Waiting to run
codeql / analyze (go) (push) Waiting to run
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-02-21 15:08:58 +03:00
23f0ad0f2f Merge pull request 'change log fields' (#129) from fix into v3
Some checks failed
build / test (push) Has been cancelled
build / lint (push) Has been cancelled
codeql / analyze (go) (push) Has been cancelled
Reviewed-on: #129
2024-02-15 10:45:37 +03:00
4fcbe0a770 change log fields
Some checks failed
codeql / analyze (go) (pull_request) Has been cancelled
prbuild / test (pull_request) Has been cancelled
prbuild / lint (pull_request) Has been cancelled
autoapprove / autoapprove (pull_request) Has been cancelled
automerge / automerge (pull_request) Has been cancelled
dependabot-automerge / automerge (pull_request) Has been cancelled
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-02-15 10:44:59 +03:00
28c9865121 Merge pull request 'logger fix' (#128) from logger_fix into v3
Some checks are pending
build / test (push) Waiting to run
build / lint (push) Waiting to run
codeql / analyze (go) (push) Waiting to run
Reviewed-on: #128
2024-02-15 10:21:06 +03:00
697413d829 logger fix
Some checks failed
codeql / analyze (go) (pull_request) Has been cancelled
prbuild / test (pull_request) Has been cancelled
prbuild / lint (pull_request) Has been cancelled
autoapprove / autoapprove (pull_request) Has been cancelled
automerge / automerge (pull_request) Has been cancelled
dependabot-automerge / automerge (pull_request) Has been cancelled
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2024-02-15 10:20:15 +03:00
27 changed files with 1372 additions and 618 deletions

View File

@@ -1,19 +0,0 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
# Maintain dependencies for GitHub Actions
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
# Maintain dependencies for Golang
- package-ecosystem: "gomod"
directory: "/"
schedule:
interval: "daily"

View File

@@ -1,20 +0,0 @@
name: "autoapprove"
on:
pull_request_target:
types: [assigned, opened, synchronize, reopened]
permissions:
pull-requests: write
contents: write
jobs:
autoapprove:
runs-on: ubuntu-latest
steps:
- name: approve
uses: hmarr/auto-approve-action@v3
if: github.actor == 'vtolstov' || github.actor == 'dependabot[bot]'
id: approve
with:
github-token: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -1,21 +0,0 @@
name: "automerge"
on:
pull_request_target:
types: [assigned, opened, synchronize, reopened]
permissions:
pull-requests: write
contents: write
jobs:
automerge:
runs-on: ubuntu-latest
if: github.actor == 'vtolstov'
steps:
- name: merge
id: merge
run: gh pr merge --auto --merge "$PR_URL"
env:
PR_URL: ${{github.event.pull_request.html_url}}
GITHUB_TOKEN: ${{secrets.TOKEN}}

View File

@@ -1,47 +0,0 @@
name: build
on:
push:
branches:
- master
- v3
jobs:
test:
name: test
runs-on: ubuntu-latest
steps:
- name: setup
uses: actions/setup-go@v3
with:
go-version: 1.17
- name: checkout
uses: actions/checkout@v3
- name: cache
uses: actions/cache@v3
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
restore-keys: ${{ runner.os }}-go-
- name: deps
run: go get -v -t -d ./...
- name: test
env:
INTEGRATION_TESTS: yes
run: go test -mod readonly -v ./...
lint:
name: lint
runs-on: ubuntu-latest
steps:
- name: checkout
uses: actions/checkout@v3
- name: lint
uses: golangci/golangci-lint-action@v3.4.0
continue-on-error: true
with:
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
version: v1.30
# Optional: working directory, useful for monorepos
# working-directory: somedir
# Optional: golangci-lint command line arguments.
# args: --issues-exit-code=0
# Optional: show only new issues if it's a pull request. The default value is `false`.
# only-new-issues: true

View File

@@ -1,78 +0,0 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "codeql"
on:
workflow_run:
workflows: ["prbuild"]
types:
- completed
push:
branches: [ master, v3 ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ master, v3 ]
schedule:
- cron: '34 1 * * 0'
jobs:
analyze:
name: analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'go' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
# Learn more:
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
steps:
- name: checkout
uses: actions/checkout@v3
- name: setup
uses: actions/setup-go@v3
with:
go-version: 1.17
# Initializes the CodeQL tools for scanning.
- name: init
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: autobuild
uses: github/codeql-action/autobuild@v2
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: analyze
uses: github/codeql-action/analyze@v2

View File

@@ -1,27 +0,0 @@
name: "dependabot-automerge"
on:
pull_request_target:
types: [assigned, opened, synchronize, reopened]
permissions:
pull-requests: write
contents: write
jobs:
automerge:
runs-on: ubuntu-latest
if: github.actor == 'dependabot[bot]'
steps:
- name: metadata
id: metadata
uses: dependabot/fetch-metadata@v1.3.6
with:
github-token: "${{ secrets.TOKEN }}"
- name: merge
id: merge
if: ${{contains(steps.metadata.outputs.dependency-names, 'go.unistack.org')}}
run: gh pr merge --auto --merge "$PR_URL"
env:
PR_URL: ${{github.event.pull_request.html_url}}
GITHUB_TOKEN: ${{secrets.TOKEN}}

54
.github/workflows/job_coverage.yml vendored Normal file
View File

@@ -0,0 +1,54 @@
name: coverage
on:
push:
branches: [ main, v3, v4 ]
paths-ignore:
- '.github/**'
- '.gitea/**'
pull_request:
branches: [ main, v3, v4 ]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: checkout code
uses: actions/checkout@v4
with:
filter: 'blob:none'
- name: setup go
uses: actions/setup-go@v5
with:
cache-dependency-path: "**/*.sum"
go-version: 'stable'
- name: test coverage
run: |
go test -v -cover ./... -covermode=count -coverprofile coverage.out -coverpkg ./...
go tool cover -func coverage.out -o coverage.out
- name: coverage badge
uses: tj-actions/coverage-badge-go@v2
with:
green: 80
filename: coverage.out
- uses: stefanzweifel/git-auto-commit-action@v4
name: autocommit
with:
commit_message: Apply Code Coverage Badge
skip_fetch: true
skip_checkout: true
file_pattern: ./README.md
- name: push
if: steps.auto-commit-action.outputs.changes_detected == 'true'
uses: ad-m/github-push-action@master
with:
github_token: ${{ github.token }}
branch: ${{ github.ref }}

29
.github/workflows/job_lint.yml vendored Normal file
View File

@@ -0,0 +1,29 @@
name: lint
on:
pull_request:
types: [opened, reopened, synchronize]
branches: [ master, v3, v4 ]
paths-ignore:
- '.github/**'
- '.gitea/**'
jobs:
lint:
runs-on: ubuntu-latest
steps:
- name: checkout code
uses: actions/checkout@v4
with:
filter: 'blob:none'
- name: setup go
uses: actions/setup-go@v5
with:
cache-dependency-path: "**/*.sum"
go-version: 'stable'
- name: setup deps
run: go get -v ./...
- name: run lint
uses: https://github.com/golangci/golangci-lint-action@v6
with:
version: 'latest'

52
.github/workflows/job_sync.yml vendored Normal file
View File

@@ -0,0 +1,52 @@
name: sync
on:
schedule:
- cron: '*/5 * * * *'
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
jobs:
sync:
if: github.server_url == 'zhttps://github.com'
runs-on: ubuntu-latest
steps:
- name: init
run: |
git config --global user.email "vtolstov <vtolstov@users.noreply.github.com>"
git config --global user.name "github-actions[bot]"
echo "machine git.unistack.org login vtolstov password ${{ secrets.TOKEN_GITEA }}" >> /root/.netrc
echo "machine github.com login vtolstov password ${{ secrets.TOKEN_GITHUB }}" >> /root/.netrc
- name: sync master
run: |
git clone --filter=blob:none --filter=tree:0 --branch master --single-branch ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} repo
cd repo
git remote add --no-tags --fetch --track master upstream https://github.com/${GITHUB_REPOSITORY}
git merge upstream/master
git push upstream master --progress
git push origin master --progress
cd ../
rm -rf repo
- name: sync v3
run: |
git clone --filter=blob:none --filter=tree:0 --branch v3 --single-branch ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} repo
cd repo
git remote add --no-tags --fetch --track v3 upstream https://github.com/${GITHUB_REPOSITORY}
git merge upstream/v3
git push upstream v3 --progress
git push origin v3 --progress
cd ../
rm -rf repo
- name: sync v4
run: |
git clone --filter=blob:none --filter=tree:0 --branch v4 --single-branch ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY} repo
cd repo
git remote add --no-tags --fetch --track v4 upstream https://github.com/${GITHUB_REPOSITORY}
git merge upstream/v4
git push upstream v4 --progress
git push origin v4 --progress
cd ../
rm -rf repo

31
.github/workflows/job_test.yml vendored Normal file
View File

@@ -0,0 +1,31 @@
name: test
on:
pull_request:
types: [opened, reopened, synchronize]
branches: [ master, v3, v4 ]
push:
branches: [ master, v3, v4 ]
paths-ignore:
- '.github/**'
- '.gitea/**'
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: checkout code
uses: actions/checkout@v4
with:
filter: 'blob:none'
- name: setup go
uses: actions/setup-go@v5
with:
cache-dependency-path: "**/*.sum"
go-version: 'stable'
- name: setup deps
run: go get -v ./...
- name: run test
env:
INTEGRATION_TESTS: yes
run: go test -mod readonly -v ./...

50
.github/workflows/job_tests.yml vendored Normal file
View File

@@ -0,0 +1,50 @@
name: test
on:
pull_request:
types: [opened, reopened, synchronize]
branches: [ master, v3, v4 ]
push:
branches: [ master, v3, v4 ]
paths-ignore:
- '.github/**'
- '.gitea/**'
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: checkout code
uses: actions/checkout@v4
with:
filter: 'blob:none'
- name: checkout tests
uses: actions/checkout@v4
with:
ref: master
filter: 'blob:none'
repository: unistack-org/micro-tests
path: micro-tests
- name: setup go
uses: actions/setup-go@v5
with:
cache-dependency-path: "**/*.sum"
go-version: 'stable'
- name: setup go work
env:
GOWORK: /workspace/${{ github.repository_owner }}/go.work
run: |
go work init
go work use .
go work use micro-tests
- name: setup deps
env:
GOWORK: /workspace/${{ github.repository_owner }}/go.work
run: go get -v ./...
- name: run tests
env:
INTEGRATION_TESTS: yes
GOWORK: /workspace/${{ github.repository_owner }}/go.work
run: |
cd micro-tests
go test -mod readonly -v ./... || true

View File

@@ -1,47 +0,0 @@
name: prbuild
on:
pull_request:
branches:
- master
- v3
jobs:
test:
name: test
runs-on: ubuntu-latest
steps:
- name: setup
uses: actions/setup-go@v3
with:
go-version: 1.17
- name: checkout
uses: actions/checkout@v3
- name: cache
uses: actions/cache@v3
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
restore-keys: ${{ runner.os }}-go-
- name: deps
run: go get -v -t -d ./...
- name: test
env:
INTEGRATION_TESTS: yes
run: go test -mod readonly -v ./...
lint:
name: lint
runs-on: ubuntu-latest
steps:
- name: checkout
uses: actions/checkout@v3
- name: lint
uses: golangci/golangci-lint-action@v3.4.0
continue-on-error: true
with:
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
version: v1.30
# Optional: working directory, useful for monorepos
# working-directory: somedir
# Optional: golangci-lint command line arguments.
# args: --issues-exit-code=0
# Optional: show only new issues if it's a pull request. The default value is `false`.
# only-new-issues: true

6
.gitignore vendored
View File

@@ -13,3 +13,9 @@
# Dependency directories (remove the comment below to include it) # Dependency directories (remove the comment below to include it)
# vendor/ # vendor/
# General
.DS_Store
.idea
.vscode
bin/

5
.golangci.yml Normal file
View File

@@ -0,0 +1,5 @@
run:
concurrency: 8
timeout: 5m
issues-exit-code: 1
tests: true

View File

@@ -1,9 +1,9 @@
# micro-broker-kgo # broker-kgo
yet another micro kafka broker alternative
TODO: TODO:
* dont always append options from context on Init and New
* add SubscriberOptions(...kgo.Opt) 1) экспортируем текущий оффсет для каждой партиции в группе
* add ServerSubscribeOptions(...kgo.Opt) 2) экспортируем лаг для группы
* check PublisherOptions(...kgo.Opt) 3) мониторим
* check ClientPublisherOptions(...kgo.Opt) 1) если есть лаг больше нуля
2) если дельта оффсета за нужное нам время не

75
broker.go Normal file
View File

@@ -0,0 +1,75 @@
package kgo
import (
"context"
"net"
"sync/atomic"
"time"
"github.com/twmb/franz-go/pkg/kgo"
"go.unistack.org/micro/v4/logger"
)
type hookEvent struct {
log logger.Logger
fatalOnError bool
connected *atomic.Uint32
}
var (
_ kgo.HookBrokerConnect = &hookEvent{}
_ kgo.HookBrokerDisconnect = &hookEvent{}
_ kgo.HookBrokerRead = &hookEvent{}
_ kgo.HookBrokerWrite = &hookEvent{}
_ kgo.HookGroupManageError = &hookEvent{}
_ kgo.HookProduceRecordUnbuffered = &hookEvent{}
)
func (m *hookEvent) OnGroupManageError(err error) {
if err != nil && !kgo.IsRetryableBrokerErr(err) {
m.connected.Store(0)
if m.fatalOnError {
m.log.Fatal(context.TODO(), "kgo.OnGroupManageError", err)
}
}
}
func (m *hookEvent) OnBrokerConnect(_ kgo.BrokerMetadata, _ time.Duration, _ net.Conn, err error) {
if err != nil && !kgo.IsRetryableBrokerErr(err) {
m.connected.Store(0)
if m.fatalOnError {
m.log.Fatal(context.TODO(), "kgo.OnBrokerConnect", err)
}
}
}
func (m *hookEvent) OnBrokerDisconnect(_ kgo.BrokerMetadata, _ net.Conn) {
// m.connected.Store(0)
}
func (m *hookEvent) OnBrokerWrite(_ kgo.BrokerMetadata, _ int16, _ int, _ time.Duration, _ time.Duration, err error) {
if err != nil && !kgo.IsRetryableBrokerErr(err) {
m.connected.Store(0)
if m.fatalOnError {
m.log.Fatal(context.TODO(), "kgo.OnBrokerWrite", err)
}
}
}
func (m *hookEvent) OnBrokerRead(_ kgo.BrokerMetadata, _ int16, _ int, _ time.Duration, _ time.Duration, err error) {
if err != nil && !kgo.IsRetryableBrokerErr(err) {
m.connected.Store(0)
if m.fatalOnError {
m.log.Fatal(context.TODO(), "kgo.OnBrokerRead", err)
}
}
}
func (m *hookEvent) OnProduceRecordUnbuffered(_ *kgo.Record, err error) {
if err != nil && !kgo.IsRetryableBrokerErr(err) {
m.connected.Store(0)
if m.fatalOnError {
m.log.Fatal(context.TODO(), "kgo.OnProduceRecordUnbuffered", err)
}
}
}

93
carrier.go Normal file
View File

@@ -0,0 +1,93 @@
package kgo
import (
"net/http"
"slices"
"strings"
"github.com/twmb/franz-go/pkg/kgo"
"go.unistack.org/micro/v4/metadata"
)
// RecordCarrier injects and extracts traces from a kgo.Record.
//
// This type exists to satisfy the otel/propagation.TextMapCarrier interface.
type RecordCarrier struct {
record *kgo.Record
}
// NewRecordCarrier creates a new RecordCarrier.
func NewRecordCarrier(record *kgo.Record) RecordCarrier {
return RecordCarrier{record: record}
}
// Get retrieves a single value for a given key if it exists.
func (c RecordCarrier) Get(key string) string {
for _, h := range c.record.Headers {
if h.Key == key {
return string(h.Value)
}
}
return ""
}
// Set sets a header.
func (c RecordCarrier) Set(key, val string) {
// Check if key already exists.
for i, h := range c.record.Headers {
if h.Key == key {
// Key exist, update the value.
c.record.Headers[i].Value = []byte(val)
return
}
}
// Key does not exist, append new header.
c.record.Headers = append(c.record.Headers, kgo.RecordHeader{
Key: key,
Value: []byte(val),
})
}
// Keys returns a slice of all key identifiers in the carrier.
func (c RecordCarrier) Keys() []string {
out := make([]string, len(c.record.Headers))
for i, h := range c.record.Headers {
out[i] = h.Key
}
return out
}
func setHeaders(r *kgo.Record, md metadata.Metadata, exclude ...string) {
seen := make(map[string]struct{})
loop:
for k, v := range md {
k = http.CanonicalHeaderKey(k)
if _, ok := seen[k]; ok {
continue loop
}
if slices.ContainsFunc(exclude, func(s string) bool {
return strings.EqualFold(s, k)
}) {
continue loop
}
for i := 0; i < len(r.Headers); i++ {
if strings.EqualFold(r.Headers[i].Key, k) {
// Key exist, update the value.
r.Headers[i].Value = []byte(strings.Join(v, ","))
continue loop
}
}
// Key does not exist, append new header.
r.Headers = append(r.Headers, kgo.RecordHeader{
Key: k,
Value: []byte(strings.Join(v, ",")),
})
seen[k] = struct{}{}
}
}

View File

@@ -1,42 +0,0 @@
package kgo
import (
"sync"
"go.unistack.org/micro/v3/broker"
)
type event struct {
topic string
err error
sync.RWMutex
msg *broker.Message
ack bool
}
func (p *event) Topic() string {
return p.topic
}
func (p *event) Message() *broker.Message {
return p.msg
}
func (p *event) Ack() error {
p.ack = true
return nil
}
func (p *event) Error() error {
return p.err
}
func (p *event) SetError(err error) {
p.err = err
}
var eventPool = sync.Pool{
New: func() interface{} {
return &event{msg: &broker.Message{}}
},
}

24
go.mod
View File

@@ -1,14 +1,24 @@
module go.unistack.org/micro-broker-kgo/v3 module go.unistack.org/micro-broker-kgo/v4
go 1.17 go 1.23.8
require ( require (
github.com/twmb/franz-go v1.12.1 github.com/twmb/franz-go v1.19.1
github.com/twmb/franz-go/pkg/kmsg v1.4.0 github.com/twmb/franz-go/pkg/kadm v1.16.0
go.unistack.org/micro/v3 v3.10.23 github.com/twmb/franz-go/pkg/kfake v0.0.0-20250508175730-72e1646135e3
github.com/twmb/franz-go/pkg/kmsg v1.11.2
go.opentelemetry.io/otel v1.35.0
go.unistack.org/micro-codec-json/v4 v4.1.0
go.unistack.org/micro/v4 v4.1.13
) )
require ( require (
github.com/klauspost/compress v1.16.0 // indirect github.com/google/uuid v1.6.0 // indirect
github.com/pierrec/lz4/v4 v4.1.17 // indirect github.com/klauspost/compress v1.18.0 // indirect
github.com/matoous/go-nanoid v1.5.1 // indirect
github.com/pierrec/lz4/v4 v4.1.22 // indirect
github.com/spf13/cast v1.8.0 // indirect
go.unistack.org/micro-proto/v4 v4.1.0 // indirect
golang.org/x/crypto v0.38.0 // indirect
google.golang.org/protobuf v1.36.6 // indirect
) )

67
go.sum
View File

@@ -1,19 +1,50 @@
github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/klauspost/compress v1.16.0 h1:iULayQNOReoYUe+1qtKOqw9CwJv3aNQu8ivo7lw1HU4= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/pierrec/lz4/v4 v4.1.15/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/pierrec/lz4/v4 v4.1.17 h1:kV4Ip+/hUBC+8T6+2EgburRtkE9ef4nbY3f4dFhGjMc= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/silas/dag v0.0.0-20211117232152-9d50aa809f35/go.mod h1:7RTUFBdIRC9nZ7/3RyRNH1bdqIShrDejd1YbLwgPS+I= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/twmb/franz-go v1.12.1 h1:8lWT8q0spL40Nfw6eonJ8OoPGLvF9arvadRRmcSiu9Y= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/twmb/franz-go/pkg/kmsg v1.4.0 h1:tbp9hxU6m8qZhQTlpGiaIJOm4BXix5lsuEZ7K00dF0s= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
go.unistack.org/micro/v3 v3.10.23 h1:4BE7NwwyJbCWOfzjzztamBxJSgRHHW1uQtMGNDLHG3s= github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
golang.org/x/crypto v0.0.0-20220817201139-bc19a97f63c8/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= github.com/matoous/go-nanoid v1.5.1 h1:aCjdvTyO9LLnTIi0fgdXhOPPvOHjpXN6Ik9DaNjIct4=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= github.com/matoous/go-nanoid v1.5.1/go.mod h1:zyD2a71IubI24efhpvkJz+ZwfwagzgSO6UNiFsZKN7U=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= github.com/pierrec/lz4/v4 v4.1.22 h1:cKFw6uJDK+/gfw5BcDL0JL5aBsAFdsIT18eRtLj7VIU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= github.com/pierrec/lz4/v4 v4.1.22/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
github.com/spf13/cast v1.8.0 h1:gEN9K4b8Xws4EX0+a0reLmhq8moKn7ntRlQYgjPeCDk=
github.com/spf13/cast v1.8.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/twmb/franz-go v1.19.0 h1:FzBAPUeaip68X9cbLDesgQesa5zxKVaZMk+du98vj3c=
github.com/twmb/franz-go v1.19.0/go.mod h1:4kFJ5tmbbl7asgwAGVuyG1ZMx0NNpYk7EqflvWfPCpM=
github.com/twmb/franz-go v1.19.1 h1:cOhDFUkGvUFHSQ7UYW6bO77BJa2fYEk5mA2AX+1NIdE=
github.com/twmb/franz-go v1.19.1/go.mod h1:4kFJ5tmbbl7asgwAGVuyG1ZMx0NNpYk7EqflvWfPCpM=
github.com/twmb/franz-go/pkg/kadm v1.16.0 h1:STMs1t5lYR5mR974PSiwNzE5TvsosByTp+rKXLOhAjE=
github.com/twmb/franz-go/pkg/kadm v1.16.0/go.mod h1:MUdcUtnf9ph4SFBLLA/XxE29rvLhWYLM9Ygb8dfSCvw=
github.com/twmb/franz-go/pkg/kfake v0.0.0-20250508175730-72e1646135e3 h1:p24opKWPySAy8xSl8NqRgOv7Q+bX7kdrQirBVRJzQfo=
github.com/twmb/franz-go/pkg/kfake v0.0.0-20250508175730-72e1646135e3/go.mod h1:7uQs3Ae6HkWT1Y9elMbqtAcNFCI0y6+iS+Phw49L49U=
github.com/twmb/franz-go/pkg/kmsg v1.11.2 h1:hIw75FpwcAjgeyfIGFqivAvwC5uNIOWRGvQgZhH4mhg=
github.com/twmb/franz-go/pkg/kmsg v1.11.2/go.mod h1:CFfkkLysDNmukPYhGzuUcDtf46gQSqCZHMW1T4Z+wDE=
go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ=
go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y=
go.unistack.org/micro-codec-json/v4 v4.1.0 h1:iydeSkt3ee7IPU0dHHKlGN97lw+YFQasBk9rdv0woYA=
go.unistack.org/micro-codec-json/v4 v4.1.0/go.mod h1:aUg86elSlURSynTAetDAAXj/VzFDwwcg92QNrRzcvrM=
go.unistack.org/micro-proto/v4 v4.1.0 h1:qPwL2n/oqh9RE3RTTDgt28XK3QzV597VugQPaw9lKUk=
go.unistack.org/micro-proto/v4 v4.1.0/go.mod h1:ArmK7o+uFvxSY3dbJhKBBX4Pm1rhWdLEFf3LxBrMtec=
go.unistack.org/micro/v4 v4.1.13 h1:1IEQwiIwHdypZN4dWmsWN83Plq9bdkQ4U8aYZsT17s8=
go.unistack.org/micro/v4 v4.1.13/go.mod h1:xleO2M5Yxh4s6I+RUcLrEpUjobefh+71ctrdIfn7TUs=
golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8=
golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw=
google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

380
kgo.go
View File

@@ -1,30 +1,41 @@
// 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" "errors"
"fmt" "fmt"
"math/rand" "math/rand/v2"
"strings" "strings"
"sync" "sync"
"sync/atomic"
"time" "time"
"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"
"go.unistack.org/micro/v3/broker" "go.unistack.org/micro/v4/broker"
"go.unistack.org/micro/v3/metadata" "go.unistack.org/micro/v4/codec"
id "go.unistack.org/micro/v3/util/id" "go.unistack.org/micro/v4/logger"
mrand "go.unistack.org/micro/v3/util/rand" "go.unistack.org/micro/v4/metadata"
"go.unistack.org/micro/v4/options"
"go.unistack.org/micro/v4/semconv"
"go.unistack.org/micro/v4/tracer"
"go.unistack.org/micro/v4/util/id"
mrand "go.unistack.org/micro/v4/util/rand"
) )
var _ broker.Broker = (*Broker)(nil) var _ broker.Broker = (*Broker)(nil)
var messagePool = sync.Pool{
New: func() interface{} {
return &kgoMessage{}
},
}
var ErrLostMessage = errors.New("message not marked for offsets commit and will be lost in next iteration") var ErrLostMessage = errors.New("message not marked for offsets commit and will be lost in next iteration")
var DefaultRetryBackoffFn = func() func(int) time.Duration { var DefaultRetryBackoffFn = func() func(int) time.Duration {
var rngMu sync.Mutex var rngMu sync.Mutex
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
return func(fails int) time.Duration { return func(fails int) time.Duration {
const ( const (
min = 100 * time.Millisecond min = 100 * time.Millisecond
@@ -40,7 +51,7 @@ var DefaultRetryBackoffFn = func() func(int) time.Duration {
backoff := min * time.Duration(1<<(fails-1)) backoff := min * time.Duration(1<<(fails-1))
rngMu.Lock() rngMu.Lock()
jitter := 0.8 + 0.4*rng.Float64() jitter := 0.8 + 0.4*rand.Float64()
rngMu.Unlock() rngMu.Unlock()
backoff = time.Duration(float64(backoff) * jitter) backoff = time.Duration(float64(backoff) * jitter)
@@ -53,13 +64,30 @@ var DefaultRetryBackoffFn = func() func(int) time.Duration {
}() }()
type Broker struct { type Broker struct {
funcPublish broker.FuncPublish
funcSubscribe broker.FuncSubscribe
c *kgo.Client c *kgo.Client
connected *atomic.Uint32
kopts []kgo.Opt kopts []kgo.Opt
connected bool subs []*Subscriber
init bool
sync.RWMutex
opts broker.Options opts broker.Options
subs []*subscriber
sync.RWMutex
init bool
}
func (r *Broker) Live() bool {
return r.connected.Load() == 1
}
func (r *Broker) Ready() bool {
return r.connected.Load() == 1
}
func (r *Broker) Health() bool {
return r.connected.Load() == 1
} }
func (k *Broker) Address() string { func (k *Broker) Address() string {
@@ -70,63 +98,166 @@ func (k *Broker) Name() string {
return k.opts.Name return k.opts.Name
} }
func (k *Broker) connect(ctx context.Context, opts ...kgo.Opt) (*kgo.Client, error) { func (k *Broker) Client() *kgo.Client {
return k.c
}
type kgoMessage struct {
c codec.Codec
topic string
ctx context.Context
body []byte
hdr metadata.Metadata
opts broker.PublishOptions
ack bool
}
func (m *kgoMessage) Ack() error {
m.ack = true
return nil
}
func (m *kgoMessage) Body() []byte {
return m.body
}
func (m *kgoMessage) Header() metadata.Metadata {
return m.hdr
}
func (m *kgoMessage) Context() context.Context {
return m.ctx
}
func (m *kgoMessage) Topic() string {
return ""
}
func (m *kgoMessage) Unmarshal(dst interface{}, opts ...codec.Option) error {
return m.c.Unmarshal(m.body, dst)
}
func (b *Broker) newCodec(ct string) (codec.Codec, error) {
if idx := strings.IndexRune(ct, ';'); idx >= 0 {
ct = ct[:idx]
}
b.RLock()
c, ok := b.opts.Codecs[ct]
b.RUnlock()
if ok {
return c, nil
}
return nil, codec.ErrUnknownContentType
}
func (b *Broker) NewMessage(ctx context.Context, hdr metadata.Metadata, body interface{}, opts ...broker.PublishOption) (broker.Message, error) {
options := broker.NewPublishOptions(opts...)
if options.ContentType == "" {
options.ContentType = b.opts.ContentType
}
m := &kgoMessage{ctx: ctx, hdr: hdr, opts: options}
c, err := b.newCodec(m.opts.ContentType)
if err == nil {
m.body, err = c.Marshal(body)
}
if err != nil {
return nil, err
}
return m, nil
}
func (k *Broker) connect(ctx context.Context, opts ...kgo.Opt) (*kgo.Client, *hookTracer, error) {
var c *kgo.Client var c *kgo.Client
var err error var err error
sp, _ := tracer.SpanFromContext(ctx)
clientID := "kgo"
group := ""
if k.opts.Context != nil {
if id, ok := k.opts.Context.Value(clientIDKey{}).(string); ok {
clientID = id
}
if id, ok := k.opts.Context.Value(groupKey{}).(string); ok {
group = id
}
}
var fatalOnError bool
if k.opts.Context != nil {
if v, ok := k.opts.Context.Value(fatalOnErrorKey{}).(bool); ok && v {
fatalOnError = v
}
}
htracer := &hookTracer{group: group, clientID: clientID, tracer: k.opts.Tracer}
opts = append(opts,
kgo.WithHooks(&hookMeter{meter: k.opts.Meter}),
kgo.WithHooks(htracer),
kgo.WithHooks(&hookEvent{log: k.opts.Logger, fatalOnError: fatalOnError, connected: k.connected}),
)
select { select {
case <-ctx.Done(): case <-ctx.Done():
return nil, ctx.Err() if ctx.Err() != nil {
if sp != nil {
sp.SetStatus(tracer.SpanStatusError, ctx.Err().Error())
}
}
return nil, nil, ctx.Err()
default: default:
c, err = kgo.NewClient(opts...) c, err = kgo.NewClient(opts...)
if err == nil { if err == nil {
err = c.Ping(ctx) // check connectivity to cluster err = c.Ping(ctx) // check connectivity to cluster
} }
if err != nil { if err != nil {
return nil, err if sp != nil {
sp.SetStatus(tracer.SpanStatusError, err.Error())
} }
return nil, nil, err
}
k.connected.Store(1)
return c, htracer, nil
} }
return c, nil
} }
func (k *Broker) Connect(ctx context.Context) error { func (k *Broker) Connect(ctx context.Context) error {
k.RLock() if k.connected.Load() == 1 {
if k.connected {
k.RUnlock()
return nil return nil
} }
k.RUnlock()
nctx := k.opts.Context nctx := k.opts.Context
if ctx != nil { if ctx != nil {
nctx = ctx nctx = ctx
} }
c, err := k.connect(nctx, k.kopts...) c, _, err := k.connect(nctx, k.kopts...)
if err != nil { if err != nil {
return err return err
} }
k.Lock() k.Lock()
k.c = c k.c = c
k.connected = true k.connected.Store(1)
k.Unlock() k.Unlock()
return nil return nil
} }
func (k *Broker) 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()
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() k.Lock()
defer k.Unlock() defer k.Unlock()
@@ -148,7 +279,7 @@ func (k *Broker) Disconnect(ctx context.Context) error {
} }
} }
k.connected = false k.connected.Store(0)
return nil return nil
} }
@@ -156,6 +287,10 @@ func (k *Broker) Init(opts ...broker.Option) error {
k.Lock() k.Lock()
defer k.Unlock() defer k.Unlock()
if len(opts) == 0 && k.init {
return nil
}
for _, o := range opts { for _, o := range opts {
o(&k.opts) o(&k.opts)
} }
@@ -179,6 +314,20 @@ func (k *Broker) Init(opts ...broker.Option) error {
} }
} }
k.funcPublish = k.fnPublish
k.funcSubscribe = k.fnSubscribe
k.opts.Hooks.EachPrev(func(hook options.Hook) {
switch h := hook.(type) {
case broker.HookPublish:
k.funcPublish = h(k.funcPublish)
case broker.HookSubscribe:
k.funcSubscribe = h(k.funcSubscribe)
}
})
k.init = true
return nil return nil
} }
@@ -186,67 +335,88 @@ func (k *Broker) Options() broker.Options {
return k.opts return k.opts
} }
func (k *Broker) BatchPublish(ctx context.Context, msgs []*broker.Message, opts ...broker.PublishOption) error { func (b *Broker) Publish(ctx context.Context, topic string, messages ...broker.Message) error {
return k.publish(ctx, msgs, opts...) return b.funcPublish(ctx, topic, messages...)
} }
func (k *Broker) Publish(ctx context.Context, topic string, msg *broker.Message, opts ...broker.PublishOption) error { func (b *Broker) fnPublish(ctx context.Context, topic string, messages ...broker.Message) error {
msg.Header.Set(metadata.HeaderTopic, topic) return b.publish(ctx, topic, messages...)
return k.publish(ctx, []*broker.Message{msg}, opts...)
} }
func (k *Broker) publish(ctx context.Context, msgs []*broker.Message, opts ...broker.PublishOption) error { func (b *Broker) publish(ctx context.Context, topic string, messages ...broker.Message) error {
k.RLock() if b.connected.Load() == 0 {
ok := k.connected c, _, err := b.connect(ctx, b.kopts...)
k.RUnlock()
if !ok {
k.Lock()
c, err := k.connect(ctx, k.kopts...)
if err != nil { if err != nil {
k.Unlock()
return err return err
} }
k.c = c b.Lock()
k.connected = true b.c = c
k.Unlock() b.Unlock()
} }
options := broker.NewPublishOptions(opts...) records := make([]*kgo.Record, 0, len(messages))
records := make([]*kgo.Record, 0, len(msgs))
var errs []string var errs []string
var err error
var key []byte var key []byte
var promise func(*kgo.Record, error)
if options.Context != nil { for _, msg := range messages {
if k, ok := options.Context.Value(publishKey{}).([]byte); ok && k != nil {
if mctx := msg.Context(); mctx != nil {
if k, ok := mctx.Value(publishKey{}).([]byte); ok && k != nil {
key = k key = k
} }
if p, ok := mctx.Value(publishPromiseKey{}).(func(*kgo.Record, error)); ok && p != nil {
promise = p
}
} }
for _, msg := range msgs { rec := &kgo.Record{
rec := &kgo.Record{Context: ctx, Key: key} Context: ctx,
rec.Topic, _ = msg.Header.Get(metadata.HeaderTopic) Key: key,
if options.BodyOnly { Topic: topic,
rec.Value = msg.Body Value: msg.Body(),
} else if k.opts.Codec.String() == "noop" {
rec.Value = msg.Body
for k, v := range msg.Header {
rec.Headers = append(rec.Headers, kgo.RecordHeader{Key: k, Value: []byte(v)})
}
} else {
rec.Value, err = k.opts.Codec.Marshal(msg)
if err != nil {
return err
}
} }
b.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", rec.Topic, "topic", rec.Topic).Inc()
setHeaders(rec, msg.Header())
records = append(records, rec) records = append(records, rec)
} }
results := k.c.ProduceSync(ctx, records...) ts := time.Now()
if promise != nil {
for _, rec := range records {
b.c.Produce(ctx, rec, func(r *kgo.Record, err error) {
te := time.Since(ts)
b.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", rec.Topic, "topic", rec.Topic).Dec()
b.opts.Meter.Summary(semconv.PublishMessageLatencyMicroseconds, "endpoint", rec.Topic, "topic", rec.Topic).Update(te.Seconds())
b.opts.Meter.Histogram(semconv.PublishMessageDurationSeconds, "endpoint", rec.Topic, "topic", rec.Topic).Update(te.Seconds())
if err != nil {
b.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", rec.Topic, "topic", rec.Topic, "status", "failure").Inc()
} else {
b.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", rec.Topic, "topic", rec.Topic, "status", "success").Inc()
}
promise(r, err)
})
}
return nil
}
results := b.c.ProduceSync(ctx, records...)
te := time.Since(ts)
for _, result := range results { for _, result := range results {
b.opts.Meter.Summary(semconv.PublishMessageLatencyMicroseconds, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Update(te.Seconds())
b.opts.Meter.Histogram(semconv.PublishMessageDurationSeconds, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Update(te.Seconds())
b.opts.Meter.Counter(semconv.PublishMessageInflight, "endpoint", result.Record.Topic, "topic", result.Record.Topic).Dec()
if result.Err != nil { if result.Err != nil {
b.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 {
b.opts.Meter.Counter(semconv.PublishMessageTotal, "endpoint", result.Record.Topic, "topic", result.Record.Topic, "status", "success").Inc()
} }
} }
@@ -257,13 +427,42 @@ func (k *Broker) publish(ctx context.Context, msgs []*broker.Message, opts ...br
return nil return nil
} }
func (k *Broker) BatchSubscribe(ctx context.Context, topic string, handler broker.BatchHandler, opts ...broker.SubscribeOption) (broker.Subscriber, error) { func (k *Broker) TopicExists(ctx context.Context, topic string) error {
return nil, nil mdreq := kmsg.NewMetadataRequest()
mdreq.Topics = []kmsg.MetadataRequestTopic{
{Topic: &topic},
}
mdrsp, err := mdreq.RequestWith(ctx, k.c)
if err != nil {
return err
} else if mdrsp.Topics[0].ErrorCode != 0 {
return fmt.Errorf("topic %s not exists or permission error", topic)
}
return nil
} }
func (k *Broker) Subscribe(ctx context.Context, topic string, handler broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) { func (b *Broker) Subscribe(ctx context.Context, topic string, handler interface{}, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
return b.funcSubscribe(ctx, topic, handler, opts...)
}
func (b *Broker) fnSubscribe(ctx context.Context, topic string, handler interface{}, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
if err := broker.IsValidHandler(handler); err != nil {
return nil, err
}
options := broker.NewSubscribeOptions(opts...) options := broker.NewSubscribeOptions(opts...)
switch handler.(type) {
default:
return nil, broker.ErrInvalidHandler
case func(broker.Message) error:
break
case func([]broker.Message) error:
break
}
if options.Group == "" { if options.Group == "" {
uid, err := id.New() uid, err := id.New()
if err != nil { if err != nil {
@@ -273,22 +472,37 @@ func (k *Broker) Subscribe(ctx context.Context, topic string, handler broker.Han
} }
commitInterval := DefaultCommitInterval commitInterval := DefaultCommitInterval
if k.opts.Context != nil { if b.opts.Context != nil {
if v, ok := k.opts.Context.Value(commitIntervalKey{}).(time.Duration); ok && v > 0 { if v, ok := b.opts.Context.Value(commitIntervalKey{}).(time.Duration); ok && v > 0 {
commitInterval = v commitInterval = v
} }
} }
sub := &subscriber{ var fatalOnError bool
if b.opts.Context != nil {
if v, ok := b.opts.Context.Value(fatalOnErrorKey{}).(bool); ok && v {
fatalOnError = v
}
}
if options.Context != nil {
if v, ok := options.Context.Value(fatalOnErrorKey{}).(bool); ok && v {
fatalOnError = v
}
}
sub := &Subscriber{
topic: topic, topic: topic,
opts: options, opts: options,
handler: handler, handler: handler,
kopts: k.opts, kopts: b.opts,
consumers: make(map[tp]*consumer), consumers: make(map[tp]*consumer),
done: make(chan struct{}), done: make(chan struct{}),
fatalOnError: fatalOnError,
connected: b.connected,
} }
kopts := append(k.kopts, kopts := append(b.kopts,
kgo.ConsumerGroup(options.Group), kgo.ConsumerGroup(options.Group),
kgo.ConsumeTopics(topic), kgo.ConsumeTopics(topic),
kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()), kgo.ConsumeResetOffset(kgo.NewOffset().AtStart()),
@@ -296,7 +510,9 @@ func (k *Broker) Subscribe(ctx context.Context, topic string, handler broker.Han
kgo.AutoCommitInterval(commitInterval), kgo.AutoCommitInterval(commitInterval),
kgo.OnPartitionsAssigned(sub.assigned), kgo.OnPartitionsAssigned(sub.assigned),
kgo.OnPartitionsRevoked(sub.revoked), kgo.OnPartitionsRevoked(sub.revoked),
kgo.StopProducerOnDataLossDetected(),
kgo.OnPartitionsLost(sub.lost), kgo.OnPartitionsLost(sub.lost),
kgo.AutoCommitCallback(sub.autocommit),
kgo.AutoCommitMarks(), kgo.AutoCommitMarks(),
) )
@@ -306,7 +522,7 @@ func (k *Broker) Subscribe(ctx context.Context, topic string, handler broker.Han
} }
} }
c, err := k.connect(ctx, kopts...) c, htracer, err := b.connect(ctx, kopts...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -324,11 +540,14 @@ func (k *Broker) Subscribe(ctx context.Context, topic string, handler broker.Han
} }
sub.c = c sub.c = c
sub.htracer = htracer
go sub.poll(ctx) go sub.poll(ctx)
k.Lock() b.Lock()
k.subs = append(k.subs, sub) b.subs = append(b.subs, sub)
k.Unlock() b.Unlock()
return sub, nil return sub, nil
} }
@@ -337,7 +556,6 @@ func (k *Broker) String() string {
} }
func NewBroker(opts ...broker.Option) *Broker { func NewBroker(opts ...broker.Option) *Broker {
rand.Seed(time.Now().Unix())
options := broker.NewOptions(opts...) options := broker.NewOptions(opts...)
kaddrs := options.Addrs kaddrs := options.Addrs
@@ -350,14 +568,13 @@ func NewBroker(opts ...broker.Option) *Broker {
kgo.DialTimeout(3 * time.Second), 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.WithLogger(kgo.BasicLogger(os.Stderr, kgo.LogLevelDebug, func() string { return time.Now().Format(time.StampMilli) })),
kgo.WithHooks(&metrics{meter: options.Meter}),
kgo.SeedBrokers(kaddrs...), kgo.SeedBrokers(kaddrs...),
kgo.RetryBackoffFn(DefaultRetryBackoffFn), kgo.RetryBackoffFn(DefaultRetryBackoffFn),
kgo.BlockRebalanceOnPoll(), kgo.BlockRebalanceOnPoll(),
kgo.Balancers(kgo.CooperativeStickyBalancer()), kgo.Balancers(kgo.CooperativeStickyBalancer()),
kgo.FetchIsolationLevel(kgo.ReadUncommitted()), kgo.FetchIsolationLevel(kgo.ReadUncommitted()),
kgo.UnknownTopicRetries(1),
} }
if options.Context != nil { if options.Context != nil {
@@ -367,6 +584,7 @@ func NewBroker(opts ...broker.Option) *Broker {
} }
return &Broker{ return &Broker{
connected: &atomic.Uint32{},
opts: options, opts: options,
kopts: kopts, kopts: kopts,
} }

View File

@@ -2,39 +2,140 @@ package kgo_test
import ( import (
"context" "context"
"fmt"
"os"
"strings"
"sync/atomic" "sync/atomic"
"testing" "testing"
"time" "time"
"github.com/twmb/franz-go/pkg/kfake"
kg "github.com/twmb/franz-go/pkg/kgo" kg "github.com/twmb/franz-go/pkg/kgo"
kgo "go.unistack.org/micro-broker-kgo/v3" kgo "go.unistack.org/micro-broker-kgo/v4"
"go.unistack.org/micro/v3/broker" "go.unistack.org/micro/v4/broker"
"go.unistack.org/micro/v3/logger" "go.unistack.org/micro/v4/codec"
"go.unistack.org/micro/v3/metadata" "go.unistack.org/micro/v4/logger"
"go.unistack.org/micro/v4/logger/slog"
"go.unistack.org/micro/v4/metadata"
) )
var ( var (
msgcnt = int64(12000000) msgcnt = int64(1200)
group = "38" group = "38"
prefill = false prefill = true
loglevel = logger.InfoLevel loglevel = logger.ErrorLevel
cluster *kfake.Cluster
) )
var bm = &broker.Message{ func TestMain(m *testing.M) {
Header: map[string]string{"hkey": "hval", metadata.HeaderTopic: "test"}, cluster = kfake.MustCluster(
Body: []byte(`"body"`), kfake.AllowAutoTopicCreation(),
)
defer cluster.Close()
m.Run()
}
func TestFail(t *testing.T) {
logger.DefaultLogger = slog.NewLogger()
if err := logger.DefaultLogger.Init(logger.WithLevel(loglevel)); err != nil {
t.Fatal(err)
}
ctx := context.Background()
b := kgo.NewBroker(
broker.ContentType("application/octet-stream"),
broker.Codec("application/octet-stream", codec.NewCodec()),
broker.Addrs(cluster.ListenAddrs()...),
kgo.CommitInterval(5*time.Second),
kgo.Options(
kg.ClientID("test"),
kg.FetchMaxBytes(10*1024*1024),
kg.AllowAutoTopicCreation(),
),
)
t.Logf("broker init")
if err := b.Init(); err != nil {
t.Fatal(err)
}
t.Logf("broker connect")
if err := b.Connect(ctx); err != nil {
t.Fatal(err)
}
defer func() {
t.Logf("broker disconnect")
if err := b.Disconnect(ctx); err != nil {
t.Fatal(err)
}
}()
t.Logf("broker health %v", b.Health())
msgs := make([]broker.Message, 0, msgcnt)
for i := int64(0); i < msgcnt; i++ {
m, err := b.NewMessage(ctx, metadata.Pairs("hkey", "hval"), []byte(`test`))
if err != nil {
t.Fatal(err)
}
msgs = append(msgs, m)
}
go func() {
for _, msg := range msgs {
// t.Logf("broker publish")
if err := b.Publish(ctx, "test", msg); err != nil {
t.Fatal(err)
}
}
}()
// t.Skip()
idx := int64(0)
fn := func(msg broker.Message) error {
atomic.AddInt64(&idx, 1)
time.Sleep(100 * time.Millisecond)
// t.Logf("ack")
return msg.Ack()
}
sub, err := b.Subscribe(ctx, "test", fn,
broker.SubscribeAutoAck(true),
broker.SubscribeGroup(group),
broker.SubscribeBodyOnly(true))
if err != nil {
t.Fatal(err)
}
defer func() {
if err := sub.Unsubscribe(ctx); err != nil {
t.Fatal(err)
}
}()
for {
t.Logf("health check")
if !b.Health() {
t.Logf("health works")
break
}
t.Logf("health sleep")
time.Sleep(100 * time.Millisecond)
if err := b.Disconnect(ctx); err != nil {
t.Fatal(err)
}
}
} }
func TestConnect(t *testing.T) { func TestConnect(t *testing.T) {
var addrs []string
ctx := context.TODO() ctx := context.TODO()
b := kgo.NewBroker( b := kgo.NewBroker(
broker.Addrs(addrs...), broker.ContentType("application/octet-stream"),
broker.Codec("application/octet-stream", codec.NewCodec()),
broker.Addrs(cluster.ListenAddrs()...),
kgo.CommitInterval(5*time.Second), kgo.CommitInterval(5*time.Second),
kgo.Options(kg.ClientID("test"), kg.FetchMaxBytes(10*1024*1024)), kgo.Options(
kg.ClientID("test"),
kg.FetchMaxBytes(10*1024*1024),
kg.AllowAutoTopicCreation(),
),
) )
if err := b.Init(); err != nil { if err := b.Init(); err != nil {
t.Fatal(err) t.Fatal(err)
@@ -46,27 +147,23 @@ func TestConnect(t *testing.T) {
} }
func TestPubSub(t *testing.T) { func TestPubSub(t *testing.T) {
if tr := os.Getenv("INTEGRATION_TESTS"); len(tr) > 0 { if err := logger.DefaultLogger.Init(logger.WithLevel(loglevel)); err != nil {
t.Skip()
}
if err := logger.DefaultLogger.Init(logger.WithLevel(loglevel), logger.WithCallerSkipCount(3)); err != nil {
t.Fatal(err) t.Fatal(err)
} }
ctx := context.Background() ctx := context.Background()
var addrs []string
if addr := os.Getenv("BROKER_ADDRS"); len(addr) == 0 {
addrs = []string{"127.0.0.1:29091", "127.0.0.2:29092", "127.0.0.3:29093"}
} else {
addrs = strings.Split(addr, ",")
}
b := kgo.NewBroker( b := kgo.NewBroker(
broker.Addrs(addrs...), broker.ContentType("application/octet-stream"),
broker.Codec("application/octet-stream", codec.NewCodec()),
broker.Addrs(cluster.ListenAddrs()...),
kgo.CommitInterval(5*time.Second), kgo.CommitInterval(5*time.Second),
kgo.Options(kg.ClientID("test"), kg.FetchMaxBytes(10*1024*1024)), kgo.Options(
kg.ClientID("test"),
kg.FetchMaxBytes(10*1024*1024),
kg.AllowAutoTopicCreation(),
),
) )
if err := b.Init(); err != nil { if err := b.Init(); err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -81,19 +178,20 @@ func TestPubSub(t *testing.T) {
} }
}() }()
if prefill { if prefill {
msgs := make([]*broker.Message, 0, msgcnt) msgs := make([]broker.Message, 0, msgcnt)
for i := int64(0); i < msgcnt; i++ { for i := int64(0); i < msgcnt; i++ {
msgs = append(msgs, bm) m, _ := b.NewMessage(ctx, metadata.Pairs("hkey", "hval"), []byte(`test`))
msgs = append(msgs, m)
} }
if err := b.BatchPublish(ctx, msgs); err != nil { if err := b.Publish(ctx, "test", msgs...); err != nil {
t.Fatal(err) t.Fatal(err)
} }
// t.Skip() // t.Skip()
} }
done := make(chan bool, 1) done := make(chan bool, 1)
idx := int64(0) idx := int64(0)
fn := func(msg broker.Event) error { fn := func(msg broker.Message) error {
atomic.AddInt64(&idx, 1) atomic.AddInt64(&idx, 1)
// time.Sleep(200 * time.Millisecond) // time.Sleep(200 * time.Millisecond)
return msg.Ack() return msg.Ack()
@@ -124,7 +222,7 @@ func TestPubSub(t *testing.T) {
if prc := atomic.LoadInt64(&idx); prc == msgcnt { if prc := atomic.LoadInt64(&idx); prc == msgcnt {
close(done) close(done)
} else { } else {
fmt.Printf("processed %v\n", prc) t.Logf("processed %v\n", prc)
} }
case <-ticker.C: case <-ticker.C:
close(done) close(done)

View File

@@ -2,10 +2,9 @@ package kgo
import ( import (
"context" "context"
"fmt"
"github.com/twmb/franz-go/pkg/kgo" "github.com/twmb/franz-go/pkg/kgo"
"go.unistack.org/micro/v3/logger" "go.unistack.org/micro/v4/logger"
) )
type mlogger struct { type mlogger struct {
@@ -29,15 +28,8 @@ func (l *mlogger) Log(lvl kgo.LogLevel, msg string, args ...interface{}) {
default: default:
return return
} }
if len(args) > 0 {
fields := make(map[string]interface{}, int(len(args)/2)) l.l.Log(l.ctx, mlvl, msg, args...)
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)
} else {
l.l.Log(l.ctx, mlvl, msg)
}
} }
func (l *mlogger) Level() kgo.LogLevel { func (l *mlogger) Level() kgo.LogLevel {

View File

@@ -6,22 +6,29 @@ import (
"time" "time"
"github.com/twmb/franz-go/pkg/kgo" "github.com/twmb/franz-go/pkg/kgo"
"go.unistack.org/micro/v3/meter" "go.unistack.org/micro/v4/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(_ 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)

View File

@@ -5,12 +5,20 @@ import (
"time" "time"
"github.com/twmb/franz-go/pkg/kgo" "github.com/twmb/franz-go/pkg/kgo"
"go.unistack.org/micro/v3/broker" "go.unistack.org/micro/v4/broker"
"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{}
@@ -26,11 +34,6 @@ func PublishKey(key []byte) broker.PublishOption {
return broker.SetPublishOption(publishKey{}, key) return broker.SetPublishOption(publishKey{}, key)
} }
// ClientPublishKey set the kafka message key (client option)
func ClientPublishKey(key []byte) client.PublishOption {
return client.SetPublishOption(publishKey{}, key)
}
type optionsKey struct{} type optionsKey struct{}
// Options pass additional options to broker // Options pass additional options to broker
@@ -63,6 +66,24 @@ func SubscribeOptions(opts ...kgo.Opt) broker.SubscribeOption {
} }
} }
type fatalOnErrorKey struct{}
func FatalOnError(b bool) broker.Option {
return broker.SetOption(fatalOnErrorKey{}, b)
}
type clientIDKey struct{}
func ClientID(id string) broker.Option {
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
@@ -70,11 +91,21 @@ func CommitInterval(td time.Duration) broker.Option {
return broker.SetOption(commitIntervalKey{}, td) return broker.SetOption(commitIntervalKey{}, td)
} }
var DefaultSubscribeMaxInflight = 10
type subscribeMaxInflightKey struct{} type subscribeMaxInflightKey struct{}
// SubscribeMaxInFlight max queued messages // SubscribeMaxInFlight max queued messages
func SubscribeMaxInFlight(n int) broker.SubscribeOption { func SubscribeMaxInFlight(n int) broker.SubscribeOption {
return broker.SetSubscribeOption(subscribeMaxInflightKey{}, n) return broker.SetSubscribeOption(subscribeMaxInflightKey{}, n)
} }
// SubscribeMaxInFlight max queued messages
func SubscribeFatalOnError(b bool) broker.SubscribeOption {
return broker.SetSubscribeOption(fatalOnErrorKey{}, b)
}
type publishPromiseKey struct{}
// PublishPromise set the kafka promise func for Produce
func PublishPromise(fn func(*kgo.Record, error)) broker.PublishOption {
return broker.SetPublishOption(publishPromiseKey{}, fn)
}

View File

@@ -2,12 +2,20 @@ package kgo
import ( import (
"context" "context"
"fmt"
"strconv"
"sync" "sync"
"sync/atomic"
"time"
"github.com/twmb/franz-go/pkg/kadm"
"github.com/twmb/franz-go/pkg/kgo" "github.com/twmb/franz-go/pkg/kgo"
"go.unistack.org/micro/v3/broker" "github.com/twmb/franz-go/pkg/kmsg"
"go.unistack.org/micro/v3/logger" "go.unistack.org/micro/v4/broker"
"go.unistack.org/micro/v3/metadata" "go.unistack.org/micro/v4/logger"
"go.unistack.org/micro/v4/metadata"
"go.unistack.org/micro/v4/semconv"
"go.unistack.org/micro/v4/tracer"
) )
type tp struct { type tp struct {
@@ -16,45 +24,53 @@ type tp struct {
} }
type consumer struct { type consumer struct {
c *kgo.Client
topic string topic string
partition int32 c *kgo.Client
opts broker.SubscribeOptions htracer *hookTracer
kopts broker.Options
handler broker.Handler
quit chan struct{} quit chan struct{}
done chan struct{} done chan struct{}
recs chan kgo.FetchTopicPartition recs chan kgo.FetchTopicPartition
}
type subscriber struct {
c *kgo.Client
topic string
opts broker.SubscribeOptions
kopts broker.Options kopts broker.Options
handler broker.Handler partition int32
closed bool opts broker.SubscribeOptions
done chan struct{} handler interface{}
consumers map[tp]*consumer connected *atomic.Uint32
sync.RWMutex
} }
func (s *subscriber) Options() broker.SubscribeOptions { type Subscriber struct {
consumers map[tp]*consumer
c *kgo.Client
htracer *hookTracer
topic string
handler interface{}
done chan struct{}
kopts broker.Options
opts broker.SubscribeOptions
connected *atomic.Uint32
sync.RWMutex
closed bool
fatalOnError bool
}
func (s *Subscriber) Client() *kgo.Client {
return s.c
}
func (s *Subscriber) Options() broker.SubscribeOptions {
return s.opts return s.opts
} }
func (s *subscriber) Topic() string { func (s *Subscriber) Topic() string {
return s.topic return s.topic
} }
func (s *subscriber) Unsubscribe(ctx context.Context) error { func (s *Subscriber) Unsubscribe(ctx context.Context) error {
if s.closed { if s.closed {
return nil return nil
} }
select {
// case <-ctx.Done():
// return ctx.Err()
default:
s.c.PauseFetchTopics(s.topic) s.c.PauseFetchTopics(s.topic)
s.c.CloseAllowingRebalance() s.c.CloseAllowingRebalance()
kc := make(map[string][]int32) kc := make(map[string][]int32)
@@ -64,17 +80,53 @@ func (s *subscriber) Unsubscribe(ctx context.Context) error {
s.killConsumers(ctx, kc) s.killConsumers(ctx, kc)
close(s.done) close(s.done)
s.closed = true s.closed = true
} s.c.ResumeFetchTopics(s.topic)
return nil return nil
} }
func (s *subscriber) poll(ctx context.Context) { func (s *Subscriber) poll(ctx context.Context) {
maxInflight := DefaultSubscribeMaxInflight maxInflight := DefaultSubscribeMaxInflight
if s.opts.Context != nil { if s.opts.Context != nil {
if n, ok := s.opts.Context.Value(subscribeMaxInflightKey{}).(int); n > 0 && ok { if n, ok := s.opts.Context.Value(subscribeMaxInflightKey{}).(int); n > 0 && ok {
maxInflight = n 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))).Set(uint64(l.Lag))
}
s.Unlock()
}
}
}()
for { for {
select { select {
case <-ctx.Done(): case <-ctx.Done():
@@ -89,77 +141,108 @@ func (s *subscriber) poll(ctx context.Context) {
return return
} }
fetches.EachError(func(t string, p int32, err error) { fetches.EachError(func(t string, p int32, err error) {
s.kopts.Logger.Fatalf(ctx, "[kgo] fetch topic %s partition %d err: %v", t, p, err) s.kopts.Logger.Fatal(ctx, fmt.Sprintf("[kgo] fetch topic %s partition %d error", t, p), err)
}) })
fetches.EachPartition(func(p kgo.FetchTopicPartition) { fetches.EachPartition(func(p kgo.FetchTopicPartition) {
tp := tp{p.Topic, p.Partition} tps := tp{p.Topic, p.Partition}
s.consumers[tp].recs <- p s.Lock()
c := s.consumers[tps]
s.Unlock()
if c != nil {
c.recs <- p
}
}) })
s.c.AllowRebalance() s.c.AllowRebalance()
} }
} }
} }
func (s *subscriber) killConsumers(ctx context.Context, lost map[string][]int32) { func (s *Subscriber) killConsumers(ctx context.Context, lost map[string][]int32) {
var wg sync.WaitGroup var wg sync.WaitGroup
defer wg.Wait() defer wg.Wait()
for topic, partitions := range lost { for topic, partitions := range lost {
for _, partition := range partitions { for _, partition := range partitions {
tp := tp{topic, partition} tps := tp{topic, partition}
pc := s.consumers[tp] s.Lock()
delete(s.consumers, tp) pc, ok := s.consumers[tps]
s.Unlock()
if !ok {
continue
}
s.Lock()
delete(s.consumers, tps)
s.Unlock()
close(pc.quit) close(pc.quit)
s.kopts.Logger.Debugf(ctx, "[kgo] waiting for work to finish topic %s partition %d", topic, partition) if s.kopts.Logger.V(logger.DebugLevel) {
s.kopts.Logger.Debug(ctx, fmt.Sprintf("[kgo] waiting for work to finish topic %s partition %d", topic, partition))
}
wg.Add(1) wg.Add(1)
go func() { <-pc.done; wg.Done() }() go func() { <-pc.done; wg.Done() }()
} }
} }
} }
func (s *subscriber) lost(ctx context.Context, _ *kgo.Client, lost map[string][]int32) { func (s *Subscriber) autocommit(_ *kgo.Client, _ *kmsg.OffsetCommitRequest, _ *kmsg.OffsetCommitResponse, err error) {
s.kopts.Logger.Debugf(ctx, "[kgo] lost %#+v", lost) if err != nil {
s.killConsumers(ctx, lost) // s.connected.Store(0)
} if s.fatalOnError {
s.kopts.Logger.Fatal(context.TODO(), "kgo.AutoCommitCallback error", err)
func (s *subscriber) revoked(ctx context.Context, c *kgo.Client, revoked map[string][]int32) { }
s.kopts.Logger.Debugf(ctx, "[kgo] revoked %#+v", revoked)
s.killConsumers(ctx, revoked)
if err := c.CommitMarkedOffsets(ctx); err != nil {
s.kopts.Logger.Errorf(ctx, "[kgo] revoked CommitMarkedOffsets err: %v", err)
} }
} }
func (s *subscriber) assigned(_ context.Context, c *kgo.Client, assigned map[string][]int32) { func (s *Subscriber) lost(ctx context.Context, _ *kgo.Client, lost map[string][]int32) {
if s.kopts.Logger.V(logger.ErrorLevel) {
s.kopts.Logger.Error(ctx, fmt.Sprintf("[kgo] lost %#+v", lost))
}
s.killConsumers(ctx, lost)
// s.connected.Store(0)
}
func (s *Subscriber) revoked(ctx context.Context, c *kgo.Client, revoked map[string][]int32) {
if s.kopts.Logger.V(logger.DebugLevel) {
s.kopts.Logger.Debug(ctx, fmt.Sprintf("[kgo] revoked %#+v", revoked))
}
s.killConsumers(ctx, revoked)
if err := c.CommitMarkedOffsets(ctx); err != nil {
s.kopts.Logger.Error(ctx, "[kgo] revoked CommitMarkedOffsets error", err)
// s.connected.Store(0)
}
}
func (s *Subscriber) assigned(_ context.Context, c *kgo.Client, assigned map[string][]int32) {
for topic, partitions := range assigned { for topic, partitions := range assigned {
for _, partition := range partitions { for _, partition := range partitions {
pc := &consumer{ pc := &consumer{
c: c, c: c,
topic: topic, topic: topic,
partition: partition, partition: partition,
htracer: s.htracer,
quit: make(chan struct{}), quit: make(chan struct{}),
done: make(chan struct{}), done: make(chan struct{}),
recs: make(chan kgo.FetchTopicPartition, 4), recs: make(chan kgo.FetchTopicPartition, 100),
handler: s.handler, handler: s.handler,
kopts: s.kopts, kopts: s.kopts,
opts: s.opts, opts: s.opts,
connected: s.connected,
} }
s.Lock()
s.consumers[tp{topic, partition}] = pc s.consumers[tp{topic, partition}] = pc
s.Unlock()
go pc.consume() go pc.consume()
} }
} }
} }
func (pc *consumer) consume() { func (pc *consumer) consume() {
defer close(pc.done) var err error
pc.kopts.Logger.Debugf(pc.kopts.Context, "starting, topic %s partition %d", pc.topic, pc.partition)
defer pc.kopts.Logger.Debugf(pc.kopts.Context, "killing, topic %s partition %d", pc.topic, pc.partition)
eh := pc.kopts.ErrorHandler defer close(pc.done)
if pc.opts.ErrorHandler != nil { if pc.kopts.Logger.V(logger.DebugLevel) {
eh = pc.opts.ErrorHandler 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))
} }
for { for {
@@ -168,66 +251,52 @@ func (pc *consumer) consume() {
return return
case p := <-pc.recs: case p := <-pc.recs:
for _, record := range p.Records { for _, record := range p.Records {
p := eventPool.Get().(*event) ctx, sp := pc.htracer.WithProcessSpan(record)
p.msg.Header = nil ts := time.Now()
p.msg.Body = nil pc.kopts.Meter.Counter(semconv.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Inc()
p := messagePool.Get().(*kgoMessage)
p.body = record.Value
p.topic = record.Topic p.topic = record.Topic
p.err = nil
p.ack = false p.ack = false
if pc.kopts.Codec.String() == "noop" { p.hdr = metadata.New(len(record.Headers))
p.msg.Header = metadata.New(len(record.Headers)) p.ctx = ctx
for _, hdr := range record.Headers { for _, hdr := range record.Headers {
p.msg.Header.Set(hdr.Key, string(hdr.Value)) p.hdr.Set(hdr.Key, string(hdr.Value))
} }
p.msg.Body = record.Value
} else if pc.opts.BodyOnly { switch h := pc.handler.(type) {
p.msg.Body = record.Value case func(broker.Message) error:
} else { err = h(p)
if err := pc.kopts.Codec.Unmarshal(record.Value, p.msg); err != nil { case func([]broker.Message) error:
p.err = err err = h([]broker.Message{p})
p.msg.Body = record.Value
if eh != nil {
_ = eh(p)
if p.ack {
pc.c.MarkCommitRecords(record)
} else {
eventPool.Put(p)
pc.kopts.Logger.Infof(pc.kopts.Context, "[kgo] ErrLostMessage wtf?")
return
} }
eventPool.Put(p)
continue pc.kopts.Meter.Counter(semconv.SubscribeMessageInflight, "endpoint", record.Topic, "topic", record.Topic).Dec()
} else { if err != nil {
if pc.kopts.Logger.V(logger.ErrorLevel) { sp.SetStatus(tracer.SpanStatusError, err.Error())
pc.kopts.Logger.Errorf(pc.kopts.Context, "[kgo]: failed to unmarshal: %v", err) pc.kopts.Meter.Counter(semconv.SubscribeMessageTotal, "endpoint", record.Topic, "topic", record.Topic, "status", "failure").Inc()
} } else if pc.opts.AutoAck {
}
eventPool.Put(p)
pc.kopts.Logger.Infof(pc.kopts.Context, "[kgo] Unmarshal err not handled wtf?")
return
}
}
err := pc.handler(p)
if err == nil && pc.opts.AutoAck {
p.ack = true p.ack = true
} else if err != nil {
p.err = err
if eh != nil {
_ = eh(p)
} else {
if pc.kopts.Logger.V(logger.ErrorLevel) {
pc.kopts.Logger.Errorf(pc.kopts.Context, "[kgo]: subscriber error: %v", err)
} }
}
} te := time.Since(ts)
if p.ack { pc.kopts.Meter.Summary(semconv.SubscribeMessageLatencyMicroseconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds())
eventPool.Put(p) pc.kopts.Meter.Histogram(semconv.SubscribeMessageDurationSeconds, "endpoint", record.Topic, "topic", record.Topic).Update(te.Seconds())
ack := p.ack
messagePool.Put(p)
if ack {
pc.c.MarkCommitRecords(record) pc.c.MarkCommitRecords(record)
} else { } else {
eventPool.Put(p) sp.Finish()
pc.kopts.Logger.Fatalf(pc.kopts.Context, "[kgo] ErrLostMessage wtf?") // pc.connected.Store(0)
pc.kopts.Logger.Fatal(pc.kopts.Context, "[kgo] message not commited")
return return
} }
sp.Finish()
} }
} }
} }

204
tracer.go Normal file
View 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/v4/metadata"
"go.unistack.org/micro/v4/tracer"
)
type hookTracer struct {
tracer tracer.Tracer
clientID string
group string
}
var messagingSystem = semconv.MessagingSystemKey.String("kafka")
var (
_ kgo.HookProduceRecordBuffered = (*hookTracer)(nil)
_ kgo.HookProduceRecordUnbuffered = (*hookTracer)(nil)
_ kgo.HookFetchRecordBuffered = (*hookTracer)(nil)
_ kgo.HookFetchRecordUnbuffered = (*hookTracer)(nil)
)
// OnProduceRecordBuffered starts a new span for the "publish" operation on a
// buffered record.
//
// It sets span options and injects the span context into record and updates
// the record's context, so it can be ended in the OnProduceRecordUnbuffered
// hook.
func (m *hookTracer) OnProduceRecordBuffered(r *kgo.Record) {
// Set up span options.
attrs := []interface{}{
messagingSystem,
semconv.MessagingDestinationKindTopic,
semconv.MessagingDestinationName(r.Topic),
semconv.MessagingOperationPublish,
}
attrs = maybeKeyAttr(attrs, r)
if m.clientID != "" {
attrs = append(attrs, semconv.MessagingKafkaClientIDKey.String(m.clientID))
}
opts := []tracer.SpanOption{
tracer.WithSpanLabels(attrs...),
tracer.WithSpanKind(tracer.SpanKindProducer),
}
if r.Context == nil {
r.Context = context.Background()
}
omd, ok := metadata.FromOutgoingContext(r.Context)
if !ok {
omd = metadata.New(len(r.Headers))
}
md := metadata.Copy(omd)
for _, h := range r.Headers {
md.Set(h.Key, string(h.Value))
}
if !ok {
r.Context, _ = m.tracer.Start(metadata.NewOutgoingContext(r.Context, md), "sdk.broker", opts...)
} else {
r.Context, _ = m.tracer.Start(r.Context, "sdk.broker", opts...)
}
setHeaders(r, omd, metadata.HeaderContentType)
}
// OnProduceRecordUnbuffered continues and ends the "publish" span for an
// unbuffered record.
//
// It sets attributes with values unset when producing and records any error
// that occurred during the publish operation.
func (m *hookTracer) OnProduceRecordUnbuffered(r *kgo.Record, err error) {
if 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, metadata.HeaderContentType)
}
// 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))
}