Compare commits

...
3 Commits
Author SHA1 Message Date
Chris LuandClaude Opus 5.5 43556b3a3c mq: publishers re-look up and resend when a partition's leader changes (#13195)
* mq client: dial brokers with the publisher's dial option

The publisher dialed every broker with insecure credentials, and the
per-partition connection added the configured option on top of them, so
a publisher could not reach a broker that requires TLS. That connection
was also never closed. PublisherConfiguration now takes the dial option,
insecure only when none is given, the agent passes its own, and the
partition connection is closed when its publish job ends.

* mq client: resend unacked messages when a partition's publish stream fails

A publisher sent each message once and kept no record of it. Acks were
only logged, a broker error on the stream was written to a field nobody
read, and the scheduler's wait loop broke out of its select instead of
the loop, so after the first stream failure it never looked the
partitions up again. Losing a partition leader silently dropped every
unacked message and stopped that partition for good.

Each partition now keeps its queue and the messages it sent but has not
had acked across streams. When a stream fails, or the broker answers
with an error or error code, the job ends, the scheduler looks the
topic up again with a short backoff, and the replacement stream resends
the unacked messages in order before draining the queue. Acks remove
messages up to the acked timestamp, so timestamps are made strictly
increasing per publisher. A partition holds at most 1024 queued or
unacked messages, and Publish blocks beyond that instead of growing
without bound. FinishPublish and Shutdown stop the input, Publish then
fails, and Shutdown returns once everything queued is acked.

* mq client: bound how long a closed publisher keeps resending

Once its input is closed, a publisher kept retrying a partition until
every message was acked, so Shutdown never returned while no broker
could take the partition, and a publisher that was only finished kept
looking the topic up forever. Resending now stops a minute after
FinishPublish or Shutdown, the open streams are cancelled, and Shutdown
reports how many messages were left unacknowledged.

* mq/kafka: replace a publish session whose call failed or was cancelled

PublishRecord ran Send and Recv in goroutines and returned when the
request context ended, leaving them on the stream. A leftover Recv then
took the ack meant for the next call on that partition, so acks and
offsets drifted apart, and a session whose stream had failed or whose
broker answered with an error stayed cached until the topic was
deleted. A call that fails, is cancelled, or gets an error response now
drops its session and cancels the stream, so the next call opens a
fresh one. PublishRecordValue shares the same path.

* mq/kafka: publish to the partition's current leader

The gateway opened every publish stream on the one broker it was
configured with, and a broker answers a publish for a partition it does
not lead with not-leader, so with more than one broker most partitions
could not be produced to, and none could after its leader moved. The
gateway now opens the stream on the leader named by the partition
lookup it already caches. A not-leader or connection failure drops the
session and the cached lookup and comes back as ErrNotLeaderOrFollower,
so the next attempt finds the new leader.

* mq/kafka: answer a produce that lost its partition leader with NOT_LEADER_OR_FOLLOWER

Every failed produce went back to the client as UNKNOWN_SERVER_ERROR,
which Kafka clients do not retry, so a partition leader change surfaced
as failed sends. A publish that failed because the leader moved or
could not be reached now answers NOT_LEADER_OR_FOLLOWER, and the client
refreshes its metadata and sends again.

* mq client: let the flush timeout cancel a stalled partition lookup

A lookup after a stream failure used context.Background, so a broker
that accepted LookupTopicBrokers and never answered kept the scheduler
inside it after the flush timeout, and Shutdown never returned. Lookups
now run under a context cancelled when the publisher stops, and each
broker attempt is bounded so a stalled one does not hold up the next.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq client: stop each test publisher and release held acks on cancel

A test that never shut its publisher down left the scheduler retrying
lookups against the stopped fake broker for the rest of the package run,
and a fake ack worker held on the gate could not exit when its stream
was cancelled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq client: do not restart a partition whose stream finished during the switch

A re-lookup that moved a partition's leader cancelled its stream and
waited for it, then started a new one. If that stream had just finished
cleanly, the replacement ran for a job already counted as done, and the
scheduler could exit with it still running.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq client: count only data messages as unacknowledged at Shutdown

The count added the in-flight list and the queue length, so the close
marker FinishPublish queues counted as a lost message: an empty
publisher whose marker went unacked reported one unacknowledged message.
Every data message holds a slot until it is acked, so the slots are the
count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq/kafka: let a produce's deadline bound opening its publish stream

Opening a session ran under the gateway's own context and waited for the
leader's hello, so a leader that took the init and never answered held
the produce, and every produce to that partition queued on the creation
lock, past their deadlines. Setup now also ends when the caller's
context does, without invalidating the assignment for a caller timeout,
and the stream outlives the call once open. A call whose context ended
while it waited for a dropped session no longer opens another one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq/kafka: cancel the held publish only once the broker holds its data

The test cancelled on a 200 ms timer. A slow session setup let that
deadline pass before the data went out, leaving the first stream open
for the next call, which then waited on the held ack.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq/kafka: fetch and read offsets from the partition's leader

Produces go to the leader, but fetches and the high water mark and log
start offset reads still went to the gateway's own broker, which answers
partition not found for a partition it does not lead. Reads now use the
leader the assignment lookup returns, as the publish path does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq agent: report unacknowledged messages when a publish session closes

ClosePublishSession returned success right after FinishPublish, which
only queues the close marker, so a message the brokers never acked was
lost without an error. The close now waits for Shutdown, which returns
once everything is acked or reports what was not after the flush
timeout, and no longer holds the session map lock while it waits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq/kafka: look the leader up again after a read it cannot serve

Reads used the cached assignment until its TTL, so after a leader died or
gave the partition up, every fetch for the next 30 seconds went to it.
A connection failure or a partition-not-found answer from the leader now
drops the cached assignment, unless the caller's own context ended.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq client: leave a Publish still waiting to enqueue out of the Shutdown count

Publish takes a slot before it checks that the input is open, so a
Publish paused between the two still held its slot when Shutdown
counted, and Shutdown reported a message the caller was then told was
rejected. Each job now counts the data messages it accepted and has not
had acked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq/kafka: cancel the silent-leader publish once its hello is withheld

The test cancelled on a 200 ms timer, which could fire before the call
opened a stream; the retry then opened the withheld stream with no
deadline and hung the suite. It now cancels once the fixture holds the
hello and bounds the retry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq: retain the original publisher payload for replay

* mq agent: flush accepted records when the publish stream closes

* mq client: isolate bootstrap RPCs by publisher credentials

* mq/kafka: honor publish cancellation during lookup and partition waits

* mq/kafka: read a partition's offset range from its leader

GetHighWaterMark and GetEarliestOffset asked the gateway's configured
broker, which answers from its own log buffer. Publishes now go to the
partition's leader, so a non-leader gateway broker reported a high water
mark that missed the leader's unflushed records. Send the range query to
the leader and drop the cached assignment when that broker fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq agent client: bound the wait for the agent to finish a session

CloseSession waited in Recv until the agent answered EOF. An agent
blocked enqueueing to a partition whose broker stopped acknowledging
never reads the close, so it never starts its bounded flush and the
close hung. After two minutes, cancel the stream: the agent then stops
accepting and flushes, and the close reports the timeout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq agent: wait for both closers to reach the flush in the close test

The duplicate-close test slept 100 ms to let the second close start. A
late goroutine then found the session already removed and the test
failed. Wait until both closers are inside finishPublisher instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mq: answer a partition's offset range only from its leader

A broker answered GetPartitionRangeInfo from its offset manager even
after the partition moved away, so the gateway kept reading the old
leader's range until its assignment cache expired. The broker now checks
ownership the way FetchMessage does, and the gateway drops the cached
assignment when the range request fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 23:34:45 -08:00
github-actions[bot] 29eebd7bb2 docs: regenerate star history chart 2026-12-01 07:21:20 +00:00
Yip LeoandClaude Opus 5.5 e3e3bacf10 mount: read an open file's extended attributes under its entry lock (#13194)
* mount: read an open file's extended attributes under its entry lock

getxattr and listxattr on an open file read the Extended map of the
handle's live entry with no lock, while setxattr and removexattr change
that map in place. Go ends the process on a concurrent map read and
write, so weed mount exits with "fatal error: concurrent map read and
map write" (GetXAttr) or "concurrent map iteration and map write"
(ListXAttr), and every file open on the mount returns ENOTCONN. The
kernel asks for security.capability on each write(), so a program that
writes a file while another process sets or removes its attributes
reaches this.

The entry's own lock, LockedEntry.RWMutex, is the one every other
writer of the handle's entry takes: truncate to zero, the metadata
merges of a flush, SetEntry and the acknowledged-attribute retention.
setxattr and removexattr changed the map under the handle lock and
entryLock only. They now also take the entry lock, in the documented
order after those two, and re-read the handle's entry under it, as
SetAttr does, in case SetEntry swapped it. GetXAttr and ListXAttr read
the handle's current entry under the entry's read lock and copy what
they return before releasing it. The read lock is a leaf: it waits for
no other lock and does not wait for the handle lock, so a getxattr is
not held up by a write in progress.

TestXAttrReadsAgainstSetAndRemoveOnOpenFile and
TestXAttrReadsAgainstTruncateToZeroOnOpenFile abort the test binary with
the fatal errors above without the change, and all three race tests
report data races under -race.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: remove the attributes the xattr race test sets

The writer of TestXAttrReadsAgainstSetAndRemoveOnOpenFile set even
keys and removed odd ones, so every RemoveXAttr found no key and
returned ENOATTR before deleting anything. Each name is now set and
then removed, and both calls must succeed. With RemoveXAttr's entry
lock taken out, -race reports its delete against GetXAttr's read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 23:13:23 -08:00
23 changed files with 3235 additions and 1547 deletions

No files matched your search

+1056 -1060
View File
File diff suppressed because it is too large. Load diff

Before

Width:  |  Height:  |  Size: 54 KiB

After

Width:  |  Height:  |  Size: 54 KiB

+39 -11
View File
@@ -42,13 +42,17 @@ func (wfs *WFS) GetXAttr(cancel <-chan struct{}, header *fuse.InHeader, attr str
ctx, cancelFunc := ctxFromCancel(cancel)
defer cancelFunc()
_, _, entry, status := wfs.maybeReadEntry(ctx, header.NodeId)
_, fh, entry, status := wfs.maybeReadEntry(ctx, header.NodeId)
if status != fuse.OK {
return 0, status
}
if entry == nil {
return 0, fuse.ENOENT
}
// An open handle's Extended map is shared with the writers of its
// entry, so the value is copied out while the entry lock is held.
unlock, entry := lockExtendedForRead(fh, entry)
defer unlock()
if entry.Extended == nil {
return 0, fuse.ENOATTR
}
@@ -64,6 +68,20 @@ func (wfs *WFS) GetXAttr(cancel <-chan struct{}, header *fuse.InHeader, attr str
return uint32(len(data)), fuse.OK
}
// lockExtendedForRead returns the entry whose Extended map the caller may
// read until it calls unlock. An open handle's entry is changed in place by
// setxattr, removexattr, truncate to zero and the metadata merges, all under
// the LockedEntry lock, and SetEntry can swap the entry since maybeReadEntry
// returned it, so the read takes that lock and the handle's current entry.
// Any other entry is a private copy.
func lockExtendedForRead(fh *FileHandle, entry *filer_pb.Entry) (unlock func(), current *filer_pb.Entry) {
if fh == nil {
return func() {}, entry
}
fh.entry.RLock()
return fh.entry.RUnlock, fh.entry.Entry
}
// SetXAttr writes an extended attribute.
// https://man7.org/linux/man-pages/man2/setxattr.2.html
//
@@ -144,6 +162,11 @@ func (wfs *WFS) SetXAttr(cancel <-chan struct{}, input *fuse.SetXAttrIn, attr st
defer wfs.fhLockTable.ReleaseLock(fh.fh, active)
fh.entryLock.Lock()
defer fh.entryLock.Unlock()
// Readers take only the LockedEntry lock. Re-read the entry under
// it in case SetEntry swapped the pointer since maybeReadEntry.
fh.entry.Lock()
defer fh.entry.Unlock()
entry = fh.entry.Entry
}
if code := applyXAttr(entry, input.Flags, attr, data); code != fuse.OK {
@@ -175,24 +198,24 @@ func (wfs *WFS) ListXAttr(cancel <-chan struct{}, header *fuse.InHeader, dest []
ctx, cancelFunc := ctxFromCancel(cancel)
defer cancelFunc()
_, _, entry, status := wfs.maybeReadEntry(ctx, header.NodeId)
_, fh, entry, status := wfs.maybeReadEntry(ctx, header.NodeId)
if status != fuse.OK {
return 0, status
}
if entry == nil {
return 0, fuse.ENOENT
}
if entry.Extended == nil {
return 0, fuse.OK
}
var data []byte
for k := range entry.Extended {
if strings.HasPrefix(k, XATTR_PREFIX) {
data = append(data, k[len(XATTR_PREFIX):]...)
data = append(data, 0)
func() {
unlock, live := lockExtendedForRead(fh, entry)
defer unlock()
for k := range live.Extended {
if strings.HasPrefix(k, XATTR_PREFIX) {
data = append(data, k[len(XATTR_PREFIX):]...)
data = append(data, 0)
}
}
}
}()
if len(dest) < len(data) {
return uint32(len(data)), fuse.ERANGE
}
@@ -244,6 +267,11 @@ func (wfs *WFS) RemoveXAttr(cancel <-chan struct{}, header *fuse.InHeader, attr
defer wfs.fhLockTable.ReleaseLock(fh.fh, active)
fh.entryLock.Lock()
defer fh.entryLock.Unlock()
// Readers take only the LockedEntry lock. Re-read the entry under
// it in case SetEntry swapped the pointer since maybeReadEntry.
fh.entry.Lock()
defer fh.entry.Unlock()
entry = fh.entry.Entry
}
if code := removeXAttr(entry, attr); code != fuse.OK {
+154
View File
@@ -0,0 +1,154 @@
//go:build !freebsd
package mount
import (
"fmt"
"sync"
"testing"
"time"
"github.com/seaweedfs/go-fuse/v2/fuse"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
)
// raceDuration is how long a reader and a writer run against each other. The
// unguarded map access this covers fails within milliseconds: Go aborts the
// whole process on a concurrent map read and write, and -race reports it.
const raceDuration = 300 * time.Millisecond
// openXAttrRaceHandle opens a file with some extended attributes and no name,
// as an unlinked file that is still open: every operation on it works on the
// handle's own entry and none goes to the filer.
func openXAttrRaceHandle(t *testing.T, content []byte) (*WFS, *FileHandle) {
t.Helper()
wfs := newCopyRangeTestWFS()
const inode = 42
fh, _, _, _ := wfs.fhMap.AcquireFileHandle(wfs, inode, &filer_pb.Entry{
Name: "x.txt",
Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, FileSize: uint64(len(content)), Inode: inode},
Content: content,
Extended: map[string][]byte{
XATTR_PREFIX + "user.a": []byte("1"),
XATTR_PREFIX + "user.b": []byte("2"),
},
}, 0, 0)
t.Cleanup(fh.dirtyPages.Destroy)
fh.dirtyMetadata = true
return wfs, fh
}
// runXAttrRace runs one writer and several readers until the time is up.
func runXAttrRace(writer func(i int), readers ...func(i int)) {
stop := make(chan struct{})
var wg sync.WaitGroup
for _, fn := range append([]func(int){writer}, readers...) {
wg.Add(1)
go func(fn func(int)) {
defer wg.Done()
for i := 0; ; i++ {
select {
case <-stop:
return
default:
}
fn(i)
}
}(fn)
}
time.Sleep(raceDuration)
close(stop)
wg.Wait()
}
func getXAttrReader(t *testing.T, wfs *WFS, inode uint64, name string) func(int) {
dest := make([]byte, 64)
return func(int) {
n, code := wfs.GetXAttr(nil, &fuse.InHeader{NodeId: inode}, name, dest)
if code == fuse.OK && n == 0 {
t.Errorf("GetXAttr(%q) = OK with no bytes", name)
}
}
}
func listXAttrReader(wfs *WFS, inode uint64) func(int) {
dest := make([]byte, 4096)
return func(int) { wfs.ListXAttr(nil, &fuse.InHeader{NodeId: inode}, dest) }
}
// SetXAttr and RemoveXAttr on an open file change its entry's Extended map in
// place while GetXAttr and ListXAttr read it.
func TestXAttrReadsAgainstSetAndRemoveOnOpenFile(t *testing.T) {
wfs, fh := openXAttrRaceHandle(t, nil)
inode := fh.inode
runXAttrRace(func(i int) {
// each name is set and then removed, so every removal deletes a key
name := fmt.Sprintf("user.k%d", (i/2)%64)
if i%2 == 0 {
if code := wfs.SetXAttr(nil, &fuse.SetXAttrIn{InHeader: fuse.InHeader{NodeId: inode}}, name, []byte("v")); code != fuse.OK {
t.Errorf("SetXAttr(%q) = %v", name, code)
}
} else if code := wfs.RemoveXAttr(nil, &fuse.InHeader{NodeId: inode}, name); code != fuse.OK {
t.Errorf("RemoveXAttr(%q) = %v", name, code)
}
}, getXAttrReader(t, wfs, inode, "user.a"), getXAttrReader(t, wfs, inode, "security.capability"), listXAttrReader(wfs, inode))
}
// Truncating an open file to zero removes its S3 encryption attributes from
// the same map.
func TestXAttrReadsAgainstTruncateToZeroOnOpenFile(t *testing.T) {
wfs, fh := openXAttrRaceHandle(t, []byte("payload"))
inode := fh.inode
runXAttrRace(func(int) {
// put the keys back so that every truncate deletes something
fh.UpdateEntry(func(e *filer_pb.Entry) {
e.Extended[s3_constants.AmzServerSideEncryption] = []byte("AES256")
e.Extended[s3_constants.SeaweedFSSSEIV] = []byte("iv")
})
in := &fuse.SetAttrIn{}
in.NodeId, in.Valid, in.Size = inode, fuse.FATTR_SIZE, 0
if code := wfs.SetAttr(nil, in, &fuse.AttrOut{}); code != fuse.OK {
t.Errorf("truncate = %v", code)
}
}, getXAttrReader(t, wfs, inode, "user.a"), listXAttrReader(wfs, inode))
}
// A flush that merged a peer's change gives the handle the merged entry's
// attributes, Extended among them.
func TestXAttrReadsAgainstFlushMergeOnOpenFile(t *testing.T) {
wfs, fh := openXAttrRaceHandle(t, nil)
inode := fh.inode
runXAttrRace(func(i int) {
merged := &filer_pb.Entry{
Name: "x.txt",
Attributes: &filer_pb.FuseAttributes{FileMode: 0100644, Inode: inode},
Extended: map[string][]byte{
XATTR_PREFIX + "user.a": []byte("1"),
XATTR_PREFIX + fmt.Sprintf("user.m%d", i%8): []byte("m"),
},
}
fh.rebaseEntry(merged, &filer_pb.Entry{Attributes: &filer_pb.FuseAttributes{}})
}, getXAttrReader(t, wfs, inode, "user.a"), listXAttrReader(wfs, inode))
}
// The reply carries the value as it was when it was read, in the caller's
// buffer.
func TestGetXAttrReturnsCopyOfOpenFileValue(t *testing.T) {
wfs, fh := openXAttrRaceHandle(t, nil)
dest := make([]byte, 8)
n, code := wfs.GetXAttr(nil, &fuse.InHeader{NodeId: fh.inode}, "user.a", dest)
if code != fuse.OK || string(dest[:n]) != "1" {
t.Fatalf("GetXAttr = %q, %v; want \"1\", OK", dest[:n], code)
}
dest[0] = 'x'
if got := fh.entry.Entry.Extended[XATTR_PREFIX+"user.a"]; string(got) != "1" {
t.Fatalf("the handle's value changed through the caller's buffer: %q", got)
}
if code := wfs.SetXAttr(nil, &fuse.SetXAttrIn{InHeader: fuse.InHeader{NodeId: fh.inode}}, "user.a", []byte("22")); code != fuse.OK {
t.Fatalf("SetXAttr = %v", code)
}
if n, code = wfs.GetXAttr(nil, &fuse.InHeader{NodeId: fh.inode}, "user.a", dest); code != fuse.OK || string(dest[:n]) != "22" {
t.Fatalf("GetXAttr after SetXAttr = %q, %v; want \"22\", OK", dest[:n], code)
}
}
+26 -9
View File
@@ -2,6 +2,7 @@ package agent
import (
"context"
"fmt"
"log/slog"
"math/rand/v2"
@@ -20,6 +21,7 @@ func (a *MessageQueueAgent) StartPublishSession(ctx context.Context, req *mq_age
Brokers: a.brokersList(),
PublisherName: req.PublisherName,
RecordType: req.RecordType,
GrpcDialOption: a.grpcDialOption,
})
if err != nil {
return nil, err
@@ -37,18 +39,33 @@ func (a *MessageQueueAgent) StartPublishSession(ctx context.Context, req *mq_age
}
func (a *MessageQueueAgent) ClosePublishSession(ctx context.Context, req *mq_agent_pb.ClosePublishSessionRequest) (*mq_agent_pb.ClosePublishSessionResponse, error) {
var finishErr string
sessionID := SessionId(req.SessionId)
a.publishersLock.RLock()
entry := a.publishers[sessionID]
a.publishersLock.RUnlock()
if entry == nil {
return &mq_agent_pb.ClosePublishSessionResponse{Error: fmt.Sprintf("publish session id %d not found", sessionID)}, nil
}
if err := a.finishPublisher(sessionID, entry); err != nil {
return &mq_agent_pb.ClosePublishSessionResponse{Error: err.Error()}, nil
}
return &mq_agent_pb.ClosePublishSessionResponse{}, nil
}
// Concurrent closers of the same publisher wait on the same scheduler and observe
// the same acknowledgment count. Keep the session reachable during the flush.
func (a *MessageQueueAgent) finishPublisher(id SessionId, entry *SessionEntry[*pub_client.TopicPublisher]) error {
err := entry.entry.FinishPublish()
if err == nil {
err = entry.entry.Shutdown()
}
a.publishersLock.Lock()
publisherEntry, found := a.publishers[SessionId(req.SessionId)]
if found {
if err := publisherEntry.entry.FinishPublish(); err != nil {
finishErr = err.Error()
if a.publishers[id] == entry {
delete(a.publishers, id)
if err != nil {
slog.Warn("failed to finish publish", "error", err)
}
delete(a.publishers, SessionId(req.SessionId))
}
a.publishersLock.Unlock()
return &mq_agent_pb.ClosePublishSessionResponse{
Error: finishErr,
}, nil
return err
}
+11 -4
View File
@@ -1,12 +1,15 @@
package agent
import (
"context"
"errors"
"fmt"
"io"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_agent_pb"
)
func (a *MessageQueueAgent) PublishRecord(stream mq_agent_pb.SeaweedMessagingAgent_PublishRecordServer) error {
func (a *MessageQueueAgent) PublishRecord(stream mq_agent_pb.SeaweedMessagingAgent_PublishRecordServer) (streamErr error) {
m, err := stream.Recv()
if err != nil {
return err
@@ -18,10 +21,11 @@ func (a *MessageQueueAgent) PublishRecord(stream mq_agent_pb.SeaweedMessagingAge
if !found {
return fmt.Errorf("publish session id %d not found", sessionId)
}
// A disconnected stream may already be blocked enqueueing to a full partition.
stopOnDisconnect := context.AfterFunc(stream.Context(), func() { publisherEntry.entry.FinishPublish() })
defer func() {
a.publishersLock.Lock()
delete(a.publishers, sessionId)
a.publishersLock.Unlock()
stopOnDisconnect()
streamErr = errors.Join(streamErr, a.finishPublisher(sessionId, publisherEntry))
}()
if m.Value != nil {
@@ -32,6 +36,9 @@ func (a *MessageQueueAgent) PublishRecord(stream mq_agent_pb.SeaweedMessagingAge
for {
m, err = stream.Recv()
if err == io.EOF {
return nil
}
if err != nil {
return err
}
+158
View File
@@ -0,0 +1,158 @@
package agent
import (
"context"
"net"
"runtime"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/mq/client/agent_client"
"github.com/seaweedfs/seaweedfs/weed/mq/pub_balancer"
"github.com/seaweedfs/seaweedfs/weed/mq/schema"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_agent_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type gatedAckBroker struct {
mq_pb.UnimplementedSeaweedMessagingServer
addr string
closeMarker chan struct{}
allowAck chan struct{}
}
func (b *gatedAckBroker) ConfigureTopic(context.Context, *mq_pb.ConfigureTopicRequest) (*mq_pb.ConfigureTopicResponse, error) {
return &mq_pb.ConfigureTopicResponse{}, nil
}
func (b *gatedAckBroker) LookupTopicBrokers(context.Context, *mq_pb.LookupTopicBrokersRequest) (*mq_pb.LookupTopicBrokersResponse, error) {
return &mq_pb.LookupTopicBrokersResponse{BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{{
Partition: &schema_pb.Partition{RangeStop: pub_balancer.MaxPartitionCount},
LeaderBroker: b.addr,
}}}, nil
}
func (b *gatedAckBroker) PublishMessage(stream mq_pb.SeaweedMessaging_PublishMessageServer) error {
if _, err := stream.Recv(); err != nil {
return err
}
if err := stream.Send(&mq_pb.PublishMessageResponse{}); err != nil {
return err
}
for {
req, err := stream.Recv()
if err != nil {
return nil
}
data := req.GetData()
if data.GetCtrl().GetIsClose() {
close(b.closeMarker)
select {
case <-b.allowAck:
case <-stream.Context().Done():
return stream.Context().Err()
}
// The marker acknowledges the entire stream, including the earlier record.
if err := stream.Send(&mq_pb.PublishMessageResponse{AckTsNs: data.TsNs}); err != nil {
return err
}
}
}
}
func TestPublishStreamCloseWaitsForAcknowledgment(t *testing.T) {
listen := func() net.Listener {
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
return l
}
brokerListener := listen()
broker := &gatedAckBroker{addr: brokerListener.Addr().String(), closeMarker: make(chan struct{}), allowAck: make(chan struct{})}
brokerServer := grpc.NewServer()
mq_pb.RegisterSeaweedMessagingServer(brokerServer, broker)
go brokerServer.Serve(brokerListener)
t.Cleanup(brokerServer.Stop)
agent := NewMessageQueueAgent(&MessageQueueAgentOptions{SeedBrokers: []pb.ServerAddress{pb.ServerAddress(broker.addr)}}, grpc.WithTransportCredentials(insecure.NewCredentials()))
agentListener := listen()
agentServer := grpc.NewServer()
mq_agent_pb.RegisterSeaweedMessagingAgentServer(agentServer, agent)
go agentServer.Serve(agentListener)
t.Cleanup(agentServer.Stop)
client, err := agent_client.NewPublishSession(agentListener.Addr().String(), &schema.Schema{Namespace: "test", Name: "events"}, 1, "test")
if err != nil {
t.Fatal(err)
}
agent.publishersLock.RLock()
var id SessionId
for id = range agent.publishers {
break
}
agent.publishersLock.RUnlock()
if err := client.PublishMessageRecord([]byte("key"), &schema_pb.RecordValue{}); err != nil {
t.Fatal(err)
}
closed := make(chan error, 1)
go func() { closed <- client.CloseSession() }()
select {
case <-broker.closeMarker:
case <-time.After(5 * time.Second):
t.Fatal("closing the stream did not finish the publisher")
}
duplicate := make(chan *mq_agent_pb.ClosePublishSessionResponse, 1)
go func() {
resp, _ := agent.ClosePublishSession(t.Context(), &mq_agent_pb.ClosePublishSessionRequest{SessionId: int64(id)})
duplicate <- resp
}()
waitForFinishers(t, 2)
select {
case <-closed:
t.Fatal("stream close returned before acknowledgment")
case <-duplicate:
t.Fatal("duplicate close returned before acknowledgment")
default:
}
close(broker.allowAck)
select {
case err := <-closed:
if err != nil {
t.Fatal(err)
}
case <-time.After(5 * time.Second):
t.Fatal("stream close did not finish")
}
select {
case resp := <-duplicate:
if resp == nil || resp.Error != "" {
t.Fatalf("duplicate close returned %v", resp)
}
case <-time.After(5 * time.Second):
t.Fatal("duplicate close did not finish")
}
}
// waitForFinishers waits until n goroutines are flushing a publisher in finishPublisher.
func waitForFinishers(t *testing.T, n int) {
t.Helper()
buf := make([]byte, 1<<20)
deadline := time.Now().Add(10 * time.Second)
for {
stacks := string(buf[:runtime.Stack(buf, true)])
if strings.Count(stacks, "(*MessageQueueAgent).finishPublisher(") >= n {
return
}
if time.Now().After(deadline) {
t.Fatalf("fewer than %d goroutines reached finishPublisher", n)
}
time.Sleep(time.Millisecond)
}
}
+13
View File
@@ -277,6 +277,19 @@ func (b *MessageQueueBroker) GetPartitionRangeInfo(ctx context.Context, req *mq_
t := topic.FromPbTopic(req.Topic)
p := topic.FromPbPartition(req.Partition)
// A broker that no longer leads the partition would answer with its stale range.
localPartition, err := b.GetOrGenerateLocalPartition(t, p)
if err != nil {
return &mq_pb.GetPartitionRangeInfoResponse{
Error: fmt.Sprintf("partition not found: %v", err),
}, nil
}
if localPartition == nil {
return &mq_pb.GetPartitionRangeInfoResponse{
Error: "partition not found",
}, nil
}
// Get offset information from the broker's internal method
info, err := b.GetPartitionOffsetInfoInternal(t, p)
if err != nil {
+55 -17
View File
@@ -3,6 +3,9 @@ package agent_client
import (
"context"
"fmt"
"io"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/mq/schema"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_agent_pb"
@@ -11,20 +14,33 @@ import (
"google.golang.org/grpc/credentials/insecure"
)
// The agent bounds its flush by a minute once it reads the close. It cannot read the
// close while it waits for room on a partition whose broker stopped acknowledging.
var closeTimeout = 2 * time.Minute
type PublishSession struct {
schema *schema.Schema
partitionCount int
publisherName string
stream grpc.BidiStreamingClient[mq_agent_pb.PublishRecordRequest, mq_agent_pb.PublishRecordResponse]
closeOnce sync.Once
closeErr error
conn *grpc.ClientConn
ctx context.Context
cancel context.CancelCauseFunc
stream grpc.BidiStreamingClient[mq_agent_pb.PublishRecordRequest, mq_agent_pb.PublishRecordResponse]
}
func NewPublishSession(agentAddress string, topicSchema *schema.Schema, partitionCount int, publisherName string) (*PublishSession, error) {
func NewPublishSession(agentAddress string, topicSchema *schema.Schema, partitionCount int, publisherName string) (_ *PublishSession, err error) {
// call local agent grpc server to create a new session
clientConn, err := grpc.NewClient(agentAddress, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return nil, fmt.Errorf("dial agent server %s: %v", agentAddress, err)
}
ctx, cancel := context.WithCancelCause(context.Background())
defer func() {
if err != nil {
cancel(nil)
clientConn.Close()
}
}()
agentClient := mq_agent_pb.NewSeaweedMessagingAgentClient(clientConn)
resp, err := agentClient.StartPublishSession(context.Background(), &mq_agent_pb.StartPublishSessionRequest{
@@ -43,7 +59,7 @@ func NewPublishSession(agentAddress string, topicSchema *schema.Schema, partitio
return nil, fmt.Errorf("start publish session: %v", resp.Error)
}
stream, err := agentClient.PublishRecord(context.Background())
stream, err := agentClient.PublishRecord(ctx)
if err != nil {
return nil, fmt.Errorf("publish record: %w", err)
}
@@ -55,23 +71,45 @@ func NewPublishSession(agentAddress string, topicSchema *schema.Schema, partitio
}
return &PublishSession{
schema: topicSchema,
partitionCount: partitionCount,
publisherName: publisherName,
stream: stream,
conn: clientConn,
ctx: ctx,
cancel: cancel,
stream: stream,
}, nil
}
func (a *PublishSession) CloseSession() error {
if a.schema == nil {
return nil
}
err := a.stream.CloseSend()
if err != nil {
a.closeOnce.Do(func() { a.closeErr = a.closeStream() })
return a.closeErr
}
func (a *PublishSession) closeStream() error {
defer a.conn.Close()
defer a.cancel(nil)
if err := a.stream.CloseSend(); err != nil {
return fmt.Errorf("close send: %w", err)
}
a.schema = nil
return err
// Cancelling the stream makes the agent stop accepting and flush what it holds.
timer := time.AfterFunc(closeTimeout, func() {
a.cancel(fmt.Errorf("agent did not finish within %v", closeTimeout))
})
defer timer.Stop()
// The agent closes the receive side after flushing all accepted records.
for {
resp, err := a.stream.Recv()
if err == io.EOF {
return nil
}
if err != nil {
if cause := context.Cause(a.ctx); cause != nil {
err = cause
}
return fmt.Errorf("finish publish: %w", err)
}
if resp.Error != "" {
return fmt.Errorf("finish publish: %s", resp.Error)
}
}
}
func (a *PublishSession) PublishMessageRecord(key []byte, record *schema_pb.RecordValue) error {
@@ -0,0 +1,68 @@
package agent_client
import (
"context"
"net"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/mq/schema"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_agent_pb"
"google.golang.org/grpc"
)
// stuckAgent never reads past the session id, like an agent blocked enqueueing to a full partition.
type stuckAgent struct {
mq_agent_pb.UnimplementedSeaweedMessagingAgentServer
cancelled chan struct{}
}
func (s *stuckAgent) StartPublishSession(context.Context, *mq_agent_pb.StartPublishSessionRequest) (*mq_agent_pb.StartPublishSessionResponse, error) {
return &mq_agent_pb.StartPublishSessionResponse{SessionId: 1}, nil
}
func (s *stuckAgent) PublishRecord(stream mq_agent_pb.SeaweedMessagingAgent_PublishRecordServer) error {
if _, err := stream.Recv(); err != nil {
return err
}
<-stream.Context().Done()
close(s.cancelled)
return stream.Context().Err()
}
func TestCloseSessionCancelsAStuckAgent(t *testing.T) {
saved := closeTimeout
closeTimeout = 200 * time.Millisecond
defer func() { closeTimeout = saved }()
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
agent := &stuckAgent{cancelled: make(chan struct{})}
server := grpc.NewServer()
mq_agent_pb.RegisterSeaweedMessagingAgentServer(server, agent)
go server.Serve(listener)
t.Cleanup(server.Stop)
session, err := NewPublishSession(listener.Addr().String(), &schema.Schema{Namespace: "test", Name: "events"}, 1, "test")
if err != nil {
t.Fatal(err)
}
closed := make(chan error, 1)
go func() { closed <- session.CloseSession() }()
select {
case err := <-closed:
if err == nil || !strings.Contains(err.Error(), "did not finish") {
t.Fatalf("close of a stuck agent returned %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("close waited on a stuck agent")
}
select {
case <-agent.cancelled:
case <-time.After(5 * time.Second):
t.Fatal("the agent's stream was not cancelled")
}
}
+76 -18
View File
@@ -1,7 +1,10 @@
package pub_client
import (
"bytes"
"errors"
"fmt"
"sync/atomic"
"time"
"github.com/golang/protobuf/proto"
@@ -11,6 +14,8 @@ import (
"github.com/seaweedfs/seaweedfs/weed/util"
)
var errPublisherClosed = errors.New("publisher is closed")
func (p *TopicPublisher) Publish(key, value []byte) error {
if p.config.RecordType != nil {
return fmt.Errorf("record type is set, use PublishRecord instead")
@@ -18,21 +23,55 @@ func (p *TopicPublisher) Publish(key, value []byte) error {
return p.doPublish(key, value)
}
// doPublish blocks while the partition already holds maxBufferedMessages queued or unacked messages.
func (p *TopicPublisher) doPublish(key, value []byte) error {
hashKey := util.HashToInt32(key) % pub_balancer.MaxPartitionCount
if hashKey < 0 {
hashKey = -hashKey
}
inputBuffer, found := p.partition2Buffer.Floor(hashKey+1, hashKey+1)
p.Lock()
job, found := p.partition2Buffer.Floor(hashKey+1, hashKey+1)
p.Unlock()
if !found {
return fmt.Errorf("no input buffer found for key %d", hashKey)
}
return inputBuffer.Enqueue(&mq_pb.DataMessage{
Key: key,
Value: value,
TsNs: time.Now().UnixNano(),
})
select {
case job.slots <- struct{}{}:
case <-p.inputDone:
return errPublisherClosed
}
p.inputLock.RLock()
defer p.inputLock.RUnlock()
if p.inputClosed {
<-job.slots
return errPublisherClosed
}
// the in-flight list matches acks by TsNs, so a partition's queue must be in TsNs order
job.enqueueLock.Lock()
job.accepted.Add(1)
job.inputQueue <- &mq_pb.DataMessage{
// The caller may reuse its buffers while this message awaits a retry.
Key: bytes.Clone(key),
Value: bytes.Clone(value),
TsNs: p.nextTsNs(),
}
job.enqueueLock.Unlock()
return nil
}
func (p *TopicPublisher) nextTsNs() int64 {
for {
last := atomic.LoadInt64(&p.lastTsNs)
tsNs := time.Now().UnixNano()
if tsNs <= last {
tsNs = last + 1
}
if atomic.CompareAndSwapInt64(&p.lastTsNs, last, tsNs) {
return tsNs
}
}
}
func (p *TopicPublisher) PublishRecord(key []byte, recordValue *schema_pb.RecordValue) error {
@@ -45,18 +84,37 @@ func (p *TopicPublisher) PublishRecord(key []byte, recordValue *schema_pb.Record
return p.doPublish(key, value)
}
// FinishPublish sends the close marker to every partition and stops accepting messages.
// Queued messages are still delivered in the background; Shutdown waits for them.
func (p *TopicPublisher) FinishPublish() error {
if inputBuffers, found := p.partition2Buffer.AllIntersections(0, pub_balancer.MaxPartitionCount); found {
for _, inputBuffer := range inputBuffers {
inputBuffer.Enqueue(&mq_pb.DataMessage{
TsNs: time.Now().UnixNano(),
Ctrl: &mq_pb.ControlMessage{
IsClose: true,
PublisherName: p.config.PublisherName,
},
})
}
}
p.closeInput(&mq_pb.ControlMessage{
IsClose: true,
PublisherName: p.config.PublisherName,
})
return nil
}
func (p *TopicPublisher) closeInput(ctrl *mq_pb.ControlMessage) {
p.inputLock.Lock()
defer p.inputLock.Unlock()
if p.inputClosed {
return
}
p.inputClosed = true
close(p.inputDone)
p.Lock()
jobs := p.jobs
p.Unlock()
for _, job := range jobs {
if ctrl != nil {
// the queue keeps one spare slot for this marker
job.inputQueue <- &mq_pb.DataMessage{
TsNs: p.nextTsNs(),
Ctrl: ctrl,
}
}
close(job.inputQueue)
}
time.AfterFunc(flushTimeout, p.stop)
}
+48 -28
View File
@@ -1,74 +1,94 @@
package pub_client
import (
"log"
"fmt"
"sync"
"time"
"github.com/rdleal/intervalst/interval"
"github.com/seaweedfs/seaweedfs/weed/mq/pub_balancer"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"github.com/seaweedfs/seaweedfs/weed/util/buffered_queue"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// how long FinishPublish or Shutdown keeps resending before giving up on unacked messages
var flushTimeout = time.Minute
type PublisherConfiguration struct {
Topic topic.Topic
PartitionCount int32
Brokers []string
PublisherName string // for debugging
RecordType *schema_pb.RecordType
GrpcDialOption grpc.DialOption // insecure when nil
}
type PublishClient struct {
mq_pb.SeaweedMessaging_PublishMessageClient
Broker string
Err error
}
type TopicPublisher struct {
partition2Buffer *interval.SearchTree[*buffered_queue.BufferedQueue[*mq_pb.DataMessage], int32]
partition2Buffer *interval.SearchTree[*EachPartitionPublishJob, int32]
grpcDialOption grpc.DialOption
sync.Mutex // protects grpc
sync.Mutex // protects partition2Buffer, jobs, and each job's run state
config *PublisherConfiguration
jobs []*EachPartitionPublishJob
jobEnded chan struct{}
lastTsNs int64
inputLock sync.RWMutex // held shared while enqueueing, exclusively to close the input
inputClosed bool
inputDone chan struct{}
stopped chan struct{}
stopOnce sync.Once
schedulerDone chan struct{}
}
func NewTopicPublisher(config *PublisherConfiguration) (tp *TopicPublisher, err error) {
grpcDialOption := config.GrpcDialOption
if grpcDialOption == nil {
grpcDialOption = grpc.WithTransportCredentials(insecure.NewCredentials())
}
tp = &TopicPublisher{
partition2Buffer: interval.NewSearchTree[*buffered_queue.BufferedQueue[*mq_pb.DataMessage]](func(a, b int32) int {
partition2Buffer: interval.NewSearchTree[*EachPartitionPublishJob](func(a, b int32) int {
return int(a - b)
}),
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
grpcDialOption: grpcDialOption,
config: config,
jobEnded: make(chan struct{}, 1),
inputDone: make(chan struct{}),
stopped: make(chan struct{}),
schedulerDone: make(chan struct{}),
}
if err = tp.doConfigureTopic(); err != nil {
return nil, fmt.Errorf("configure topic %s: %w", config.Topic, err)
}
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
if err = tp.startSchedulerThread(&wg); err != nil {
log.Println(err)
return
}
}()
go tp.startSchedulerThread(&wg)
wg.Wait()
return
}
// Shutdown stops accepting messages and returns once every queued message is acked,
// or with an error once flushTimeout passes.
func (p *TopicPublisher) Shutdown() error {
p.closeInput(nil)
<-p.schedulerDone
if inputBuffers, found := p.partition2Buffer.AllIntersections(0, pub_balancer.MaxPartitionCount); found {
for _, inputBuffer := range inputBuffers {
inputBuffer.CloseInput()
}
p.Lock()
jobs := p.jobs
p.Unlock()
unacked := 0
for _, job := range jobs {
unacked += job.unackedCount()
}
for _, job := range p.jobs {
job.wg.Wait()
if unacked > 0 {
return fmt.Errorf("publish to %s: %d messages not acknowledged", p.config.Topic, unacked)
}
return nil
}
func (p *TopicPublisher) stop() {
p.stopOnce.Do(func() { close(p.stopped) })
}
+500
View File
@@ -0,0 +1,500 @@
package pub_client
import (
"context"
"fmt"
"io"
"net"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/mq/pub_balancer"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
)
// fakeBroker leads the single partition of every topic. A message counts as
// stored only once it is acked.
type fakeBroker struct {
mq_pb.UnimplementedSeaweedMessagingServer
addr string
// breakStream, when set, returns how many data messages stream n (0-based)
// receives and how many of those it acks before failing.
breakStream func(n int) (receive, ack int, ok bool)
// ackGate, when set, holds every ack until it is closed.
ackGate chan struct{}
// receivedData observes each copy as it arrives, before any acknowledgment.
receivedData chan *mq_pb.DataMessage
// stallLookup, when set, holds lookup n (0-based) until the caller gives up.
stallLookup func(n int) bool
mu sync.Mutex
lookups int
streams int
stored map[string]int
perStream [][]string // keys received on each stream, in order
ctrlAcked int
}
func startFakeBroker(t *testing.T, fb *fakeBroker) *fakeBroker {
t.Helper()
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
fb.addr = listener.Addr().String()
fb.stored = make(map[string]int)
server := grpc.NewServer()
mq_pb.RegisterSeaweedMessagingServer(server, fb)
go server.Serve(listener)
t.Cleanup(server.Stop)
return fb
}
func (fb *fakeBroker) ConfigureTopic(ctx context.Context, req *mq_pb.ConfigureTopicRequest) (*mq_pb.ConfigureTopicResponse, error) {
return &mq_pb.ConfigureTopicResponse{}, nil
}
func (fb *fakeBroker) LookupTopicBrokers(ctx context.Context, req *mq_pb.LookupTopicBrokersRequest) (*mq_pb.LookupTopicBrokersResponse, error) {
fb.mu.Lock()
n := fb.lookups
fb.lookups++
fb.mu.Unlock()
if fb.stallLookup != nil && fb.stallLookup(n) {
<-ctx.Done()
return nil, ctx.Err()
}
return &mq_pb.LookupTopicBrokersResponse{
Topic: req.Topic,
BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{{
Partition: &schema_pb.Partition{
RingSize: pub_balancer.MaxPartitionCount,
RangeStart: 0,
RangeStop: pub_balancer.MaxPartitionCount,
},
LeaderBroker: fb.addr,
}},
}, nil
}
func (fb *fakeBroker) PublishMessage(stream mq_pb.SeaweedMessaging_PublishMessageServer) error {
if _, err := stream.Recv(); err != nil {
return err
}
fb.mu.Lock()
n := fb.streams
fb.streams++
fb.perStream = append(fb.perStream, nil)
fb.mu.Unlock()
receive, ackLimit, breaks := 0, 0, false
if fb.breakStream != nil {
receive, ackLimit, breaks = fb.breakStream(n)
}
if err := stream.Send(&mq_pb.PublishMessageResponse{}); err != nil {
return err
}
// acks go out from their own goroutine so a held ack never stops receiving
toAck := make(chan *mq_pb.DataMessage, 4*maxBufferedMessages)
ackDone := make(chan error, 1)
go func() {
var offset int64
for data := range toAck {
if fb.ackGate != nil {
select {
case <-fb.ackGate:
case <-stream.Context().Done():
ackDone <- stream.Context().Err()
for range toAck {
}
return
}
}
fb.mu.Lock()
if data.Ctrl != nil {
fb.ctrlAcked++
} else {
fb.stored[string(data.Key)]++
}
fb.mu.Unlock()
if err := stream.Send(&mq_pb.PublishMessageResponse{AckTsNs: data.TsNs, AssignedOffset: offset}); err != nil {
ackDone <- err
for range toAck {
}
return
}
offset++
}
ackDone <- nil
}()
received := 0
for {
req, err := stream.Recv()
if err != nil {
close(toAck)
ackErr := <-ackDone
if err == io.EOF {
return ackErr
}
return err
}
data := req.GetData()
if data == nil {
continue
}
fb.mu.Lock()
fb.perStream[n] = append(fb.perStream[n], string(data.Key))
fb.mu.Unlock()
if fb.receivedData != nil {
fb.receivedData <- data
}
received++
if breaks && received > ackLimit {
if received >= receive {
close(toAck)
<-ackDone
return status.Error(codes.Unavailable, "leader lost")
}
continue
}
toAck <- data
}
}
func (fb *fakeBroker) counts() (lookups, streams int) {
fb.mu.Lock()
defer fb.mu.Unlock()
return fb.lookups, fb.streams
}
func (fb *fakeBroker) storedKeys() map[string]int {
fb.mu.Lock()
defer fb.mu.Unlock()
out := make(map[string]int, len(fb.stored))
for k, v := range fb.stored {
out[k] = v
}
return out
}
func newTestPublisher(t *testing.T, fb *fakeBroker) *TopicPublisher {
t.Helper()
publisher, err := NewTopicPublisher(&PublisherConfiguration{
Topic: topic.NewTopic("test", t.Name()),
PartitionCount: 1,
Brokers: []string{fb.addr},
PublisherName: "test",
})
if err != nil {
t.Fatalf("new publisher: %v", err)
}
t.Cleanup(func() {
publisher.closeInput(nil)
publisher.stop()
<-publisher.schedulerDone
})
return publisher
}
func waitFor(t *testing.T, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(10 * time.Second)
for !cond() {
if time.Now().After(deadline) {
t.Fatalf("timed out waiting for %s", what)
}
time.Sleep(10 * time.Millisecond)
}
}
func testKey(i int) string {
return fmt.Sprintf("key-%05d", i)
}
func TestPublisherLooksUpAgainAfterStreamFailure(t *testing.T) {
fb := startFakeBroker(t, &fakeBroker{
breakStream: func(n int) (int, int, bool) { return 1, 0, n == 0 },
})
publisher := newTestPublisher(t, fb)
if err := publisher.Publish([]byte(testKey(0)), []byte("v")); err != nil {
t.Fatalf("publish: %v", err)
}
waitFor(t, "a second lookup and stream", func() bool {
lookups, streams := fb.counts()
return lookups >= 2 && streams >= 2
})
waitFor(t, "the message to be stored", func() bool {
return fb.storedKeys()[testKey(0)] > 0
})
}
func TestPublisherResendsOriginalBytesAfterCallerReusesBuffers(t *testing.T) {
reconnect := make(chan struct{})
allowReconnect := sync.OnceFunc(func() { close(reconnect) })
received := make(chan *mq_pb.DataMessage, 2)
fb := startFakeBroker(t, &fakeBroker{
receivedData: received,
breakStream: func(n int) (int, int, bool) {
if n == 1 {
<-reconnect
}
return 1, 0, n == 0
},
})
publisher := newTestPublisher(t, fb)
defer allowReconnect()
key, value := []byte("key"), []byte("value")
if err := publisher.Publish(key, value); err != nil {
t.Fatal(err)
}
select {
case <-received:
case <-time.After(10 * time.Second):
t.Fatal("first stream did not receive the message")
}
copy(key, "new")
copy(value, "other")
allowReconnect()
if err := publisher.Shutdown(); err != nil {
t.Fatal(err)
}
select {
case replay := <-received:
if string(replay.Key) != "key" || string(replay.Value) != "value" {
t.Fatalf("resend carried key %q, value %q", replay.Key, replay.Value)
}
default:
t.Fatal("no resend on replacement stream")
}
}
func TestPublisherResendsUnackedInOrder(t *testing.T) {
const total = 200
fb := startFakeBroker(t, &fakeBroker{
// the first stream acks 30 messages, takes 20 more without acking, then dies
breakStream: func(n int) (int, int, bool) { return 50, 30, n == 0 },
})
publisher := newTestPublisher(t, fb)
for i := 0; i < total; i++ {
if err := publisher.Publish([]byte(testKey(i)), []byte("v")); err != nil {
t.Fatalf("publish %d: %v", i, err)
}
}
if err := publisher.Shutdown(); err != nil {
t.Fatalf("shutdown: %v", err)
}
stored := fb.storedKeys()
for i := 0; i < total; i++ {
if stored[testKey(i)] == 0 {
t.Fatalf("message %s lost", testKey(i))
}
}
fb.mu.Lock()
defer fb.mu.Unlock()
if len(fb.perStream) < 2 {
t.Fatalf("expected a second stream, got %d", len(fb.perStream))
}
second := fb.perStream[1]
if len(second) == 0 || second[0] != testKey(30) {
t.Fatalf("second stream should start with the first unacked message %s, got %v", testKey(30), second[:min(len(second), 3)])
}
for i := 1; i < len(second); i++ {
if second[i] <= second[i-1] {
t.Fatalf("second stream out of order at %d: %s after %s", i, second[i], second[i-1])
}
}
}
func TestPublishBlocksWhenBufferIsFull(t *testing.T) {
fb := startFakeBroker(t, &fakeBroker{ackGate: make(chan struct{})})
publisher := newTestPublisher(t, fb)
for i := 0; i < maxBufferedMessages; i++ {
if err := publisher.Publish([]byte(testKey(i)), []byte("v")); err != nil {
t.Fatalf("publish %d: %v", i, err)
}
}
published := make(chan error, 1)
go func() {
published <- publisher.Publish([]byte(testKey(maxBufferedMessages)), []byte("v"))
}()
select {
case err := <-published:
t.Fatalf("publish past the bound returned %v before any ack", err)
case <-time.After(300 * time.Millisecond):
}
close(fb.ackGate)
select {
case err := <-published:
if err != nil {
t.Fatalf("publish after acks: %v", err)
}
case <-time.After(10 * time.Second):
t.Fatal("publish still blocked after acks arrived")
}
if err := publisher.Shutdown(); err != nil {
t.Fatalf("shutdown: %v", err)
}
if got := len(fb.storedKeys()); got != maxBufferedMessages+1 {
t.Fatalf("stored %d messages, want %d", got, maxBufferedMessages+1)
}
}
func TestShutdownFlushesQueuedMessages(t *testing.T) {
const total = 500
fb := startFakeBroker(t, &fakeBroker{
breakStream: func(n int) (int, int, bool) { return 120, 100, n == 0 },
})
publisher := newTestPublisher(t, fb)
for i := 0; i < total; i++ {
if err := publisher.Publish([]byte(testKey(i)), []byte("v")); err != nil {
t.Fatalf("publish %d: %v", i, err)
}
}
if err := publisher.FinishPublish(); err != nil {
t.Fatalf("finish: %v", err)
}
if err := publisher.Shutdown(); err != nil {
t.Fatalf("shutdown: %v", err)
}
stored := fb.storedKeys()
for i := 0; i < total; i++ {
if stored[testKey(i)] == 0 {
t.Fatalf("message %s not flushed before Shutdown returned", testKey(i))
}
}
fb.mu.Lock()
ctrlAcked := fb.ctrlAcked
fb.mu.Unlock()
if ctrlAcked == 0 {
t.Fatal("close marker was not delivered")
}
if err := publisher.Publish([]byte("late"), []byte("v")); err == nil {
t.Fatal("publish after Shutdown should fail")
}
}
func TestShutdownGivesUpAfterFlushTimeout(t *testing.T) {
saved := flushTimeout
flushTimeout = 300 * time.Millisecond
defer func() { flushTimeout = saved }()
gate := make(chan struct{})
defer close(gate)
fb := startFakeBroker(t, &fakeBroker{ackGate: gate})
publisher := newTestPublisher(t, fb)
for i := 0; i < 5; i++ {
if err := publisher.Publish([]byte(testKey(i)), []byte("v")); err != nil {
t.Fatalf("publish %d: %v", i, err)
}
}
done := make(chan error, 1)
go func() { done <- publisher.Shutdown() }()
select {
case err := <-done:
if err == nil || !strings.Contains(err.Error(), "5 messages not acknowledged") {
t.Fatalf("shutdown should report 5 unacked messages, got %v", err)
}
case <-time.After(10 * time.Second):
t.Fatal("shutdown did not give up after the flush timeout")
}
}
func TestShutdownCancelsAStalledLookup(t *testing.T) {
saved := flushTimeout
flushTimeout = 300 * time.Millisecond
defer func() { flushTimeout = saved }()
fb := startFakeBroker(t, &fakeBroker{
breakStream: func(n int) (int, int, bool) { return 1, 0, true },
stallLookup: func(n int) bool { return n > 0 },
})
publisher := newTestPublisher(t, fb)
if err := publisher.Publish([]byte(testKey(0)), []byte("v")); err != nil {
t.Fatalf("publish: %v", err)
}
waitFor(t, "a second lookup", func() bool {
lookups, _ := fb.counts()
return lookups >= 2
})
done := make(chan error, 1)
go func() { done <- publisher.Shutdown() }()
select {
case err := <-done:
if err == nil || !strings.Contains(err.Error(), "1 messages not acknowledged") {
t.Fatalf("shutdown should report 1 unacked message, got %v", err)
}
case <-time.After(lookupTimeout / 2):
t.Fatal("shutdown waited on a stalled lookup")
}
}
func TestShutdownIgnoresAnUnackedCloseMarker(t *testing.T) {
saved := flushTimeout
flushTimeout = 300 * time.Millisecond
defer func() { flushTimeout = saved }()
gate := make(chan struct{})
defer close(gate)
fb := startFakeBroker(t, &fakeBroker{ackGate: gate})
publisher := newTestPublisher(t, fb)
publisher.FinishPublish()
if err := publisher.Shutdown(); err != nil {
t.Fatalf("nothing was published, got %v", err)
}
}
type countedCredentials struct {
credentials.TransportCredentials
handshakes atomic.Int32
}
func (c *countedCredentials) ClientHandshake(ctx context.Context, authority string, conn net.Conn) (net.Conn, credentials.AuthInfo, error) {
c.handshakes.Add(1)
return c.TransportCredentials.ClientHandshake(ctx, authority, conn)
}
func TestBootstrapUsesPublisherCredentials(t *testing.T) {
for _, rpc := range []string{"configure", "lookup"} {
t.Run(rpc, func(t *testing.T) {
broker := startFakeBroker(t, &fakeBroker{})
for i := 0; i < 2; i++ {
creds := &countedCredentials{TransportCredentials: insecure.NewCredentials()}
p := &TopicPublisher{
config: &PublisherConfiguration{Brokers: []string{broker.addr}, Topic: topic.NewTopic("test", rpc)},
grpcDialOption: grpc.WithTransportCredentials(creds),
}
var err error
if rpc == "configure" {
err = p.doConfigureTopic()
} else {
_, err = p.doLookupTopicPartitions(t.Context())
}
if err != nil || creds.handshakes.Load() == 0 {
t.Fatalf("publisher %d: handshake count %d, error %v", i, creds.handshakes.Load(), err)
}
}
})
}
}
+356 -199
View File
@@ -3,7 +3,7 @@ package pub_client
import (
"context"
"fmt"
"log"
"io"
"sort"
"sync"
"sync/atomic"
@@ -12,229 +12,384 @@ import (
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/util/buffered_queue"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
)
type EachPartitionError struct {
*mq_pb.BrokerPartitionAssignment
Err error
generation int
}
const (
maxBufferedMessages = 1024 // per partition, queued plus sent but not yet acked
lookupMinBackoff = 100 * time.Millisecond
lookupMaxBackoff = 5 * time.Second
lookupTimeout = 10 * time.Second // per broker, so a stalled one does not hold up the next
)
// EachPartitionPublishJob owns one partition's queue and unacked messages across
// the publish streams opened to whichever broker leads the partition.
type EachPartitionPublishJob struct {
*mq_pb.BrokerPartitionAssignment
stopChan chan bool
wg sync.WaitGroup
generation int
inputQueue *buffered_queue.BufferedQueue[*mq_pb.DataMessage]
inputQueue chan *mq_pb.DataMessage
slots chan struct{}
enqueueLock sync.Mutex
accepted atomic.Int64 // data messages enqueued and not yet acked
inflightLock sync.Mutex
inflight []*mq_pb.DataMessage // sent but not acked, in send order
inputDrained bool
// guarded by TopicPublisher.Mutex
running bool
done bool
cancel context.CancelFunc
wg sync.WaitGroup
}
func (p *TopicPublisher) startSchedulerThread(wg *sync.WaitGroup) error {
func (p *TopicPublisher) startSchedulerThread(wg *sync.WaitGroup) {
defer close(p.schedulerDone)
if err := p.doConfigureTopic(); err != nil {
wg.Done()
return fmt.Errorf("configure topic %s: %v", p.config.Topic, err)
}
glog.V(0).Infof("start scheduler thread for topic %s", p.config.Topic)
log.Printf("start scheduler thread for topic %s", p.config.Topic)
generation := 0
var errChan chan EachPartitionError
for {
glog.V(0).Infof("lookup partitions gen %d topic %s", generation+1, p.config.Topic)
if assignments, err := p.doLookupTopicPartitions(); err == nil {
generation++
glog.V(0).Infof("start generation %d with %d assignments", generation, len(assignments))
if errChan == nil {
errChan = make(chan EachPartitionError, len(assignments))
}
p.onEachAssignments(generation, assignments, errChan)
} else {
glog.Errorf("lookup topic %s: %v", p.config.Topic, err)
time.Sleep(5 * time.Second)
continue
}
if generation == 1 {
wg.Done()
}
// wait for any error to happen. If so, consume all remaining errors, and retry
for {
select {
case eachErr := <-errChan:
glog.Errorf("gen %d publish to topic %s partition %v: %v", eachErr.generation, p.config.Topic, eachErr.Partition, eachErr.Err)
if eachErr.generation < generation {
continue
}
break
}
}
}
}
func (p *TopicPublisher) onEachAssignments(generation int, assignments []*mq_pb.BrokerPartitionAssignment, errChan chan EachPartitionError) {
// TODO assuming this is not re-configured so the partitions are fixed.
sort.Slice(assignments, func(i, j int) bool {
return assignments[i].Partition.RangeStart < assignments[j].Partition.RangeStart
})
var jobs []*EachPartitionPublishJob
hasExistingJob := len(p.jobs) == len(assignments)
for i, assignment := range assignments {
if assignment.LeaderBroker == "" {
continue
}
if hasExistingJob {
var existingJob *EachPartitionPublishJob
existingJob = p.jobs[i]
if pb.ServerAddress(existingJob.BrokerPartitionAssignment.LeaderBroker).Equals(pb.ServerAddress(assignment.LeaderBroker)) {
existingJob.generation = generation
jobs = append(jobs, existingJob)
continue
} else {
if existingJob.LeaderBroker != "" {
close(existingJob.stopChan)
existingJob.LeaderBroker = ""
existingJob.wg.Wait()
}
}
}
// start a go routine to publish to this partition
job := &EachPartitionPublishJob{
BrokerPartitionAssignment: assignment,
stopChan: make(chan bool, 1),
generation: generation,
inputQueue: buffered_queue.NewBufferedQueue[*mq_pb.DataMessage](1024),
}
job.wg.Add(1)
go func(job *EachPartitionPublishJob) {
defer job.wg.Done()
if err := p.doPublishToPartition(job); err != nil {
log.Printf("publish to %s partition %v: %v", p.config.Topic, job.Partition, err)
errChan <- EachPartitionError{assignment, err, generation}
}
}(job)
jobs = append(jobs, job)
// TODO assuming this is not re-configured so the partitions are fixed.
// better just reuse the existing job
p.partition2Buffer.Insert(assignment.Partition.RangeStart, assignment.Partition.RangeStop, job.inputQueue)
}
p.jobs = jobs
}
func (p *TopicPublisher) doPublishToPartition(job *EachPartitionPublishJob) error {
log.Printf("connecting to %v for topic partition %+v", job.LeaderBroker, job.Partition)
grpcConnection, err := grpc.NewClient(job.LeaderBroker, grpc.WithTransportCredentials(insecure.NewCredentials()), p.grpcDialOption)
if err != nil {
return fmt.Errorf("dial broker %s: %v", job.LeaderBroker, err)
}
brokerClient := mq_pb.NewSeaweedMessagingClient(grpcConnection)
stream, err := brokerClient.PublishMessage(context.Background())
if err != nil {
return fmt.Errorf("create publish client: %w", err)
}
publishClient := &PublishClient{
SeaweedMessaging_PublishMessageClient: stream,
Broker: job.LeaderBroker,
}
if err = publishClient.Send(&mq_pb.PublishMessageRequest{
Message: &mq_pb.PublishMessageRequest_Init{
Init: &mq_pb.PublishMessageRequest_InitMessage{
Topic: p.config.Topic.ToPbTopic(),
Partition: job.Partition,
AckInterval: 128,
FollowerBroker: job.FollowerBroker,
PublisherName: p.config.PublisherName,
},
},
}); err != nil {
return fmt.Errorf("send init message: %w", err)
}
// process the hello message
resp, err := stream.Recv()
if err != nil {
return fmt.Errorf("recv init response: %w", err)
}
if resp.Error != "" {
return fmt.Errorf("init response error: %v", resp.Error)
}
var publishedTsNs int64
hasMoreData := int32(1)
var wg sync.WaitGroup
wg.Add(1)
lookupCtx, cancelLookups := context.WithCancel(context.Background())
defer cancelLookups()
go func() {
defer wg.Done()
for {
ackResp, err := publishClient.Recv()
if err != nil {
e, _ := status.FromError(err)
if e.Code() == codes.Unknown && e.Message() == "EOF" {
log.Printf("publish to %s EOF", publishClient.Broker)
return
}
publishClient.Err = err
log.Printf("publish1 to %s error: %v\n", publishClient.Broker, err)
return
}
if ackResp.Error != "" {
publishClient.Err = fmt.Errorf("ack error: %v", ackResp.Error)
log.Printf("publish2 to %s error: %v\n", publishClient.Broker, ackResp.Error)
return
}
if ackResp.AckTsNs > 0 {
log.Printf("ack %d published %d hasMoreData:%d", ackResp.AckTsNs, atomic.LoadInt64(&publishedTsNs), atomic.LoadInt32(&hasMoreData))
}
if atomic.LoadInt64(&publishedTsNs) <= ackResp.AckTsNs && atomic.LoadInt32(&hasMoreData) == 0 {
return
}
select {
case <-p.stopped:
cancelLookups()
case <-lookupCtx.Done():
}
}()
publishCounter := 0
for data, hasData := job.inputQueue.Dequeue(); hasData; data, hasData = job.inputQueue.Dequeue() {
if data.Ctrl != nil && data.Ctrl.IsClose {
// need to set this before sending to brokers, to avoid timing issue
atomic.StoreInt32(&hasMoreData, 0)
ready := false
var backoff time.Duration
for {
if backoff > 0 {
select {
case <-time.After(backoff):
case <-p.stopped:
p.stopJobs()
return
}
}
if err := publishClient.Send(&mq_pb.PublishMessageRequest{
Message: &mq_pb.PublishMessageRequest_Data{
Data: data,
backoff = min(max(2*backoff, lookupMinBackoff), lookupMaxBackoff)
assignments, err := p.doLookupTopicPartitions(lookupCtx)
if err != nil {
glog.Errorf("lookup topic %s: %v", p.config.Topic, err)
continue
}
p.onEachAssignments(assignments)
if !ready {
ready = true
wg.Done()
}
// wait until a partition needs a new leader
healthySince := time.Now()
for !p.hasIdleJob() {
if p.allJobsDone() {
return
}
select {
case <-p.jobEnded:
case <-p.stopped:
p.stopJobs()
return
}
}
if time.Since(healthySince) > lookupMaxBackoff {
backoff = lookupMinBackoff
}
}
}
func (p *TopicPublisher) onEachAssignments(assignments []*mq_pb.BrokerPartitionAssignment) {
sort.Slice(assignments, func(i, j int) bool {
return assignments[i].Partition.RangeStart < assignments[j].Partition.RangeStart
})
p.inputLock.RLock()
defer p.inputLock.RUnlock()
for _, assignment := range assignments {
if assignment.Partition == nil {
continue
}
p.Lock()
job, found := p.partition2Buffer.Find(assignment.Partition.RangeStart, assignment.Partition.RangeStop)
if !found {
job = &EachPartitionPublishJob{
inputQueue: make(chan *mq_pb.DataMessage, maxBufferedMessages+1),
slots: make(chan struct{}, maxBufferedMessages),
}
if p.inputClosed {
close(job.inputQueue)
}
p.jobs = append(p.jobs, job)
p.partition2Buffer.Insert(assignment.Partition.RangeStart, assignment.Partition.RangeStop, job)
}
if job.done {
p.Unlock()
continue
}
if job.running {
if pb.ServerAddress(job.LeaderBroker).Equals(pb.ServerAddress(assignment.LeaderBroker)) {
p.Unlock()
continue
}
cancel := job.cancel
p.Unlock()
cancel()
job.wg.Wait()
p.Lock()
if job.done {
p.Unlock()
continue
}
}
job.BrokerPartitionAssignment = assignment
if assignment.LeaderBroker != "" {
p.startJob(job)
}
p.Unlock()
}
}
// startJob runs one publish stream for the job; the caller holds p.Mutex.
func (p *TopicPublisher) startJob(job *EachPartitionPublishJob) {
ctx, cancel := context.WithCancel(context.Background())
job.running = true
job.cancel = cancel
job.wg.Add(1)
assignment := job.BrokerPartitionAssignment
go func() {
defer job.wg.Done()
err := p.doPublishToPartition(ctx, job, assignment)
cancel()
if err != nil {
glog.Warningf("publish to %s partition %v on %s: %v", p.config.Topic, assignment.Partition, assignment.LeaderBroker, err)
}
p.Lock()
job.running = false
job.done = err == nil
p.Unlock()
select {
case p.jobEnded <- struct{}{}:
default:
}
}()
}
func (p *TopicPublisher) hasIdleJob() bool {
p.Lock()
defer p.Unlock()
for _, job := range p.jobs {
if !job.running && !job.done {
return true
}
}
return false
}
func (p *TopicPublisher) allJobsDone() bool {
p.Lock()
defer p.Unlock()
for _, job := range p.jobs {
if !job.done {
return false
}
}
return true
}
func (p *TopicPublisher) stopJobs() {
p.Lock()
jobs := p.jobs
for _, job := range jobs {
if job.running {
job.cancel()
}
}
p.Unlock()
for _, job := range jobs {
job.wg.Wait()
}
}
// doPublishToPartition resends the job's unacked messages, then publishes its queue,
// until the queue is closed and everything is acked or the stream fails.
func (p *TopicPublisher) doPublishToPartition(ctx context.Context, job *EachPartitionPublishJob, assignment *mq_pb.BrokerPartitionAssignment) error {
glog.V(1).Infof("connecting to %v for topic %s partition %v", assignment.LeaderBroker, p.config.Topic, assignment.Partition)
return pb.WithBrokerGrpcClient(true, assignment.LeaderBroker, p.grpcDialOption, func(client mq_pb.SeaweedMessagingClient) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
stream, err := client.PublishMessage(ctx)
if err != nil {
return fmt.Errorf("create publish client: %w", err)
}
if err = stream.Send(&mq_pb.PublishMessageRequest{
Message: &mq_pb.PublishMessageRequest_Init{
Init: &mq_pb.PublishMessageRequest_InitMessage{
Topic: p.config.Topic.ToPbTopic(),
Partition: assignment.Partition,
AckInterval: 128,
FollowerBroker: assignment.FollowerBroker,
PublisherName: p.config.PublisherName,
},
},
}); err != nil {
return fmt.Errorf("send publish data: %w", err)
return fmt.Errorf("send init message: %w", err)
}
publishCounter++
atomic.StoreInt64(&publishedTsNs, data.TsNs)
}
if publishCounter > 0 {
wg.Wait()
} else {
// CloseSend would cancel the context on the server side
if err := publishClient.CloseSend(); err != nil {
return fmt.Errorf("close send: %w", err)
resp, err := stream.Recv()
if err != nil {
return fmt.Errorf("recv init response: %w", err)
}
if err = responseError(resp); err != nil {
return fmt.Errorf("init: %w", err)
}
finished := make(chan struct{})
var finishOnce sync.Once
finish := func() { finishOnce.Do(func() { close(finished) }) }
ackErr := make(chan error, 1)
var acks sync.WaitGroup
acks.Add(1)
go func() {
defer acks.Done()
err := job.receiveAcks(stream, finish)
if err != nil {
// unblock a Send stuck on flow control
cancel()
}
ackErr <- err
}()
defer acks.Wait()
defer cancel()
send := func(data *mq_pb.DataMessage) error {
if err := stream.Send(&mq_pb.PublishMessageRequest{
Message: &mq_pb.PublishMessageRequest_Data{
Data: data,
},
}); err != nil {
return fmt.Errorf("send publish data: %w", err)
}
return nil
}
for _, data := range job.unacked() {
if err := send(data); err != nil {
return err
}
}
queue := job.inputQueue
for {
select {
case data, ok := <-queue:
if !ok {
queue = nil
if job.markDrained() {
finish()
}
continue
}
job.addInflight(data)
if err := send(data); err != nil {
return err
}
case <-finished:
// the broker answers the close with EOF, which receiveAcks takes as success
finished = nil
if err := stream.CloseSend(); err != nil {
return fmt.Errorf("close send: %w", err)
}
case err := <-ackErr:
return err
}
}
})
}
func responseError(resp *mq_pb.PublishMessageResponse) error {
if resp.Error != "" || resp.ErrorCode != 0 {
return fmt.Errorf("broker error %d: %s", resp.ErrorCode, resp.Error)
}
log.Printf("published %d messages to %v for topic partition %+v", publishCounter, job.LeaderBroker, job.Partition)
return nil
}
// receiveAcks calls finish once the input is drained and every message is acked,
// and returns nil when the broker then ends the stream.
func (job *EachPartitionPublishJob) receiveAcks(stream mq_pb.SeaweedMessaging_PublishMessageClient, finish func()) error {
for {
resp, err := stream.Recv()
if err == io.EOF && job.isFinished() {
return nil
}
if err != nil {
return fmt.Errorf("receive ack: %w", err)
}
if err = responseError(resp); err != nil {
return err
}
if resp.AckTsNs > 0 && job.ack(resp.AckTsNs) {
finish()
}
}
}
func (job *EachPartitionPublishJob) addInflight(data *mq_pb.DataMessage) {
job.inflightLock.Lock()
job.inflight = append(job.inflight, data)
job.inflightLock.Unlock()
}
func (job *EachPartitionPublishJob) unacked() []*mq_pb.DataMessage {
job.inflightLock.Lock()
defer job.inflightLock.Unlock()
return append([]*mq_pb.DataMessage(nil), job.inflight...)
}
// ack drops every in-flight message up to tsNs and reports whether the job is finished.
func (job *EachPartitionPublishJob) ack(tsNs int64) bool {
job.inflightLock.Lock()
defer job.inflightLock.Unlock()
n := 0
for n < len(job.inflight) && job.inflight[n].TsNs <= tsNs {
if job.inflight[n].Ctrl == nil {
<-job.slots
job.accepted.Add(-1)
}
job.inflight[n] = nil
n++
}
job.inflight = job.inflight[n:]
return job.inputDrained && len(job.inflight) == 0
}
// markDrained records that the closed input is empty and reports whether nothing is left to ack.
func (job *EachPartitionPublishJob) markDrained() bool {
job.inflightLock.Lock()
defer job.inflightLock.Unlock()
job.inputDrained = true
return len(job.inflight) == 0
}
func (job *EachPartitionPublishJob) isFinished() bool {
job.inflightLock.Lock()
defer job.inflightLock.Unlock()
return job.inputDrained && len(job.inflight) == 0
}
// unackedCount counts accepted data messages not yet acked, not a Publish still waiting to enqueue.
func (job *EachPartitionPublishJob) unackedCount() int {
return int(job.accepted.Load())
}
func (p *TopicPublisher) doConfigureTopic() (err error) {
if len(p.config.Brokers) == 0 {
return fmt.Errorf("topic configuring found no bootstrap brokers")
}
var lastErr error
for _, brokerAddress := range p.config.Brokers {
err = pb.WithBrokerGrpcClient(false,
// The configured dial option belongs to this publisher. A process-wide
// address cache can reuse a connection opened with different credentials.
err = pb.WithBrokerGrpcClient(true,
brokerAddress,
p.grpcDialOption,
func(client mq_pb.SeaweedMessagingClient) error {
@@ -259,17 +414,19 @@ func (p *TopicPublisher) doConfigureTopic() (err error) {
return nil
}
func (p *TopicPublisher) doLookupTopicPartitions() (assignments []*mq_pb.BrokerPartitionAssignment, err error) {
func (p *TopicPublisher) doLookupTopicPartitions(ctx context.Context) (assignments []*mq_pb.BrokerPartitionAssignment, err error) {
if len(p.config.Brokers) == 0 {
return nil, fmt.Errorf("lookup found no bootstrap brokers")
}
var lastErr error
for _, brokerAddress := range p.config.Brokers {
err := pb.WithBrokerGrpcClient(false,
err := pb.WithBrokerGrpcClient(true,
brokerAddress,
p.grpcDialOption,
func(client mq_pb.SeaweedMessagingClient) error {
lookupResp, err := client.LookupTopicBrokers(context.Background(),
ctx, cancel := context.WithTimeout(ctx, lookupTimeout)
defer cancel()
lookupResp, err := client.LookupTopicBrokers(ctx,
&mq_pb.LookupTopicBrokersRequest{
Topic: p.config.Topic.ToPbTopic(),
})
+17 -11
View File
@@ -58,6 +58,7 @@ func NewBrokerClientWithFilerAccessor(brokerAddress string, filerClientAccessor
return &BrokerClient{
filerClientAccessor: filerClientAccessor,
brokerAddress: brokerAddress,
grpcDialOption: grpcDialOption,
conn: conn,
client: client,
publishers: make(map[string]*BrokerPublisherSession),
@@ -76,12 +77,9 @@ func (bc *BrokerClient) Close() error {
// Close all publisher streams
bc.publishersLock.Lock()
for key, session := range bc.publishers {
if session.Stream != nil {
_ = session.Stream.CloseSend()
}
delete(bc.publishers, key)
}
// Cancelling bc.ctx above stops every publish stream, including remote
// leaders. CloseSend must not race a Send in progress.
clear(bc.publishers)
bc.publishersLock.Unlock()
// Close all subscriber streams
@@ -146,21 +144,29 @@ func (bc *BrokerClient) GetPartitionRangeInfo(topic string, partition int32) (*P
}
// Get the actual partition assignment for this Kafka partition
actualPartition, err := bc.getActualPartitionAssignment(topic, partition)
actualPartition, leader, err := bc.getActualPartitionAssignment(bc.ctx, topic, partition)
if err != nil {
return nil, fmt.Errorf("failed to get actual partition assignment: %v", err)
}
// Call the broker's gRPC method
resp, err := bc.client.GetPartitionRangeInfo(context.Background(), &mq_pb.GetPartitionRangeInfoRequest{
Topic: pbTopic,
Partition: actualPartition,
// Only the leader's log buffer holds the unflushed tail of the range.
var resp *mq_pb.GetPartitionRangeInfoResponse
err = bc.withLeaderClient(leader, func(client mq_pb.SeaweedMessagingClient) (rpcErr error) {
resp, rpcErr = client.GetPartitionRangeInfo(bc.ctx, &mq_pb.GetPartitionRangeInfoRequest{
Topic: pbTopic,
Partition: actualPartition,
})
return rpcErr
})
if err != nil {
if bc.ctx.Err() == nil {
bc.invalidatePartitionAssignment(topic)
}
return nil, fmt.Errorf("failed to get partition range info from broker: %v", err)
}
if resp.Error != "" {
bc.invalidatePartitionAssignment(topic)
return nil, fmt.Errorf("broker error: %s", resp.Error)
}
@@ -25,7 +25,7 @@ func (bc *BrokerClient) FetchMessagesStateless(ctx context.Context, topic string
topic, partition, startOffset, maxRecords)
// Get actual partition assignment from broker
actualPartition, err := bc.getActualPartitionAssignment(topic, partition)
actualPartition, leader, err := bc.getActualPartitionAssignment(ctx, topic, partition)
if err != nil {
return nil, fmt.Errorf("failed to get partition assignment: %v", err)
}
@@ -51,7 +51,7 @@ func (bc *BrokerClient) FetchMessagesStateless(ctx context.Context, topic string
// Note: We use a default of 100ms above, but if context has shorter timeout, use that
// Call FetchMessage RPC (simple request/response)
resp, err := bc.client.FetchMessage(ctx, req)
resp, err := bc.fetchMessage(ctx, leader, req)
if err != nil {
return nil, fmt.Errorf("FetchMessage RPC failed: %v", err)
}
@@ -66,7 +66,7 @@ func (bc *BrokerClient) FetchMessagesStateless(ctx context.Context, topic string
// Retry with adjusted offset
req.StartOffset = resp.LogStartOffset
resp, err = bc.client.FetchMessage(ctx, req)
resp, err = bc.fetchMessage(ctx, leader, req)
if err != nil {
return nil, fmt.Errorf("FetchMessage RPC failed on retry: %v", err)
}
@@ -122,7 +122,7 @@ func (bc *BrokerClient) FetchMessagesStateless(ctx context.Context, topic string
// This is useful for Kafka clients to track consumer lag
func (bc *BrokerClient) GetPartitionHighWaterMark(ctx context.Context, topic string, partition int32) (int64, error) {
// Use FetchMessage with 0 maxRecords to just get metadata
actualPartition, err := bc.getActualPartitionAssignment(topic, partition)
actualPartition, leader, err := bc.getActualPartitionAssignment(ctx, topic, partition)
if err != nil {
return 0, fmt.Errorf("failed to get partition assignment: %v", err)
}
@@ -141,7 +141,7 @@ func (bc *BrokerClient) GetPartitionHighWaterMark(ctx context.Context, topic str
ConsumerId: "hwm-check",
}
resp, err := bc.client.FetchMessage(ctx, req)
resp, err := bc.fetchMessage(ctx, leader, req)
if err != nil {
return 0, fmt.Errorf("FetchMessage RPC failed: %v", err)
}
@@ -156,7 +156,7 @@ func (bc *BrokerClient) GetPartitionHighWaterMark(ctx context.Context, topic str
// GetPartitionLogStartOffset returns the earliest offset available in a partition
// This is useful for Kafka clients to know the valid offset range
func (bc *BrokerClient) GetPartitionLogStartOffset(ctx context.Context, topic string, partition int32) (int64, error) {
actualPartition, err := bc.getActualPartitionAssignment(topic, partition)
actualPartition, leader, err := bc.getActualPartitionAssignment(ctx, topic, partition)
if err != nil {
return 0, fmt.Errorf("failed to get partition assignment: %v", err)
}
@@ -175,7 +175,7 @@ func (bc *BrokerClient) GetPartitionLogStartOffset(ctx context.Context, topic st
ConsumerId: "lso-check",
}
resp, err := bc.client.FetchMessage(ctx, req)
resp, err := bc.fetchMessage(ctx, leader, req)
if err != nil {
return 0, fmt.Errorf("FetchMessage RPC failed: %v", err)
}
@@ -186,3 +186,16 @@ func (bc *BrokerClient) GetPartitionLogStartOffset(ctx context.Context, topic st
return resp.LogStartOffset, nil
}
// fetchMessage reads from the partition's leader, which holds its unflushed messages.
// A leader that is gone or no longer has the partition drops the cached assignment.
func (bc *BrokerClient) fetchMessage(ctx context.Context, leader string, req *mq_pb.FetchMessageRequest) (resp *mq_pb.FetchMessageResponse, err error) {
err = bc.withLeaderClient(leader, func(client mq_pb.SeaweedMessagingClient) error {
resp, err = client.FetchMessage(ctx, req)
return err
})
if ctx.Err() == nil && (err != nil || resp.ErrorCode == 1) {
bc.invalidatePartitionAssignment(req.Topic.GetName())
}
return resp, err
}
+159 -167
View File
@@ -3,11 +3,11 @@ package integration
import (
"context"
"fmt"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/mq/pub_balancer"
"github.com/seaweedfs/seaweedfs/weed/pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
)
@@ -20,25 +20,6 @@ func (bc *BrokerClient) PublishRecord(ctx context.Context, topic string, partiti
return 0, fmt.Errorf("context cancelled before publish: %w", err)
}
session, err := bc.getOrCreatePublisher(topic, partition)
if err != nil {
return 0, err
}
if session.Stream == nil {
return 0, fmt.Errorf("publisher session stream cannot be nil")
}
// CRITICAL: Lock to prevent concurrent Send/Recv causing response mix-ups
// Without this, two concurrent publishes can steal each other's offsets
session.mu.Lock()
defer session.mu.Unlock()
// Check context after acquiring lock
if err := ctx.Err(); err != nil {
return 0, fmt.Errorf("context cancelled after lock: %w", err)
}
// Send data message using broker API format
dataMsg := &mq_pb.DataMessage{
Key: key,
@@ -60,55 +41,9 @@ func (bc *BrokerClient) PublishRecord(ctx context.Context, topic string, partiti
glog.V(1).Infof("[PUBLISH] topic=%s partition=%d key=%s valueLen=%d valuePreview=%q timestamp=%d",
topic, partition, string(key), len(value), valuePreview, timestamp)
// CRITICAL: Use a goroutine with context checking to enforce timeout
// gRPC streams may not respect context deadlines automatically
// We need to monitor the context and timeout the operation if needed
sendErrChan := make(chan error, 1)
go func() {
sendErrChan <- session.Stream.Send(&mq_pb.PublishMessageRequest{
Message: &mq_pb.PublishMessageRequest_Data{
Data: dataMsg,
},
})
}()
select {
case err := <-sendErrChan:
if err != nil {
return 0, fmt.Errorf("failed to send data: %v", err)
}
case <-ctx.Done():
return 0, fmt.Errorf("context cancelled while sending: %w", ctx.Err())
}
// Read acknowledgment with context timeout enforcement
recvErrChan := make(chan interface{}, 1)
go func() {
resp, err := session.Stream.Recv()
if err != nil {
recvErrChan <- err
} else {
recvErrChan <- resp
}
}()
var resp *mq_pb.PublishMessageResponse
select {
case result := <-recvErrChan:
if err, isErr := result.(error); isErr {
return 0, fmt.Errorf("failed to receive ack: %v", err)
}
resp = result.(*mq_pb.PublishMessageResponse)
case <-ctx.Done():
return 0, fmt.Errorf("context cancelled while receiving: %w", ctx.Err())
}
// Handle structured broker errors
if kafkaErrorCode, errorMsg, handleErr := HandleBrokerResponse(resp); handleErr != nil {
return 0, handleErr
} else if kafkaErrorCode != 0 {
// Return error with Kafka error code information for better debugging
return 0, fmt.Errorf("broker error (Kafka code %d): %s", kafkaErrorCode, errorMsg)
resp, err := bc.publishData(ctx, topic, partition, dataMsg)
if err != nil {
return 0, err
}
// Use the assigned offset from SMQ, not the timestamp
@@ -124,24 +59,6 @@ func (bc *BrokerClient) PublishRecordValue(ctx context.Context, topic string, pa
return 0, fmt.Errorf("context cancelled before publish: %w", err)
}
session, err := bc.getOrCreatePublisher(topic, partition)
if err != nil {
return 0, err
}
if session.Stream == nil {
return 0, fmt.Errorf("publisher session stream cannot be nil")
}
// CRITICAL: Lock to prevent concurrent Send/Recv causing response mix-ups
session.mu.Lock()
defer session.mu.Unlock()
// Check context after acquiring lock
if err := ctx.Err(); err != nil {
return 0, fmt.Errorf("context cancelled after lock: %w", err)
}
// Send data message with RecordValue in the Value field
dataMsg := &mq_pb.DataMessage{
Key: key,
@@ -149,78 +66,114 @@ func (bc *BrokerClient) PublishRecordValue(ctx context.Context, topic string, pa
TsNs: timestamp,
}
if err := session.Stream.Send(&mq_pb.PublishMessageRequest{
Message: &mq_pb.PublishMessageRequest_Data{
Data: dataMsg,
},
}); err != nil {
return 0, fmt.Errorf("failed to send RecordValue data: %v", err)
}
// Read acknowledgment
resp, err := session.Stream.Recv()
resp, err := bc.publishData(ctx, topic, partition, dataMsg)
if err != nil {
return 0, fmt.Errorf("failed to receive RecordValue ack: %v", err)
}
// Handle structured broker errors
if kafkaErrorCode, errorMsg, handleErr := HandleBrokerResponse(resp); handleErr != nil {
return 0, handleErr
} else if kafkaErrorCode != 0 {
// Return error with Kafka error code information for better debugging
return 0, fmt.Errorf("RecordValue broker error (Kafka code %d): %s", kafkaErrorCode, errorMsg)
return 0, fmt.Errorf("RecordValue: %w", err)
}
// Use the assigned offset from SMQ, not the timestamp
return resp.AssignedOffset, nil
}
// getOrCreatePublisher gets or creates a publisher stream for a topic-partition
func (bc *BrokerClient) getOrCreatePublisher(topic string, partition int32) (*BrokerPublisherSession, error) {
// publishData sends one message on the partition's publish stream and waits for its ack.
// A call that fails or is cancelled drops the session, so a late ack never answers the next call.
func (bc *BrokerClient) publishData(ctx context.Context, topic string, partition int32, dataMsg *mq_pb.DataMessage) (*mq_pb.PublishMessageResponse, error) {
key := fmt.Sprintf("%s-%d", topic, partition)
// Try to get existing publisher
bc.publishersLock.RLock()
if session, exists := bc.publishers[key]; exists {
bc.publishersLock.RUnlock()
return session, nil
bc.publishersLock.Lock()
if bc.publishGates == nil {
bc.publishGates = make(map[string]chan struct{})
}
gate := bc.publishGates[key]
if gate == nil {
gate = make(chan struct{}, 1)
bc.publishGates[key] = gate
}
bc.publishersLock.Unlock()
// Serialize both setup and Send/Recv. A caller waiting behind a stalled
// publish must be able to leave without cancelling the other caller.
select {
case gate <- struct{}{}:
defer func() { <-gate }()
case <-ctx.Done():
return nil, ctx.Err()
case <-bc.ctx.Done():
return nil, bc.ctx.Err()
}
if err := ctx.Err(); err != nil {
return nil, err
}
session, err := bc.getOrCreatePublisher(ctx, key, topic, partition)
if err != nil {
return nil, err
}
bc.publishersLock.RUnlock()
// CRITICAL FIX: Prevent multiple concurrent attempts to create the same publisher
// Use a creation lock that is specific to each topic-partition pair
// This ensures only ONE goroutine tries to create/initialize for each publisher
if bc.publisherCreationLocks == nil {
bc.publishersLock.Lock()
if bc.publisherCreationLocks == nil {
bc.publisherCreationLocks = make(map[string]*sync.Mutex)
// gRPC stream calls ignore ctx, so wait for them here and drop the stream on cancel
type result struct {
resp *mq_pb.PublishMessageResponse
err error
}
done := make(chan result, 1)
go func() {
if err := session.Stream.Send(&mq_pb.PublishMessageRequest{
Message: &mq_pb.PublishMessageRequest_Data{
Data: dataMsg,
},
}); err != nil {
done <- result{err: fmt.Errorf("failed to send data: %w", err)}
return
}
bc.publishersLock.Unlock()
}
bc.publishersLock.RLock()
creationLock, exists := bc.publisherCreationLocks[key]
if !exists {
// Need to create a creation lock for this topic-partition
bc.publishersLock.RUnlock()
bc.publishersLock.Lock()
// Double-check if someone else created it
if lock, exists := bc.publisherCreationLocks[key]; exists {
creationLock = lock
} else {
creationLock = &sync.Mutex{}
bc.publisherCreationLocks[key] = creationLock
resp, err := session.Stream.Recv()
if err != nil {
err = fmt.Errorf("failed to receive ack: %w", err)
}
bc.publishersLock.Unlock()
} else {
bc.publishersLock.RUnlock()
done <- result{resp: resp, err: err}
}()
select {
case r := <-done:
if r.err != nil {
bc.dropPublisher(session)
bc.invalidatePartitionAssignment(topic)
return nil, fmt.Errorf("%w: %v", ErrNotLeaderOrFollower, r.err)
}
if kafkaErrorCode, errorMsg, _ := HandleBrokerResponse(r.resp); kafkaErrorCode != 0 {
// the broker ends the stream after an error response
bc.dropPublisher(session)
return nil, bc.brokerResponseError(topic, kafkaErrorCode, errorMsg)
}
return r.resp, nil
case <-ctx.Done():
bc.dropPublisher(session)
return nil, fmt.Errorf("context cancelled while publishing: %w", ctx.Err())
}
}
// Acquire the creation lock - only ONE goroutine will proceed
creationLock.Lock()
defer creationLock.Unlock()
// brokerResponseError wraps ErrNotLeaderOrFollower when the code says the leader moved or is unreachable.
func (bc *BrokerClient) brokerResponseError(topic string, kafkaErrorCode int16, errorMsg string) error {
if leaderUnavailable(kafkaErrorCode) {
bc.invalidatePartitionAssignment(topic)
return fmt.Errorf("%w: broker error (Kafka code %d): %s", ErrNotLeaderOrFollower, kafkaErrorCode, errorMsg)
}
return fmt.Errorf("broker error (Kafka code %d): %s", kafkaErrorCode, errorMsg)
}
// Double-check if publisher was created while we were waiting for the lock
// dropPublisher retires a session so the next publish to its partition opens a fresh stream.
func (bc *BrokerClient) dropPublisher(session *BrokerPublisherSession) {
if session.cancel != nil {
session.cancel()
}
key := fmt.Sprintf("%s-%d", session.Topic, session.Partition)
bc.publishersLock.Lock()
if bc.publishers[key] == session {
delete(bc.publishers, key)
}
bc.publishersLock.Unlock()
}
// getOrCreatePublisher gets or creates a publisher stream for a topic-partition
// ctx bounds only opening the stream; the session outlives the call.
func (bc *BrokerClient) getOrCreatePublisher(ctx context.Context, key, topic string, partition int32) (*BrokerPublisherSession, error) {
// The caller holds the publish gate for this partition.
bc.publishersLock.RLock()
if session, exists := bc.publishers[key]; exists {
bc.publishersLock.RUnlock()
@@ -229,15 +182,29 @@ func (bc *BrokerClient) getOrCreatePublisher(topic string, partition int32) (*Br
bc.publishersLock.RUnlock()
// Create the stream
stream, err := bc.client.PublishMessage(bc.ctx)
if err != nil {
return nil, fmt.Errorf("failed to create publish stream: %v", err)
streamCtx, cancel := context.WithCancel(bc.ctx)
stopSetupCancel := context.AfterFunc(ctx, cancel)
fail := func(err error) error {
stopSetupCancel()
cancel()
if ctx.Err() != nil {
return fmt.Errorf("context cancelled while opening publish stream: %w", ctx.Err())
}
bc.invalidatePartitionAssignment(topic)
return err
}
// Get the actual partition assignment from the broker
actualPartition, err := bc.getActualPartitionAssignment(topic, partition)
actualPartition, leader, err := bc.getActualPartitionAssignment(streamCtx, topic, partition)
if err != nil {
return nil, fmt.Errorf("failed to get actual partition assignment: %v", err)
return nil, fail(fmt.Errorf("failed to get actual partition assignment: %w", err))
}
var stream mq_pb.SeaweedMessaging_PublishMessageClient
err = bc.withLeaderClient(leader, func(client mq_pb.SeaweedMessagingClient) error {
var streamErr error
stream, streamErr = client.PublishMessage(streamCtx)
return streamErr
})
if err != nil {
return nil, fail(fmt.Errorf("%w: failed to create publish stream to %s: %v", ErrNotLeaderOrFollower, leader, err))
}
// Send init message
@@ -254,32 +221,51 @@ func (bc *BrokerClient) getOrCreatePublisher(topic string, partition int32) (*Br
},
},
}); err != nil {
return nil, fmt.Errorf("failed to send init message: %v", err)
return nil, fail(fmt.Errorf("%w: failed to send init message: %v", ErrNotLeaderOrFollower, err))
}
// Consume the "hello" message sent by broker after init
helloResp, err := stream.Recv()
if err != nil {
return nil, fmt.Errorf("failed to receive hello message: %v", err)
return nil, fail(fmt.Errorf("%w: failed to receive hello message: %v", ErrNotLeaderOrFollower, err))
}
if helloResp.ErrorCode != 0 {
return nil, fmt.Errorf("broker init error (code %d): %s", helloResp.ErrorCode, helloResp.Error)
if kafkaErrorCode, errorMsg, _ := HandleBrokerResponse(helloResp); kafkaErrorCode != 0 {
stopSetupCancel()
cancel()
return nil, fmt.Errorf("broker init: %w", bc.brokerResponseError(topic, kafkaErrorCode, errorMsg))
}
if !stopSetupCancel() {
return nil, fmt.Errorf("context cancelled while opening publish stream: %w", ctx.Err())
}
session := &BrokerPublisherSession{
Topic: topic,
Partition: partition,
Stream: stream,
cancel: cancel,
}
// Store in the map under the publishersLock
bc.publishersLock.Lock()
if err := bc.ctx.Err(); err != nil {
bc.publishersLock.Unlock()
cancel()
return nil, err
}
bc.publishers[key] = session
bc.publishersLock.Unlock()
return session, nil
}
// withLeaderClient runs fn against the partition's leader, or the gateway's broker when the leader is unknown.
func (bc *BrokerClient) withLeaderClient(leader string, fn func(mq_pb.SeaweedMessagingClient) error) error {
if leader == "" || pb.ServerAddress(leader).Equals(pb.ServerAddress(bc.brokerAddress)) {
return fn(bc.client)
}
return pb.WithBrokerGrpcClient(false, leader, bc.grpcDialOption, fn)
}
// ClosePublisher closes a specific publisher session
func (bc *BrokerClient) ClosePublisher(topic string, partition int32) error {
key := fmt.Sprintf("%s-%d", topic, partition)
@@ -292,16 +278,16 @@ func (bc *BrokerClient) ClosePublisher(topic string, partition int32) error {
return nil // Already closed or never existed
}
if session.Stream != nil {
session.Stream.CloseSend()
if session.cancel != nil {
session.cancel()
}
delete(bc.publishers, key)
return nil
}
// getActualPartitionAssignment looks up the actual partition assignment from the broker configuration
// getActualPartitionAssignment looks up the actual partition assignment and its leader broker
// Uses cache to avoid expensive LookupTopicBrokers calls on every fetch (13.5% CPU overhead!)
func (bc *BrokerClient) getActualPartitionAssignment(topic string, kafkaPartition int32) (*schema_pb.Partition, error) {
func (bc *BrokerClient) getActualPartitionAssignment(ctx context.Context, topic string, kafkaPartition int32) (*schema_pb.Partition, string, error) {
// Check cache first
bc.partitionAssignmentCacheMu.RLock()
if entry, found := bc.partitionAssignmentCache[topic]; found {
@@ -317,18 +303,18 @@ func (bc *BrokerClient) getActualPartitionAssignment(topic string, kafkaPartitio
// Cache miss or expired - lookup from broker
glog.V(4).Infof("Partition assignment cache MISS for topic %s, calling LookupTopicBrokers", topic)
lookupResp, err := bc.client.LookupTopicBrokers(bc.ctx, &mq_pb.LookupTopicBrokersRequest{
lookupResp, err := bc.client.LookupTopicBrokers(ctx, &mq_pb.LookupTopicBrokersRequest{
Topic: &schema_pb.Topic{
Namespace: "kafka",
Name: topic,
},
})
if err != nil {
return nil, fmt.Errorf("failed to lookup topic brokers: %v", err)
return nil, "", fmt.Errorf("failed to lookup topic brokers: %w", err)
}
if len(lookupResp.BrokerPartitionAssignments) == 0 {
return nil, fmt.Errorf("no partition assignments found for topic %s", topic)
return nil, "", fmt.Errorf("no partition assignments found for topic %s", topic)
}
// Cache the assignments
@@ -344,11 +330,17 @@ func (bc *BrokerClient) getActualPartitionAssignment(topic string, kafkaPartitio
return bc.findPartitionInAssignments(topic, kafkaPartition, lookupResp.BrokerPartitionAssignments)
}
// findPartitionInAssignments finds the SeaweedFS partition for a given Kafka partition ID
func (bc *BrokerClient) findPartitionInAssignments(topic string, kafkaPartition int32, assignments []*mq_pb.BrokerPartitionAssignment) (*schema_pb.Partition, error) {
func (bc *BrokerClient) invalidatePartitionAssignment(topic string) {
bc.partitionAssignmentCacheMu.Lock()
delete(bc.partitionAssignmentCache, topic)
bc.partitionAssignmentCacheMu.Unlock()
}
// findPartitionInAssignments finds the SeaweedFS partition and its leader for a given Kafka partition ID
func (bc *BrokerClient) findPartitionInAssignments(topic string, kafkaPartition int32, assignments []*mq_pb.BrokerPartitionAssignment) (*schema_pb.Partition, string, error) {
totalPartitions := int32(len(assignments))
if kafkaPartition >= totalPartitions {
return nil, fmt.Errorf("kafka partition %d out of range, topic %s has %d partitions",
return nil, "", fmt.Errorf("kafka partition %d out of range, topic %s has %d partitions",
kafkaPartition, topic, totalPartitions)
}
@@ -379,7 +371,7 @@ func (bc *BrokerClient) findPartitionInAssignments(topic string, kafkaPartition
glog.V(1).Infof("found matching partition assignment for %s[%d]: {RingSize: %d, RangeStart: %d, RangeStop: %d, UnixTimeNs: %d}",
topic, kafkaPartition, assignment.Partition.RingSize, assignment.Partition.RangeStart,
assignment.Partition.RangeStop, assignment.Partition.UnixTimeNs)
return assignment.Partition, nil
return assignment.Partition, assignment.LeaderBroker, nil
}
}
@@ -394,6 +386,6 @@ func (bc *BrokerClient) findPartitionInAssignments(topic string, kafkaPartition
}
}
return nil, fmt.Errorf("no broker assignment found for Kafka partition %d with expected range [%d, %d]",
return nil, "", fmt.Errorf("no broker assignment found for Kafka partition %d with expected range [%d, %d]",
kafkaPartition, expectedRangeStart, expectedRangeStop)
}
@@ -0,0 +1,417 @@
package integration
import (
"context"
"errors"
"net"
"strconv"
"sync"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/mq/pub_balancer"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
// publishBroker acks each message with its key parsed as the offset.
type publishBroker struct {
mq_pb.UnimplementedSeaweedMessagingServer
addr string
// notLeader makes the broker refuse every publish stream the way a non-leader does
notLeader bool
// first returns the response stream n sends for its first data message,
// nil to ack normally, or hold=true to never answer it
first func(n int) (resp *mq_pb.PublishMessageResponse, hold bool)
// holdHello, when set, keeps stream n from answering its init
holdHello func(n int) bool
holdLookup chan struct{}
mu sync.Mutex
streams int
leader string // reported by lookups; defaults to addr
}
func (b *publishBroker) setLeader(leader string) {
b.mu.Lock()
b.leader = leader
b.mu.Unlock()
}
func startPublishBroker(t *testing.T, b *publishBroker) *publishBroker {
t.Helper()
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
b.addr = listener.Addr().String()
server := grpc.NewServer()
mq_pb.RegisterSeaweedMessagingServer(server, b)
go server.Serve(listener)
t.Cleanup(server.Stop)
return b
}
func (b *publishBroker) LookupTopicBrokers(ctx context.Context, req *mq_pb.LookupTopicBrokersRequest) (*mq_pb.LookupTopicBrokersResponse, error) {
if b.holdLookup != nil {
close(b.holdLookup)
<-ctx.Done()
return nil, ctx.Err()
}
b.mu.Lock()
leader := b.leader
b.mu.Unlock()
if leader == "" {
leader = b.addr
}
return &mq_pb.LookupTopicBrokersResponse{
Topic: req.Topic,
BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{{
Partition: &schema_pb.Partition{
RingSize: pub_balancer.MaxPartitionCount,
RangeStart: 0,
RangeStop: pub_balancer.MaxPartitionCount,
},
LeaderBroker: leader,
}},
}, nil
}
func (b *publishBroker) PublishMessage(stream mq_pb.SeaweedMessaging_PublishMessageServer) error {
if _, err := stream.Recv(); err != nil {
return err
}
b.mu.Lock()
n := b.streams
b.streams++
b.mu.Unlock()
if b.holdHello != nil && b.holdHello(n) {
<-stream.Context().Done()
return nil
}
if b.notLeader {
return stream.Send(&mq_pb.PublishMessageResponse{ErrorCode: 6, Error: "not the leader for this partition"})
}
if err := stream.Send(&mq_pb.PublishMessageResponse{}); err != nil {
return err
}
for i := 0; ; i++ {
req, err := stream.Recv()
if err != nil {
return nil
}
data := req.GetData()
if i == 0 && b.first != nil {
if resp, hold := b.first(n); hold {
<-stream.Context().Done()
return nil
} else if resp != nil {
return stream.Send(resp)
}
}
offset, _ := strconv.ParseInt(string(data.Key), 10, 64)
if err := stream.Send(&mq_pb.PublishMessageResponse{AckTsNs: data.TsNs, AssignedOffset: offset}); err != nil {
return err
}
}
}
// FetchMessage serves reads only where the partition is led, like a broker that has no local copy elsewhere.
func (b *publishBroker) FetchMessage(ctx context.Context, req *mq_pb.FetchMessageRequest) (*mq_pb.FetchMessageResponse, error) {
b.mu.Lock()
leader := b.leader
b.mu.Unlock()
if b.notLeader || (leader != "" && leader != b.addr) {
return &mq_pb.FetchMessageResponse{Error: "partition not found", ErrorCode: 1}, nil
}
return &mq_pb.FetchMessageResponse{HighWaterMark: 7}, nil
}
// GetPartitionRangeInfo answers from the broker's own log buffer, which holds the tail only where the partition is led.
func (b *publishBroker) GetPartitionRangeInfo(ctx context.Context, req *mq_pb.GetPartitionRangeInfoRequest) (*mq_pb.GetPartitionRangeInfoResponse, error) {
b.mu.Lock()
leader := b.leader
b.mu.Unlock()
if b.notLeader || (leader != "" && leader != b.addr) {
return &mq_pb.GetPartitionRangeInfoResponse{Error: "partition not found"}, nil
}
return &mq_pb.GetPartitionRangeInfoResponse{OffsetRange: &mq_pb.OffsetRangeInfo{HighWaterMark: 7}}, nil
}
func (b *publishBroker) streamCount() int {
b.mu.Lock()
defer b.mu.Unlock()
return b.streams
}
func newPublishTestClient(t *testing.T, addr string) *BrokerClient {
t.Helper()
conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatalf("dial: %v", err)
}
ctx, cancel := context.WithCancel(context.Background())
bc := &BrokerClient{
brokerAddress: addr,
conn: conn,
client: mq_pb.NewSeaweedMessagingClient(conn),
publishers: make(map[string]*BrokerPublisherSession),
subscribers: make(map[string]*BrokerSubscriberSession),
partitionAssignmentCache: make(map[string]*partitionAssignmentCacheEntry),
partitionAssignmentCacheTTL: 30 * time.Second,
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
ctx: ctx,
cancel: cancel,
}
t.Cleanup(func() { bc.Close() })
return bc
}
func publishKey(t *testing.T, bc *BrokerClient, ctx context.Context, key int64) (int64, error) {
t.Helper()
return bc.PublishRecord(ctx, "events", 0, []byte(strconv.FormatInt(key, 10)), []byte("v"), time.Now().UnixNano())
}
func TestPublishRecordReplacesCancelledSession(t *testing.T) {
held := make(chan struct{})
broker := startPublishBroker(t, &publishBroker{
first: func(n int) (*mq_pb.PublishMessageResponse, bool) {
if n == 0 {
close(held)
}
return nil, n == 0
},
})
bc := newPublishTestClient(t, broker.addr)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
<-held
cancel()
}()
if _, err := publishKey(t, bc, ctx, 1); err == nil {
t.Fatal("publish whose ack never came should fail")
}
ctx2, cancel2 := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel2()
offset, err := publishKey(t, bc, ctx2, 2)
if err != nil {
t.Fatalf("publish after a cancelled call: %v", err)
}
if offset != 2 {
t.Fatalf("got offset %d, want the ack of this call (2)", offset)
}
if got := broker.streamCount(); got != 2 {
t.Fatalf("expected a fresh stream after the cancelled call, broker saw %d streams", got)
}
}
func TestPublishRecordDropsSessionOnNotLeader(t *testing.T) {
broker := startPublishBroker(t, &publishBroker{
first: func(n int) (*mq_pb.PublishMessageResponse, bool) {
if n == 0 {
return &mq_pb.PublishMessageResponse{ErrorCode: 6, Error: "not the leader for this partition"}, false
}
return nil, false
},
})
bc := newPublishTestClient(t, broker.addr)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if _, err := publishKey(t, bc, ctx, 1); err == nil {
t.Fatal("publish answered with not-leader should fail")
}
bc.publishersLock.RLock()
remaining := len(bc.publishers)
bc.publishersLock.RUnlock()
if remaining != 0 {
t.Fatalf("not-leader session still cached")
}
offset, err := publishKey(t, bc, ctx, 7)
if err != nil {
t.Fatalf("publish after not-leader: %v", err)
}
if offset != 7 {
t.Fatalf("got offset %d, want 7", offset)
}
}
func TestPublishRecordFollowsPartitionLeader(t *testing.T) {
leader := startPublishBroker(t, &publishBroker{})
// the gateway's own broker leads nothing once the partition moves
gatewayBroker := startPublishBroker(t, &publishBroker{notLeader: true})
bc := newPublishTestClient(t, gatewayBroker.addr)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_, err := publishKey(t, bc, ctx, 1)
if !errors.Is(err, ErrNotLeaderOrFollower) {
t.Fatalf("publish to a non-leader should be retriable, got %v", err)
}
gatewayBroker.setLeader(leader.addr)
offset, err := publishKey(t, bc, ctx, 3)
if err != nil {
t.Fatalf("publish after the leader moved: %v", err)
}
if offset != 3 {
t.Fatalf("got offset %d, want 3", offset)
}
if got := leader.streamCount(); got != 1 {
t.Fatalf("leader saw %d publish streams, want 1", got)
}
}
func TestPublishRecordGivesUpOnASilentLeader(t *testing.T) {
held := make(chan struct{})
broker := startPublishBroker(t, &publishBroker{holdHello: func(n int) bool {
if n == 0 {
close(held)
}
return n == 0
}})
bc := newPublishTestClient(t, broker.addr)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
<-held
cancel()
}()
done := make(chan error, 1)
go func() {
_, err := publishKey(t, bc, ctx, 1)
done <- err
}()
select {
case err := <-done:
if !errors.Is(err, context.Canceled) {
t.Fatalf("publish to a silent leader returned %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("publish outlived its context while the leader withheld its hello")
}
ctx2, cancel2 := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel2()
if offset, err := publishKey(t, bc, ctx2, 2); err != nil || offset != 2 {
t.Fatalf("next publish: offset %d, err %v", offset, err)
}
}
func TestFetchReadsFromPartitionLeader(t *testing.T) {
leader := startPublishBroker(t, &publishBroker{})
gatewayBroker := startPublishBroker(t, &publishBroker{})
gatewayBroker.setLeader(leader.addr)
bc := newPublishTestClient(t, gatewayBroker.addr)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
hwm, err := bc.GetPartitionHighWaterMark(ctx, "events", 0)
if err != nil {
t.Fatalf("high water mark through a non-leader gateway broker: %v", err)
}
if hwm != 7 {
t.Fatalf("got high water mark %d, want the leader's 7", hwm)
}
}
func TestRangeInfoReadsFromPartitionLeader(t *testing.T) {
leader := startPublishBroker(t, &publishBroker{})
gatewayBroker := startPublishBroker(t, &publishBroker{})
gatewayBroker.setLeader(leader.addr)
bc := newPublishTestClient(t, gatewayBroker.addr)
hwm, err := bc.GetHighWaterMark("events", 0)
if err != nil {
t.Fatalf("high water mark through a non-leader gateway broker: %v", err)
}
if hwm != 7 {
t.Fatalf("got high water mark %d, want the leader's 7", hwm)
}
}
func TestRangeInfoLooksUpALeaderThatLostThePartition(t *testing.T) {
gatewayBroker := startPublishBroker(t, &publishBroker{})
oldLeader := startPublishBroker(t, &publishBroker{})
gatewayBroker.setLeader(oldLeader.addr)
bc := newPublishTestClient(t, gatewayBroker.addr)
if _, err := bc.GetPartitionRangeInfo("events", 0); err != nil {
t.Fatalf("range from the first leader: %v", err)
}
gatewayBroker.setLeader(gatewayBroker.addr)
oldLeader.setLeader(gatewayBroker.addr)
bc.GetPartitionRangeInfo("events", 0)
if info, err := bc.GetPartitionRangeInfo("events", 0); err != nil || info.HighWaterMark != 7 {
t.Fatalf("range after the leader moved: %+v, err %v", info, err)
}
}
func TestFetchLooksUpALeaderThatLostThePartition(t *testing.T) {
gatewayBroker := startPublishBroker(t, &publishBroker{})
oldLeader := startPublishBroker(t, &publishBroker{})
gatewayBroker.setLeader(oldLeader.addr)
bc := newPublishTestClient(t, gatewayBroker.addr)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if _, err := bc.GetPartitionHighWaterMark(ctx, "events", 0); err != nil {
t.Fatalf("read from the first leader: %v", err)
}
gatewayBroker.setLeader(gatewayBroker.addr)
oldLeader.setLeader(gatewayBroker.addr)
bc.GetPartitionHighWaterMark(ctx, "events", 0)
if hwm, err := bc.GetPartitionHighWaterMark(ctx, "events", 0); err != nil || hwm != 7 {
t.Fatalf("read after the leader moved: hwm %d, err %v", hwm, err)
}
}
func TestPublishCancellationDuringLookupAndPartitionWait(t *testing.T) {
lookupStarted := make(chan struct{})
broker := startPublishBroker(t, &publishBroker{holdLookup: lookupStarted})
bc := newPublishTestClient(t, broker.addr)
firstCtx, cancelFirst := context.WithCancel(t.Context())
defer cancelFirst()
firstDone := make(chan error, 1)
go func() {
_, err := publishKey(t, bc, firstCtx, 1)
firstDone <- err
}()
select {
case <-lookupStarted:
case <-time.After(5 * time.Second):
t.Fatal("broker did not receive the lookup")
}
secondCtx, cancelSecond := context.WithTimeout(t.Context(), 100*time.Millisecond)
defer cancelSecond()
secondDone := make(chan error, 1)
go func() {
_, err := publishKey(t, bc, secondCtx, 2)
secondDone <- err
}()
select {
case err := <-secondDone:
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("waiting publisher returned %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("waiting publisher outlived its deadline")
}
cancelFirst()
select {
case err := <-firstDone:
if !errors.Is(err, context.Canceled) {
t.Fatalf("publisher doing the lookup returned %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("cancelled publisher still waiting for its lookup")
}
}
@@ -49,7 +49,7 @@ func (bc *BrokerClient) CreateFreshSubscriber(topic string, partition int32, sta
}
// Get the actual partition assignment from the broker
actualPartition, err := bc.getActualPartitionAssignment(topic, partition)
actualPartition, _, err := bc.getActualPartitionAssignment(bc.ctx, topic, partition)
if err != nil {
subscriberCancel()
return nil, fmt.Errorf("failed to get actual partition assignment for subscribe: %v", err)
@@ -171,7 +171,7 @@ func (bc *BrokerClient) GetOrCreateSubscriber(topic string, partition int32, sta
}
// Get the actual partition assignment from the broker
actualPartition, err := bc.getActualPartitionAssignment(topic, partition)
actualPartition, _, err := bc.getActualPartitionAssignment(bc.ctx, topic, partition)
if err != nil {
subscriberCancel()
return nil, fmt.Errorf("failed to get actual partition assignment for subscribe: %v", err)
@@ -240,7 +240,7 @@ func (bc *BrokerClient) createTemporarySubscriber(topic string, partition int32,
}
// Get the actual partition assignment from the broker
actualPartition, err := bc.getActualPartitionAssignment(topic, partition)
actualPartition, _, err := bc.getActualPartitionAssignment(bc.ctx, topic, partition)
if err != nil {
cancel()
return nil, fmt.Errorf("failed to get actual partition assignment: %v", err)
@@ -299,7 +299,7 @@ func (bc *BrokerClient) createSubscriberSession(topic string, partition int32, s
}
// Get the actual partition assignment from the broker
actualPartition, err := bc.getActualPartitionAssignment(topic, partition)
actualPartition, _, err := bc.getActualPartitionAssignment(bc.ctx, topic, partition)
if err != nil {
cancel()
return nil, fmt.Errorf("failed to get actual partition assignment: %v", err)
@@ -1077,7 +1077,7 @@ func (bc *BrokerClient) RestartSubscriber(session *BrokerSubscriberSession, newO
}
// Get the actual partition assignment
actualPartition, err := bc.getActualPartitionAssignment(session.Topic, session.Partition)
actualPartition, _, err := bc.getActualPartitionAssignment(bc.ctx, session.Topic, session.Partition)
if err != nil {
cancel()
_ = stream.CloseSend()
@@ -1,6 +1,7 @@
package integration
import (
"errors"
"strings"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
@@ -23,6 +24,10 @@ const (
kafkaErrorCodeInvalidRecord int16 = 42
)
// ErrNotLeaderOrFollower marks a publish that lost its partition leader or could not reach it.
// The Kafka client should refresh its metadata and retry.
var ErrNotLeaderOrFollower = errors.New("not leader or follower")
// MapBrokerErrorToKafka maps a broker error code to the corresponding Kafka protocol error code
func MapBrokerErrorToKafka(brokerErrorCode int32) int16 {
switch brokerErrorCode {
@@ -86,6 +91,15 @@ func HandleBrokerResponse(resp *mq_pb.PublishMessageResponse) (int16, string, er
return kafkaErrorCode, resp.Error, nil
}
// leaderUnavailable reports whether a Kafka error code means the partition needs a fresh leader.
func leaderUnavailable(kafkaErrorCode int16) bool {
switch kafkaErrorCode {
case kafkaErrorCodeNotLeaderOrFollower, kafkaErrorCodeBrokerNotAvailable, kafkaErrorCodeNetworkException:
return true
}
return false
}
// parseStringErrorToKafkaCode provides backward compatibility for string-based error parsing
// This is the old brittle approach that we're replacing with structured error codes
func parseStringErrorToKafkaCode(errorMsg string) int16 {
@@ -247,7 +247,7 @@ func (h *SeaweedMQHandler) ProduceRecord(ctx context.Context, topic string, part
}
if publishErr != nil {
return 0, fmt.Errorf("failed to publish to SeaweedMQ: %v", publishErr)
return 0, fmt.Errorf("failed to publish to SeaweedMQ: %w", publishErr)
}
// SMQ should have generated and returned the offset - use it directly as the Kafka offset
@@ -284,7 +284,7 @@ func (h *SeaweedMQHandler) ProduceRecordValue(ctx context.Context, topic string,
}
if publishErr != nil {
return 0, fmt.Errorf("failed to publish RecordValue to SeaweedMQ: %v", publishErr)
return 0, fmt.Errorf("failed to publish RecordValue to SeaweedMQ: %w", publishErr)
}
// SMQ broker has assigned the offset - use it directly as the Kafka offset
+7 -6
View File
@@ -171,16 +171,17 @@ type BrokerClient struct {
// Reference to shared filer client accessor
filerClientAccessor *filer_client.FilerClientAccessor
brokerAddress string
conn *grpc.ClientConn
client mq_pb.SeaweedMessagingClient
brokerAddress string
grpcDialOption grpc.DialOption
conn *grpc.ClientConn
client mq_pb.SeaweedMessagingClient
// Publisher streams: topic-partition -> stream info
publishersLock sync.RWMutex
publishers map[string]*BrokerPublisherSession
// Publisher creation locks to prevent concurrent creation attempts for the same topic-partition
publisherCreationLocks map[string]*sync.Mutex
// A gate serializes publisher setup and send/receive pairs for its partition.
publishGates map[string]chan struct{}
// Subscriber streams for offset tracking
subscribersLock sync.RWMutex
@@ -204,7 +205,7 @@ type BrokerPublisherSession struct {
Topic string
Partition int32
Stream mq_pb.SeaweedMessaging_PublishMessageClient
mu sync.Mutex // Protects Send/Recv pairs from concurrent access
cancel context.CancelFunc
}
// BrokerSubscriberSession tracks a subscription stream for offset management
+14 -3
View File
@@ -3,11 +3,13 @@ package protocol
import (
"context"
"encoding/binary"
"errors"
"fmt"
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/mq/kafka/compression"
"github.com/seaweedfs/seaweedfs/weed/mq/kafka/integration"
"github.com/seaweedfs/seaweedfs/weed/mq/kafka/schema"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"google.golang.org/protobuf/proto"
@@ -135,7 +137,7 @@ func (h *Handler) handleProduceV0V1(ctx context.Context, correlationID uint32, a
if h.isSchemaValidationError(err) {
time.Sleep(200 * time.Millisecond) // Brief delay for schema validation failures
}
errorCode = 0xFFFF // UNKNOWN_SERVER_ERROR (-1 as uint16)
errorCode = produceErrorCode(err)
} else {
baseOffset = offset
}
@@ -169,6 +171,15 @@ func (h *Handler) handleProduceV0V1(ctx context.Context, correlationID uint32, a
return response, nil
}
// produceErrorCode answers a publish that lost or could not reach its partition leader with
// NOT_LEADER_OR_FOLLOWER, so the client refreshes metadata and retries.
func produceErrorCode(err error) uint16 {
if errors.Is(err, integration.ErrNotLeaderOrFollower) {
return uint16(ErrorCodeNotLeaderOrFollower)
}
return 0xFFFF // UNKNOWN_SERVER_ERROR (-1 as uint16)
}
// parseRecordSet parses a Kafka record set using the enhanced record batch parser
// Now supports:
// - Proper record batch format parsing (v2)
@@ -713,7 +724,7 @@ func (h *Handler) handleProduceV2Plus(ctx context.Context, correlationID uint32,
if h.isSchemaValidationError(prodErr) {
time.Sleep(200 * time.Millisecond) // Brief delay for schema validation failures
}
errorCode = 0xFFFF // UNKNOWN_SERVER_ERROR (-1 as uint16)
errorCode = produceErrorCode(prodErr)
break
}
@@ -729,7 +740,7 @@ func (h *Handler) handleProduceV2Plus(ctx context.Context, correlationID uint32,
for idx, kv := range records {
offsetProduced, prodErr := h.produceSchemaBasedRecord(ctx, topicName, int32(partitionID), kv.Key, kv.Value)
if prodErr != nil {
errorCode = 0xFFFF // UNKNOWN_SERVER_ERROR (-1 as uint16)
errorCode = produceErrorCode(prodErr)
break
}
if idx == 0 {
@@ -0,0 +1,20 @@
package protocol
import (
"errors"
"fmt"
"testing"
"github.com/seaweedfs/seaweedfs/weed/mq/kafka/integration"
)
func TestProduceErrorCodeAsksClientToRetryOnLostLeader(t *testing.T) {
lostLeader := fmt.Errorf("failed to publish to SeaweedMQ: %w",
fmt.Errorf("%w: failed to receive ack: connection reset", integration.ErrNotLeaderOrFollower))
if got := produceErrorCode(lostLeader); got != uint16(ErrorCodeNotLeaderOrFollower) {
t.Fatalf("lost leader mapped to %d, want NOT_LEADER_OR_FOLLOWER", got)
}
if got := produceErrorCode(errors.New("failed to marshal record")); got != 0xFFFF {
t.Fatalf("other errors mapped to %d, want UNKNOWN_SERVER_ERROR", got)
}
}