mq: one offset assigner per partition, continued from disk (#13191)

* mq: assign publish offsets inside the partition's log buffer

A publish took its offset from the offset manager under one lock and
appended it to the log buffer under another, so two publishers on one
partition could append offsets out of order. The buffer now assigns the
offset under its own lock when the entry asks for one, and an entry
that already carries an offset moves the buffer's next offset past it
instead of bumping it by one.

* mq: give the entry that rolls a window over to the new window

Both append paths widened the window's offset range before checking
for a rollover. The sealed window then claimed the entry that started
the next one, and the new window's range started without it, so a
window holding only that entry was flushed as offsets 0..0 and readers
skipped it. The range is now widened after the rollover.

* mq: seed a partition's offsets from all of its own files

A loading partition continued its offsets from the highest offset
recorded on disk, but the scan listed without a limit, so the filer
returned only its default page (1000 entries under weed server and
mini) and offsets below the real maximum were handed out again. It also
read the newest version directory rather than the partition's own, and
a filer error left the partition counting from 0.

The broker and the Kafka gateway now share mq.ReadOffsetRange, which
lists every file, the broker reads the partition's own directory, and
a partition whose stored offsets cannot be read is not loaded, so the
publish fails and is retried.

* mq: reload a partition only after its retired copy has flushed

Idle cleanup and a drain retire a partition and return while its last
flush is still queued. A publish right behind them created a new copy,
which read the stored offsets before that flush landed and handed out
its offsets again. Loading a partition now waits for a retired copy of
the same range, outside the broker's access lock that the flush takes.

* mq broker: report a partition's high water mark from its buffer

The range reported to the Kafka gateway took the larger of the offset
manager's count and the buffer's, so it followed the manager's
checkpoint rather than what the partition had assigned. It now comes
from the loaded partition's buffer, which assigns the offsets, or from
the ranges stored on disk when this broker has not loaded the partition.

* mq: drop the offset manager's assignment, checkpoint and subscription code

Publish offsets now come from each partition's log buffer and its high
water mark from that buffer or the stored ranges, so the separate
assigner, its checkpoint.offset writer and the offset subscription
layer built on it have no callers left. Only consumer-group positions
remain in BrokerOffsetManager. Existing checkpoint.offset files are left
alone; readers already skip them.

* mq broker: recheck a retiring partition under the lock when assigning

AssignTopicPartitions waited for a retiring copy before taking the
access lock, so a drain in between could retire the partition and the
assignment then seeded a replacement before that flush landed. The
check now runs under the lock, which is released only to wait.

* mq topic: mark a partition retiring before it leaves the list

RemoveLocalPartition took the partition out of the active list before
recording it as retiring, so a replacement loaded in between saw
neither and read the stored offsets before the last flush landed. The
partition is now recorded as retiring first.

* mq topic: gate the retired-flush test on a channel instead of a sleep

The test relied on a 200ms flush delay to observe the partition as
pending, which a paused test goroutine could outlast.

* mq topic: remove a partition by its instance under one lock

RemoveLocalPartition looked the partition up, marked it retiring and then
removed by range in separate steps. A second remover of the same copy could
take out a replacement loaded in between, leaving it neither listed nor
retiring, and a removal that found nothing still left a stale retiring entry.
Callers now pass the copy they hold; it is marked retiring and taken out of
the list under the partition lock, and only if it is still listed.

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

* mq broker: look a partition up once per assignment pass

The retirement wait checked one lookup and the load used a second one, so
idle cleanup retiring the partition between them let the assignment load a
replacement from stored offsets before the retired copy's last flush landed.
The wait and the load now use the same lookup.

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

* mq broker: let a cancelled assignment leave the retirement wait

AssignTopicPartitions waited for a retired copy's last flush without watching
its request, so while that flush kept failing a cancelled call still held its
handler. WaitRetired now takes a context and returns its error, leaving the
retirement pending; the publish and subscribe loader keeps waiting as before.

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

* mq topic: share one flush signal per retirement

A cancelled WaitRetired left its goroutine blocked on the retired
buffer's flush, so repeated cancelled assignments piled up goroutines
until that flush finished. The retirement now owns one channel, closed
after its last flush, and every waiter selects on it.

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

* mq broker: load the assigned generation for any request of its range

Subscribe and fetch pass the partition from the request, and the loader
built the local partition from it after matching only the range. A stale
or zero generation then scanned a directory the broker was not assigned,
found no offsets, and registered a partition that restarted at zero over
stored data. The loader now takes the assignment's partition.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Chris LuandClaude Opus 5.5 authored and GitHub committed 2026-11-30 22:29:27 -08:00
1 parent de76148f54
commit 24951dbfe7
28 files changed
+527 -3478

No files matched your search

+15 -6
View File
@@ -24,24 +24,33 @@ func (b *MessageQueueBroker) AssignTopicPartitions(c context.Context, request *m
t := topic.FromPbTopic(request.Topic)
partition := topic.FromPbPartition(assignment.Partition)
b.accessLock.Lock()
localPartition := b.localTopicManager.GetLocalPartition(t, partition)
for !request.IsDraining && localPartition == nil && b.localTopicManager.RetiringPartition(t, partition) != nil {
// its flush takes accessLock, so wait without it
b.accessLock.Unlock()
if err := b.localTopicManager.WaitRetired(c, t, partition); err != nil {
return nil, status.FromContextError(err).Err()
}
b.accessLock.Lock()
localPartition = b.localTopicManager.GetLocalPartition(t, partition)
}
if request.IsDraining {
// TODO drain existing topic partition subscriptions
b.localTopicManager.RemoveLocalPartition(t, b.localTopicManager.GetLocalPartition(t, partition))
b.localTopicManager.RemoveLocalPartition(t, localPartition)
} else {
existing := b.localTopicManager.GetLocalPartition(t, partition)
for b.retireStaleLeader(t, existing, assignment.Epoch) {
existing = b.localTopicManager.GetLocalPartition(t, partition)
for b.retireStaleLeader(t, localPartition, assignment.Epoch) {
localPartition = b.localTopicManager.GetLocalPartition(t, partition)
}
// checked after the reload, which can wait out a Shutdown that starts meanwhile
if b.localTopicManager.IsStopping() {
b.accessLock.Unlock()
return nil, status.Errorf(codes.Unavailable, "broker %s is stopping", b.option.BrokerAddress())
}
if existing == nil {
if localPartition == nil {
localPartition, genErr := b.newLeaderPartition(t, partition, assignment.Epoch)
if genErr != nil {
b.accessLock.Unlock()
return nil, genErr
return nil, status.Errorf(codes.Unavailable, "%v", genErr)
}
if !b.localTopicManager.AddLocalPartition(t, localPartition) {
localPartition.Shutdown()
+1 -10
View File
@@ -198,16 +198,7 @@ func (b *MessageQueueBroker) PublishMessage(stream mq_pb.SeaweedMessaging_Publis
return stream.Send(response)
}
// Send to the local partition with offset assignment
t, p := topic.FromPbTopic(initMessage.Topic), topic.FromPbPartition(initMessage.Partition)
// Create offset assignment function for this partition
assignOffsetFn := func() (int64, error) {
return b.offsetManager.AssignOffset(t, p)
}
// Use offset-aware publishing
assignedOffset, err := localTopicPartition.PublishWithOffset(dataMessage, assignOffsetFn)
assignedOffset, err := localTopicPartition.PublishWithOffset(dataMessage)
if err != nil {
return fmt.Errorf("topic %v partition %v publish error: %w", initMessage.Topic, initMessage.Partition, err)
}
-253
View File
@@ -1,253 +0,0 @@
package broker
import (
"context"
"fmt"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
"github.com/seaweedfs/seaweedfs/weed/mq/offset"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
)
// SubscribeWithOffset handles subscription requests with offset-based positioning
// TODO: This extends the broker with offset-aware subscription support
// ASSUMPTION: This will eventually be integrated into the main SubscribeMessage method
func (b *MessageQueueBroker) SubscribeWithOffset(
ctx context.Context,
req *mq_pb.SubscribeMessageRequest,
stream mq_pb.SeaweedMessaging_SubscribeMessageServer,
offsetType schema_pb.OffsetType,
startOffset int64,
) error {
initMessage := req.GetInit()
if initMessage == nil {
return fmt.Errorf("missing init message")
}
// Extract partition information from the request
t := topic.FromPbTopic(initMessage.Topic)
// Get partition from the request's partition_offset field
if initMessage.PartitionOffset == nil || initMessage.PartitionOffset.Partition == nil {
return fmt.Errorf("missing partition information in request")
}
// Use the partition information from the request
p := topic.Partition{
RingSize: initMessage.PartitionOffset.Partition.RingSize,
RangeStart: initMessage.PartitionOffset.Partition.RangeStart,
RangeStop: initMessage.PartitionOffset.Partition.RangeStop,
UnixTimeNs: initMessage.PartitionOffset.Partition.UnixTimeNs,
}
// Create offset-based subscription
subscriptionID := fmt.Sprintf("%s-%s-%d", initMessage.ConsumerGroup, initMessage.ConsumerId, startOffset)
subscription, err := b.offsetManager.CreateSubscription(subscriptionID, t, p, offsetType, startOffset)
if err != nil {
return fmt.Errorf("failed to create offset subscription: %w", err)
}
defer func() {
if closeErr := b.offsetManager.CloseSubscription(subscriptionID); closeErr != nil {
glog.V(0).Infof("Failed to close subscription %s: %v", subscriptionID, closeErr)
}
}()
// Get local partition for reading
localTopicPartition, err := b.GetOrGenerateLocalPartition(t, p)
if err != nil {
return fmt.Errorf("topic %v partition %v not found: %v", t, p, err)
}
// Subscribe to messages using offset-based positioning
return b.subscribeWithOffsetSubscription(ctx, localTopicPartition, subscription, stream, initMessage)
}
// subscribeWithOffsetSubscription handles the actual message consumption with offset tracking
func (b *MessageQueueBroker) subscribeWithOffsetSubscription(
ctx context.Context,
localPartition *topic.LocalPartition,
subscription *offset.OffsetSubscription,
stream mq_pb.SeaweedMessaging_SubscribeMessageServer,
initMessage *mq_pb.SubscribeMessageRequest_InitMessage,
) error {
clientName := fmt.Sprintf("%s-%s", initMessage.ConsumerGroup, initMessage.ConsumerId)
// TODO: Implement offset-based message reading
// ASSUMPTION: For now, we'll use the existing subscription mechanism and track offsets separately
// This should be replaced with proper offset-based reading from storage
// Convert the subscription's current offset to a proper MessagePosition
startPosition, err := b.convertOffsetToMessagePosition(subscription)
if err != nil {
return fmt.Errorf("failed to convert offset to message position: %w", err)
}
glog.V(0).Infof("[%s] Starting Subscribe for topic %s partition %d-%d at offset %d",
clientName, subscription.TopicName, subscription.Partition.RangeStart, subscription.Partition.RangeStop, subscription.CurrentOffset)
return localPartition.Subscribe(clientName,
startPosition,
func() bool {
// Check if context is cancelled (client disconnected)
select {
case <-ctx.Done():
glog.V(0).Infof("[%s] Context cancelled, stopping", clientName)
return false
default:
}
// Check if subscription is still active and not at end
if !subscription.IsActive {
glog.V(0).Infof("[%s] Subscription not active, stopping", clientName)
return false
}
atEnd, err := subscription.IsAtEnd()
if err != nil {
glog.V(0).Infof("[%s] Error checking if subscription at end: %v", clientName, err)
return false
}
if atEnd {
glog.V(4).Infof("[%s] At end of subscription, stopping", clientName)
return false
}
// Add a small sleep to avoid CPU busy-wait when checking for new data
time.Sleep(10 * time.Millisecond)
return true
},
func(logEntry *filer_pb.LogEntry) (bool, error) {
// Check if this message matches our offset requirements
currentOffset := subscription.GetNextOffset()
if logEntry.Offset < currentOffset {
// Skip messages before our current offset
return false, nil
}
// Send message to client
if err := stream.Send(&mq_pb.SubscribeMessageResponse{
Message: &mq_pb.SubscribeMessageResponse_Data{
Data: &mq_pb.DataMessage{
Key: logEntry.Key,
Value: logEntry.Data,
TsNs: logEntry.TsNs,
},
},
}); err != nil {
glog.Errorf("Error sending data to %s: %v", clientName, err)
return false, err
}
// Advance subscription offset
subscription.AdvanceOffset()
// Check context for cancellation
select {
case <-ctx.Done():
return true, ctx.Err()
default:
return false, nil
}
})
}
// GetSubscriptionInfo returns information about an active subscription
func (b *MessageQueueBroker) GetSubscriptionInfo(subscriptionID string) (map[string]interface{}, error) {
subscription, err := b.offsetManager.GetSubscription(subscriptionID)
if err != nil {
return nil, err
}
lag, err := subscription.GetLag()
if err != nil {
return nil, err
}
atEnd, err := subscription.IsAtEnd()
if err != nil {
return nil, err
}
return map[string]interface{}{
"subscription_id": subscription.ID,
"start_offset": subscription.StartOffset,
"current_offset": subscription.CurrentOffset,
"offset_type": subscription.OffsetType.String(),
"is_active": subscription.IsActive,
"lag": lag,
"at_end": atEnd,
}, nil
}
// ListActiveSubscriptions returns information about all active subscriptions
func (b *MessageQueueBroker) ListActiveSubscriptions() ([]map[string]interface{}, error) {
subscriptions, err := b.offsetManager.ListActiveSubscriptions()
if err != nil {
return nil, err
}
result := make([]map[string]interface{}, len(subscriptions))
for i, subscription := range subscriptions {
lag, _ := subscription.GetLag()
atEnd, _ := subscription.IsAtEnd()
result[i] = map[string]interface{}{
"subscription_id": subscription.ID,
"start_offset": subscription.StartOffset,
"current_offset": subscription.CurrentOffset,
"offset_type": subscription.OffsetType.String(),
"is_active": subscription.IsActive,
"lag": lag,
"at_end": atEnd,
}
}
return result, nil
}
// SeekSubscription seeks an existing subscription to a specific offset
func (b *MessageQueueBroker) SeekSubscription(subscriptionID string, offset int64) error {
subscription, err := b.offsetManager.GetSubscription(subscriptionID)
if err != nil {
return err
}
return subscription.SeekToOffset(offset)
}
// convertOffsetToMessagePosition converts a subscription's current offset to a MessagePosition for log_buffer
func (b *MessageQueueBroker) convertOffsetToMessagePosition(subscription *offset.OffsetSubscription) (log_buffer.MessagePosition, error) {
currentOffset := subscription.GetNextOffset()
// Handle special offset cases
switch subscription.OffsetType {
case schema_pb.OffsetType_RESET_TO_EARLIEST:
return log_buffer.NewMessagePosition(1, -3), nil
case schema_pb.OffsetType_RESET_TO_LATEST:
return log_buffer.NewMessagePosition(time.Now().UnixNano(), -4), nil
case schema_pb.OffsetType_EXACT_OFFSET:
// Use proper offset-based positioning that provides consistent results
// This uses the same approach as the main subscription handler in broker_grpc_sub.go
return log_buffer.NewMessagePositionFromOffset(currentOffset), nil
case schema_pb.OffsetType_EXACT_TS_NS:
// For exact timestamps, use the timestamp directly
return log_buffer.NewMessagePosition(currentOffset, -2), nil
default:
// Default to starting from current time for unknown offset types
return log_buffer.NewMessagePosition(time.Now().UnixNano(), -2), nil
}
}
@@ -1,707 +0,0 @@
package broker
import (
"fmt"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/mq/offset"
"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/log_buffer"
)
func TestConvertOffsetToMessagePosition(t *testing.T) {
broker := &MessageQueueBroker{}
tests := []struct {
name string
offsetType schema_pb.OffsetType
currentOffset int64
expectedBatch int64
expectError bool
}{
{
name: "reset to earliest",
offsetType: schema_pb.OffsetType_RESET_TO_EARLIEST,
currentOffset: 0,
expectedBatch: -3,
expectError: false,
},
{
name: "reset to latest",
offsetType: schema_pb.OffsetType_RESET_TO_LATEST,
currentOffset: 0,
expectedBatch: -4,
expectError: false,
},
{
name: "exact offset zero",
offsetType: schema_pb.OffsetType_EXACT_OFFSET,
currentOffset: 0,
expectedBatch: 0, // NewMessagePositionFromOffset stores offset directly in Offset field
expectError: false,
},
{
name: "exact offset non-zero",
offsetType: schema_pb.OffsetType_EXACT_OFFSET,
currentOffset: 100,
expectedBatch: 100, // NewMessagePositionFromOffset stores offset directly in Offset field
expectError: false,
},
{
name: "exact timestamp",
offsetType: schema_pb.OffsetType_EXACT_TS_NS,
currentOffset: 50,
expectedBatch: -2,
expectError: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create a mock subscription
subscription := &offset.OffsetSubscription{
ID: "test-subscription",
CurrentOffset: tt.currentOffset,
OffsetType: tt.offsetType,
IsActive: true,
}
position, err := broker.convertOffsetToMessagePosition(subscription)
if tt.expectError && err == nil {
t.Error("Expected error but got none")
return
}
if !tt.expectError && err != nil {
t.Errorf("Unexpected error: %v", err)
return
}
if position.Offset != tt.expectedBatch {
t.Errorf("Expected batch index %d, got %d", tt.expectedBatch, position.Offset)
}
// Verify that the timestamp is reasonable (not zero for most cases)
// Note: EXACT_OFFSET uses epoch time (zero) with NewMessagePositionFromOffset
if tt.offsetType != schema_pb.OffsetType_RESET_TO_EARLIEST &&
tt.offsetType != schema_pb.OffsetType_EXACT_OFFSET &&
position.Time.IsZero() {
t.Error("Expected non-zero timestamp")
}
})
}
}
func TestConvertOffsetToMessagePosition_OffsetEncoding(t *testing.T) {
broker := &MessageQueueBroker{}
// Test that offset-based positions encode the offset correctly in Offset field
testCases := []struct {
offset int64
expectedBatch int64
expectedIsSentinel bool // Should timestamp be the offset sentinel value?
}{
{10, 10, true},
{100, 100, true},
{0, 0, true},
{42, 42, true},
}
for _, tc := range testCases {
t.Run(fmt.Sprintf("offset_%d", tc.offset), func(t *testing.T) {
subscription := &offset.OffsetSubscription{
ID: fmt.Sprintf("test-%d", tc.offset),
CurrentOffset: tc.offset,
OffsetType: schema_pb.OffsetType_EXACT_OFFSET,
IsActive: true,
}
pos, err := broker.convertOffsetToMessagePosition(subscription)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
// Check Offset encoding
if pos.Offset != tc.expectedBatch {
t.Errorf("Expected batch index %d, got %d", tc.expectedBatch, pos.Offset)
}
// Verify the offset can be extracted correctly using IsOffsetBased/GetOffset
if !pos.IsOffsetBased {
t.Error("Position should be detected as offset-based")
}
// Check that IsOffsetBased flag is set correctly
if tc.expectedIsSentinel && !pos.IsOffsetBased {
t.Error("Expected offset-based position but IsOffsetBased=false")
}
if extractedOffset := pos.GetOffset(); extractedOffset != tc.offset {
t.Errorf("Expected extracted offset %d, got %d", tc.offset, extractedOffset)
}
})
}
}
func TestConvertOffsetToMessagePosition_ConsistentResults(t *testing.T) {
broker := &MessageQueueBroker{}
subscription := &offset.OffsetSubscription{
ID: "consistent-test",
CurrentOffset: 42,
OffsetType: schema_pb.OffsetType_EXACT_OFFSET,
IsActive: true,
}
// Call multiple times within a short period
positions := make([]log_buffer.MessagePosition, 5)
for i := 0; i < 5; i++ {
pos, err := broker.convertOffsetToMessagePosition(subscription)
if err != nil {
t.Fatalf("Unexpected error on iteration %d: %v", i, err)
}
positions[i] = pos
time.Sleep(1 * time.Millisecond) // Small delay
}
// All positions should have the same Offset
for i := 1; i < len(positions); i++ {
if positions[i].Offset != positions[0].Offset {
t.Errorf("Inconsistent Offset: %d vs %d", positions[0].Offset, positions[i].Offset)
}
}
// With NewMessagePositionFromOffset, timestamps should be identical (zero time for offset-based)
expectedTime := time.Time{}
for i := 0; i < len(positions); i++ {
if !positions[i].Time.Equal(expectedTime) {
t.Errorf("Expected all timestamps to be sentinel time (%v), got %v at index %d",
expectedTime, positions[i].Time, i)
}
}
}
func TestConvertOffsetToMessagePosition_FixVerification(t *testing.T) {
// This test specifically verifies that the fix addresses the issue mentioned:
// "The calculated timestamp for a given offset will change every time the function is called"
broker := &MessageQueueBroker{}
subscription := &offset.OffsetSubscription{
ID: "fix-verification",
CurrentOffset: 123,
OffsetType: schema_pb.OffsetType_EXACT_OFFSET,
IsActive: true,
}
// Call the function multiple times with delays to simulate real-world usage
var positions []log_buffer.MessagePosition
var timestamps []int64
for i := 0; i < 10; i++ {
pos, err := broker.convertOffsetToMessagePosition(subscription)
if err != nil {
t.Fatalf("Unexpected error on iteration %d: %v", i, err)
}
positions = append(positions, pos)
timestamps = append(timestamps, pos.Time.UnixNano())
time.Sleep(2 * time.Millisecond) // Small delay to ensure time progression
}
// Verify ALL timestamps are identical (no time-based variance)
expectedTimestamp := timestamps[0]
for i, ts := range timestamps {
if ts != expectedTimestamp {
t.Errorf("Timestamp variance detected at call %d: expected %d, got %d", i, expectedTimestamp, ts)
}
}
// Verify ALL Offset values are identical
expectedBatch := positions[0].Offset
for i, pos := range positions {
if pos.Offset != expectedBatch {
t.Errorf("Offset variance detected at call %d: expected %d, got %d", i, expectedBatch, pos.Offset)
}
}
// Verify the offset can be consistently extracted
expectedOffset := subscription.CurrentOffset
for i, pos := range positions {
if extractedOffset := pos.GetOffset(); extractedOffset != expectedOffset {
t.Errorf("Extracted offset variance at call %d: expected %d, got %d", i, expectedOffset, extractedOffset)
}
}
}
func TestPartitionIdentityConsistency(t *testing.T) {
// Test that partition identity is preserved from request to avoid breaking offset manager keys
// Create a mock init message with specific partition info
partition := &schema_pb.Partition{
RingSize: 32,
RangeStart: 0,
RangeStop: 31,
UnixTimeNs: 1234567890123456789, // Fixed timestamp
}
initMessage := &mq_pb.SubscribeMessageRequest_InitMessage{
ConsumerGroup: "test-group",
ConsumerId: "test-consumer",
PartitionOffset: &schema_pb.PartitionOffset{
Partition: partition,
},
}
// Simulate the partition creation logic from SubscribeWithOffset
p := topic.Partition{
RingSize: initMessage.PartitionOffset.Partition.RingSize,
RangeStart: initMessage.PartitionOffset.Partition.RangeStart,
RangeStop: initMessage.PartitionOffset.Partition.RangeStop,
UnixTimeNs: initMessage.PartitionOffset.Partition.UnixTimeNs,
}
// Verify that the partition preserves the original UnixTimeNs
if p.UnixTimeNs != partition.UnixTimeNs {
t.Errorf("Partition UnixTimeNs not preserved: expected %d, got %d",
partition.UnixTimeNs, p.UnixTimeNs)
}
// Verify partition key consistency
expectedKey := fmt.Sprintf("ring:%d:range:%d-%d:time:%d",
partition.RingSize, partition.RangeStart, partition.RangeStop, partition.UnixTimeNs)
actualKey := fmt.Sprintf("ring:%d:range:%d-%d:time:%d",
p.RingSize, p.RangeStart, p.RangeStop, p.UnixTimeNs)
if actualKey != expectedKey {
t.Errorf("Partition key mismatch: expected %s, got %s", expectedKey, actualKey)
}
}
func TestBrokerOffsetManager_GetSubscription_Fixed(t *testing.T) {
// Test that GetSubscription now works correctly after the fix
storage := NewInMemoryOffsetStorageForTesting()
offsetManager := NewBrokerOffsetManagerWithStorage(storage)
// Create test topic and partition
testTopic := topic.Topic{Namespace: "test", Name: "topic1"}
testPartition := topic.Partition{
RingSize: 32,
RangeStart: 0,
RangeStop: 31,
UnixTimeNs: time.Now().UnixNano(),
}
// Test getting non-existent subscription
_, err := offsetManager.GetSubscription("non-existent")
if err == nil {
t.Error("Expected error for non-existent subscription")
}
// Create a subscription
subscriptionID := "test-subscription-fixed"
subscription, err := offsetManager.CreateSubscription(
subscriptionID,
testTopic,
testPartition,
schema_pb.OffsetType_RESET_TO_EARLIEST,
0,
)
if err != nil {
t.Fatalf("Failed to create subscription: %v", err)
}
// Test getting existing subscription (this should now work)
retrievedSub, err := offsetManager.GetSubscription(subscriptionID)
if err != nil {
t.Fatalf("GetSubscription failed after fix: %v", err)
}
if retrievedSub.ID != subscription.ID {
t.Errorf("Expected subscription ID %s, got %s", subscription.ID, retrievedSub.ID)
}
if retrievedSub.OffsetType != subscription.OffsetType {
t.Errorf("Expected offset type %v, got %v", subscription.OffsetType, retrievedSub.OffsetType)
}
}
func TestBrokerOffsetManager_ListActiveSubscriptions_Fixed(t *testing.T) {
// Test that ListActiveSubscriptions now works correctly after the fix
storage := NewInMemoryOffsetStorageForTesting()
offsetManager := NewBrokerOffsetManagerWithStorage(storage)
// Create test topic and partition
testTopic := topic.Topic{Namespace: "test", Name: "topic1"}
testPartition := topic.Partition{
RingSize: 32,
RangeStart: 0,
RangeStop: 31,
UnixTimeNs: time.Now().UnixNano(),
}
// Initially should have no subscriptions
subscriptions, err := offsetManager.ListActiveSubscriptions()
if err != nil {
t.Fatalf("ListActiveSubscriptions failed after fix: %v", err)
}
if len(subscriptions) != 0 {
t.Errorf("Expected 0 subscriptions, got %d", len(subscriptions))
}
// Create multiple subscriptions (use RESET types to avoid HWM validation issues)
subscriptionIDs := []string{"sub-fixed-1", "sub-fixed-2", "sub-fixed-3"}
offsetTypes := []schema_pb.OffsetType{
schema_pb.OffsetType_RESET_TO_EARLIEST,
schema_pb.OffsetType_RESET_TO_LATEST,
schema_pb.OffsetType_RESET_TO_EARLIEST, // Changed from EXACT_OFFSET
}
for i, subID := range subscriptionIDs {
_, err := offsetManager.CreateSubscription(
subID,
testTopic,
testPartition,
offsetTypes[i],
0, // Use 0 for all to avoid validation issues
)
if err != nil {
t.Fatalf("Failed to create subscription %s: %v", subID, err)
}
}
// List all subscriptions (this should now work)
subscriptions, err = offsetManager.ListActiveSubscriptions()
if err != nil {
t.Fatalf("ListActiveSubscriptions failed after fix: %v", err)
}
if len(subscriptions) != len(subscriptionIDs) {
t.Errorf("Expected %d subscriptions, got %d", len(subscriptionIDs), len(subscriptions))
}
// Verify all subscriptions are active
for _, sub := range subscriptions {
if !sub.IsActive {
t.Errorf("Subscription %s should be active", sub.ID)
}
}
}
func TestMessageQueueBroker_ListActiveSubscriptions_Fixed(t *testing.T) {
// Test that the broker-level ListActiveSubscriptions now works correctly
storage := NewInMemoryOffsetStorageForTesting()
offsetManager := NewBrokerOffsetManagerWithStorage(storage)
broker := &MessageQueueBroker{
offsetManager: offsetManager,
}
// Create test topic and partition
testTopic := topic.Topic{Namespace: "test", Name: "topic1"}
testPartition := topic.Partition{
RingSize: 32,
RangeStart: 0,
RangeStop: 31,
UnixTimeNs: time.Now().UnixNano(),
}
// Initially should have no subscriptions
subscriptionInfos, err := broker.ListActiveSubscriptions()
if err != nil {
t.Fatalf("Broker ListActiveSubscriptions failed after fix: %v", err)
}
if len(subscriptionInfos) != 0 {
t.Errorf("Expected 0 subscription infos, got %d", len(subscriptionInfos))
}
// Create subscriptions with different offset types (use RESET types to avoid HWM validation issues)
testCases := []struct {
id string
offsetType schema_pb.OffsetType
startOffset int64
}{
{"broker-earliest-sub", schema_pb.OffsetType_RESET_TO_EARLIEST, 0},
{"broker-latest-sub", schema_pb.OffsetType_RESET_TO_LATEST, 0},
{"broker-reset-sub", schema_pb.OffsetType_RESET_TO_EARLIEST, 0}, // Changed from EXACT_OFFSET
}
for _, tc := range testCases {
_, err := broker.offsetManager.CreateSubscription(
tc.id,
testTopic,
testPartition,
tc.offsetType,
tc.startOffset,
)
if err != nil {
t.Fatalf("Failed to create subscription %s: %v", tc.id, err)
}
}
// List subscription infos (this should now work)
subscriptionInfos, err = broker.ListActiveSubscriptions()
if err != nil {
t.Fatalf("Broker ListActiveSubscriptions failed after fix: %v", err)
}
if len(subscriptionInfos) != len(testCases) {
t.Errorf("Expected %d subscription infos, got %d", len(testCases), len(subscriptionInfos))
}
// Verify subscription info structure
for _, info := range subscriptionInfos {
// Check required fields
requiredFields := []string{
"subscription_id", "start_offset", "current_offset",
"offset_type", "is_active", "lag", "at_end",
}
for _, field := range requiredFields {
if _, ok := info[field]; !ok {
t.Errorf("Missing field %s in subscription info", field)
}
}
// Verify is_active is true
if isActive, ok := info["is_active"].(bool); !ok || !isActive {
t.Errorf("Expected is_active to be true, got %v", info["is_active"])
}
}
}
func TestSingleWriterPerPartitionCorrectness(t *testing.T) {
// Test that demonstrates correctness under single-writer-per-partition model
// Simulate two brokers with separate offset managers but same partition
storage1 := NewInMemoryOffsetStorageForTesting()
storage2 := NewInMemoryOffsetStorageForTesting()
offsetManager1 := NewBrokerOffsetManagerWithStorage(storage1)
offsetManager2 := NewBrokerOffsetManagerWithStorage(storage2)
broker1 := &MessageQueueBroker{offsetManager: offsetManager1}
broker2 := &MessageQueueBroker{offsetManager: offsetManager2}
// Same partition identity (this is key for correctness)
fixedTimestamp := time.Now().UnixNano()
testTopic := topic.Topic{Namespace: "test", Name: "shared-topic"}
testPartition := topic.Partition{
RingSize: 32,
RangeStart: 0,
RangeStop: 31,
UnixTimeNs: fixedTimestamp, // Same timestamp = same partition identity
}
// Broker 1 is the leader for this partition - assigns offsets
baseOffset, lastOffset, err := broker1.offsetManager.AssignBatchOffsets(testTopic, testPartition, 10)
if err != nil {
t.Fatalf("Failed to assign offsets on broker1: %v", err)
}
if baseOffset != 0 || lastOffset != 9 {
t.Errorf("Expected offsets 0-9, got %d-%d", baseOffset, lastOffset)
}
// Get HWM from leader
hwm1, err := broker1.offsetManager.GetHighWaterMark(testTopic, testPartition)
if err != nil {
t.Fatalf("Failed to get HWM from broker1: %v", err)
}
if hwm1 != 10 {
t.Errorf("Expected HWM 10 on leader, got %d", hwm1)
}
// Broker 2 is a follower - should have HWM 0 (no local assignments)
hwm2, err := broker2.offsetManager.GetHighWaterMark(testTopic, testPartition)
if err != nil {
t.Fatalf("Failed to get HWM from broker2: %v", err)
}
if hwm2 != 0 {
t.Errorf("Expected HWM 0 on follower, got %d", hwm2)
}
// Create subscription on leader (where offsets were assigned)
subscription1, err := broker1.offsetManager.CreateSubscription(
"leader-subscription",
testTopic,
testPartition,
schema_pb.OffsetType_RESET_TO_EARLIEST,
0,
)
if err != nil {
t.Fatalf("Failed to create subscription on leader: %v", err)
}
// Verify subscription can see the correct HWM
lag1, err := subscription1.GetLag()
if err != nil {
t.Fatalf("Failed to get lag on leader subscription: %v", err)
}
if lag1 != 10 {
t.Errorf("Expected lag 10 on leader subscription, got %d", lag1)
}
// Create subscription on follower (should have different lag due to local HWM)
subscription2, err := broker2.offsetManager.CreateSubscription(
"follower-subscription",
testTopic,
testPartition,
schema_pb.OffsetType_RESET_TO_EARLIEST,
0,
)
if err != nil {
t.Fatalf("Failed to create subscription on follower: %v", err)
}
lag2, err := subscription2.GetLag()
if err != nil {
t.Fatalf("Failed to get lag on follower subscription: %v", err)
}
if lag2 != 0 {
t.Errorf("Expected lag 0 on follower subscription (no local data), got %d", lag2)
}
}
func TestEndToEndWorkflowAfterFixes(t *testing.T) {
// Test the complete workflow with all fixes applied
storage := NewInMemoryOffsetStorageForTesting()
offsetManager := NewBrokerOffsetManagerWithStorage(storage)
broker := &MessageQueueBroker{
offsetManager: offsetManager,
}
// Create test topic and partition with fixed timestamp
fixedTimestamp := time.Now().UnixNano()
testTopic := topic.Topic{Namespace: "test", Name: "e2e-topic"}
testPartition := topic.Partition{
RingSize: 32,
RangeStart: 0,
RangeStop: 31,
UnixTimeNs: fixedTimestamp,
}
subscriptionID := "e2e-test-sub"
// 1. Create subscription (use RESET_TO_EARLIEST to avoid HWM validation issues)
subscription, err := broker.offsetManager.CreateSubscription(
subscriptionID,
testTopic,
testPartition,
schema_pb.OffsetType_RESET_TO_EARLIEST,
0,
)
if err != nil {
t.Fatalf("Failed to create subscription: %v", err)
}
// 2. Verify GetSubscription works
retrievedSub, err := broker.offsetManager.GetSubscription(subscriptionID)
if err != nil {
t.Fatalf("GetSubscription failed: %v", err)
}
if retrievedSub.ID != subscription.ID {
t.Errorf("GetSubscription returned wrong subscription: expected %s, got %s",
subscription.ID, retrievedSub.ID)
}
// 3. Verify it appears in active list
activeList, err := broker.ListActiveSubscriptions()
if err != nil {
t.Fatalf("Failed to list active subscriptions: %v", err)
}
found := false
for _, info := range activeList {
if info["subscription_id"] == subscriptionID {
found = true
break
}
}
if !found {
t.Error("New subscription not found in active list")
}
// 4. Get subscription info
info, err := broker.GetSubscriptionInfo(subscriptionID)
if err != nil {
t.Fatalf("Failed to get subscription info: %v", err)
}
if info["subscription_id"] != subscriptionID {
t.Errorf("Wrong subscription ID in info: expected %s, got %v", subscriptionID, info["subscription_id"])
}
// 5. Assign some offsets to create data for seeking
_, _, err = broker.offsetManager.AssignBatchOffsets(testTopic, testPartition, 50)
if err != nil {
t.Fatalf("Failed to assign offsets: %v", err)
}
// 6. Seek subscription
newOffset := int64(42)
err = broker.SeekSubscription(subscriptionID, newOffset)
if err != nil {
t.Fatalf("Failed to seek subscription: %v", err)
}
// 7. Verify seek worked
updatedInfo, err := broker.GetSubscriptionInfo(subscriptionID)
if err != nil {
t.Fatalf("Failed to get updated subscription info: %v", err)
}
if updatedInfo["current_offset"] != newOffset {
t.Errorf("Seek didn't work: expected offset %d, got %v", newOffset, updatedInfo["current_offset"])
}
// 8. Test offset to timestamp conversion with fixed partition identity
updatedSub, err := broker.offsetManager.GetSubscription(subscriptionID)
if err != nil {
t.Fatalf("Failed to get updated subscription: %v", err)
}
position, err := broker.convertOffsetToMessagePosition(updatedSub)
if err != nil {
t.Fatalf("Failed to convert offset to position: %v", err)
}
if position.Time.IsZero() {
t.Error("Expected non-zero timestamp from conversion")
}
// 9. Verify partition identity consistency throughout
partitionKey1 := fmt.Sprintf("ring:%d:range:%d-%d:time:%d",
testPartition.RingSize, testPartition.RangeStart, testPartition.RangeStop, testPartition.UnixTimeNs)
partitionKey2 := fmt.Sprintf("ring:%d:range:%d-%d:time:%d",
testPartition.RingSize, testPartition.RangeStart, testPartition.RangeStop, fixedTimestamp)
if partitionKey1 != partitionKey2 {
t.Errorf("Partition key inconsistency: %s != %s", partitionKey1, partitionKey2)
}
}
+14 -126
View File
@@ -1,107 +1,30 @@
package broker
import (
"time"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
)
// OffsetAssignmentFunc is a function type for assigning offsets to messages
type OffsetAssignmentFunc func() (int64, error)
// AddToBufferWithOffset adds a message to the log buffer with offset assignment
// TODO: This is a temporary solution until LogBuffer can be modified to accept offset assignment
// ASSUMPTION: This function will be integrated into LogBuffer.AddToBuffer in the future
func (b *MessageQueueBroker) AddToBufferWithOffset(
logBuffer *log_buffer.LogBuffer,
message *mq_pb.DataMessage,
t topic.Topic,
p topic.Partition,
) error {
// Assign offset for this message
offset, err := b.offsetManager.AssignOffset(t, p)
if err != nil {
return err
}
// PERFORMANCE OPTIMIZATION: Pre-process expensive operations OUTSIDE the lock
processingTsNs := message.TsNs
if processingTsNs == 0 {
processingTsNs = time.Now().UnixNano()
}
// Create LogEntry with assigned offset
logEntry := &filer_pb.LogEntry{
TsNs: processingTsNs,
PartitionKeyHash: util.HashToInt32(message.Key),
Data: message.Value,
Key: message.Key,
Offset: offset, // Add the assigned offset
}
// Use the existing LogBuffer infrastructure for the rest
// TODO: This is a workaround - ideally LogBuffer should handle offset assignment
// For now, we'll add the message with the pre-assigned offset
return b.addLogEntryToBuffer(logBuffer, logEntry)
}
// addLogEntryToBuffer adds a pre-constructed LogEntry to the buffer
// This is a helper function that directly uses LogBuffer.AddLogEntryToBuffer
func (b *MessageQueueBroker) addLogEntryToBuffer(
logBuffer *log_buffer.LogBuffer,
logEntry *filer_pb.LogEntry,
) error {
// Use the AddLogEntryToBuffer method to preserve offset information
// This ensures the offset is maintained throughout the entire data flow
return logBuffer.AddLogEntryToBuffer(logEntry)
}
// GetPartitionOffsetInfoInternal returns offset information for a partition (internal method)
// GetPartitionOffsetInfoInternal reports offsets from the loaded partition's buffer, which
// assigns them, or from the ranges stored on disk when this broker has not loaded it.
func (b *MessageQueueBroker) GetPartitionOffsetInfoInternal(t topic.Topic, p topic.Partition) (*PartitionOffsetInfo, error) {
info, err := b.offsetManager.GetPartitionOffsetInfo(t, p)
if err != nil {
return nil, err
}
// CRITICAL FIX: Also check LogBuffer for in-memory messages
// The offset manager only tracks assigned offsets from persistent storage
// But the LogBuffer contains recently written messages that haven't been flushed yet
localPartition := b.localTopicManager.GetLocalPartition(t, p)
logBufferHWM := int64(-1)
if localPartition != nil && localPartition.LogBuffer != nil {
logBufferHWM = localPartition.LogBuffer.GetOffset()
var earliestOffset, highWaterMark, activeSubscriptions int64
if localPartition := b.localTopicManager.GetLocalPartition(t, p); localPartition != nil {
highWaterMark = localPartition.LogBuffer.GetOffset()
activeSubscriptions = int64(localPartition.Subscribers.Size())
} else {
var err error
if earliestOffset, highWaterMark, err = b.getOffsetRangeFromChunkMetadata(t, p); err != nil {
return nil, err
}
}
// Use the MAX of offset manager HWM and LogBuffer HWM
// This ensures we report the correct HWM even if data hasn't been flushed to disk yet
// IMPORTANT: Use >= not > because when they're equal, we still want the correct value
highWaterMark := info.HighWaterMark
if logBufferHWM >= 0 && logBufferHWM > highWaterMark {
highWaterMark = logBufferHWM
} else if logBufferHWM >= 0 && logBufferHWM == highWaterMark && highWaterMark > 0 {
} else if logBufferHWM >= 0 {
}
// Latest offset is HWM - 1 (last assigned offset)
latestOffset := highWaterMark - 1
if highWaterMark == 0 {
latestOffset = -1 // No records
}
// Convert to broker-specific format
return &PartitionOffsetInfo{
Topic: t,
Partition: p,
EarliestOffset: info.EarliestOffset,
LatestOffset: latestOffset,
EarliestOffset: earliestOffset,
LatestOffset: highWaterMark - 1,
HighWaterMark: highWaterMark,
RecordCount: highWaterMark, // HWM equals record count (offsets 0 to HWM-1)
ActiveSubscriptions: info.ActiveSubscriptions,
RecordCount: highWaterMark - earliestOffset,
ActiveSubscriptions: activeSubscriptions,
}, nil
}
@@ -115,38 +38,3 @@ type PartitionOffsetInfo struct {
RecordCount int64
ActiveSubscriptions int64
}
// CreateOffsetSubscription creates an offset-based subscription through the broker
func (b *MessageQueueBroker) CreateOffsetSubscription(
subscriptionID string,
t topic.Topic,
p topic.Partition,
offsetType string, // Will be converted to schema_pb.OffsetType
startOffset int64,
) error {
// TODO: Convert string offsetType to schema_pb.OffsetType
// ASSUMPTION: For now using RESET_TO_EARLIEST as default
// This should be properly mapped based on the offsetType parameter
_, err := b.offsetManager.CreateSubscription(
subscriptionID,
t,
p,
0, // schema_pb.OffsetType_RESET_TO_EARLIEST
startOffset,
)
return err
}
// GetOffsetMetrics returns offset metrics for monitoring
func (b *MessageQueueBroker) GetOffsetMetrics() map[string]interface{} {
metrics := b.offsetManager.GetOffsetMetrics()
return map[string]interface{}{
"partition_count": metrics.PartitionCount,
"total_offsets": metrics.TotalOffsets,
"active_subscriptions": metrics.ActiveSubscriptions,
"average_latency": metrics.AverageLatency,
}
}
@@ -0,0 +1,67 @@
package broker
import (
"encoding/binary"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/mq"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
)
// A loaded partition's buffer assigns offsets, so it is the high water mark.
func TestPartitionOffsetInfoFromLoadedBuffer(t *testing.T) {
b := newUnelectedBroker()
b.localTopicManager = topic.NewLocalTopicManager()
tp := topic.NewTopic("test", "t")
partition := topic.Partition{RingSize: 2520, RangeStart: 0, RangeStop: 2520, UnixTimeNs: time.Now().UnixNano()}
lp := topic.NewLocalPartition(partition, 3600, nil, nil)
defer lp.Shutdown()
b.localTopicManager.AddLocalPartition(tp, lp)
for i := 0; i < 3; i++ {
if _, err := lp.PublishWithOffset(&mq_pb.DataMessage{Key: []byte("k"), Value: []byte("v"), TsNs: time.Now().UnixNano()}); err != nil {
t.Fatal(err)
}
}
info, err := b.GetPartitionOffsetInfoInternal(tp, partition)
if err != nil {
t.Fatal(err)
}
if info.HighWaterMark != 3 || info.LatestOffset != 2 || info.RecordCount != 3 {
t.Fatalf("info = %+v, want hwm 3, latest 2, count 3", info)
}
}
// A subscriber or fetch naming a stale generation of an assigned range loads
// the assigned generation and continues its stored offsets.
func TestStaleGenerationRequestLoadsTheAssignedPartition(t *testing.T) {
tp := topic.NewTopic("test", "t")
assigned := topic.Partition{RingSize: 2520, RangeStart: 0, RangeStop: 2520, UnixTimeNs: time.Now().UnixNano()}
f, b := newFencingFiler(t)
offsetMax := make([]byte, 8)
binary.BigEndian.PutUint64(offsetMax, 41)
f.entries[topic.PartitionDir(tp, assigned)+"/segment"] = &filer_pb.Entry{Name: "segment", Extended: map[string][]byte{mq.ExtendedAttrOffsetMax: offsetMax}}
b.localTopicManager = topic.NewLocalTopicManager()
conf := &mq_pb.ConfigureTopicResponse{BrokerPartitionAssignments: []*mq_pb.BrokerPartitionAssignment{{
LeaderBroker: string(b.option.BrokerAddress()),
Partition: &schema_pb.Partition{RingSize: assigned.RingSize, RangeStart: assigned.RangeStart, RangeStop: assigned.RangeStop, UnixTimeNs: assigned.UnixTimeNs},
}}}
stale := assigned
stale.UnixTimeNs = 0
lp, generated, err := b.doGetOrGenLocalPartition(tp, stale, conf)
if err != nil || !generated {
t.Fatalf("generated=%v err=%v", generated, err)
}
defer lp.Shutdown()
if lp.Partition.UnixTimeNs != assigned.UnixTimeNs {
t.Errorf("loaded generation %d, assigned %d", lp.Partition.UnixTimeNs, assigned.UnixTimeNs)
}
if next := lp.LogBuffer.GetOffset(); next != 42 {
t.Errorf("next offset %d, want 42 after the stored offsets", next)
}
}
+3 -152
View File
@@ -2,173 +2,24 @@ package broker
import (
"fmt"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer_client"
"github.com/seaweedfs/seaweedfs/weed/mq/offset"
"github.com/seaweedfs/seaweedfs/weed/mq/topic"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
)
// BrokerOffsetManager manages offset assignment for all partitions in a broker
// BrokerOffsetManager keeps consumer-group positions. Publish offsets are
// assigned by each partition's log buffer.
type BrokerOffsetManager struct {
mu sync.RWMutex
offsetIntegration *offset.SMQOffsetIntegration
storage offset.OffsetStorage
consumerGroupStorage offset.ConsumerGroupOffsetStorage
}
// NewBrokerOffsetManagerWithFilerAccessor creates a new broker offset manager using existing filer client accessor
func NewBrokerOffsetManagerWithFilerAccessor(filerAccessor *filer_client.FilerClientAccessor) *BrokerOffsetManager {
// Create filer storage using the accessor directly - no duplicate connection management
filerStorage := offset.NewFilerOffsetStorageWithAccessor(filerAccessor)
// Create consumer group storage using the accessor directly
consumerGroupStorage := offset.NewFilerConsumerGroupOffsetStorageWithAccessor(filerAccessor)
return &BrokerOffsetManager{
offsetIntegration: offset.NewSMQOffsetIntegration(filerStorage),
storage: filerStorage,
consumerGroupStorage: consumerGroupStorage,
consumerGroupStorage: offset.NewFilerConsumerGroupOffsetStorageWithAccessor(filerAccessor),
}
}
// AssignOffset assigns the next offset for a partition
func (bom *BrokerOffsetManager) AssignOffset(t topic.Topic, p topic.Partition) (int64, error) {
partition := topicPartitionToSchemaPartition(t, p)
// Use the integration layer's offset assigner to ensure consistency with subscriptions
result := bom.offsetIntegration.AssignSingleOffset(t.Namespace, t.Name, partition)
if result.Error != nil {
return 0, result.Error
}
return result.Assignment.Offset, nil
}
// AssignBatchOffsets assigns a batch of offsets for a partition
func (bom *BrokerOffsetManager) AssignBatchOffsets(t topic.Topic, p topic.Partition, count int64) (baseOffset, lastOffset int64, err error) {
partition := topicPartitionToSchemaPartition(t, p)
// Use the integration layer's offset assigner to ensure consistency with subscriptions
result := bom.offsetIntegration.AssignBatchOffsets(t.Namespace, t.Name, partition, count)
if result.Error != nil {
return 0, 0, result.Error
}
return result.Batch.BaseOffset, result.Batch.LastOffset, nil
}
// GetHighWaterMark returns the high water mark for a partition
func (bom *BrokerOffsetManager) GetHighWaterMark(t topic.Topic, p topic.Partition) (int64, error) {
partition := topicPartitionToSchemaPartition(t, p)
// Use the integration layer's offset assigner to ensure consistency with subscriptions
return bom.offsetIntegration.GetHighWaterMark(t.Namespace, t.Name, partition)
}
// CreateSubscription creates an offset-based subscription
func (bom *BrokerOffsetManager) CreateSubscription(
subscriptionID string,
t topic.Topic,
p topic.Partition,
offsetType schema_pb.OffsetType,
startOffset int64,
) (*offset.OffsetSubscription, error) {
partition := topicPartitionToSchemaPartition(t, p)
return bom.offsetIntegration.CreateSubscription(subscriptionID, t.Namespace, t.Name, partition, offsetType, startOffset)
}
// GetSubscription retrieves an existing subscription
func (bom *BrokerOffsetManager) GetSubscription(subscriptionID string) (*offset.OffsetSubscription, error) {
return bom.offsetIntegration.GetSubscription(subscriptionID)
}
// CloseSubscription closes a subscription
func (bom *BrokerOffsetManager) CloseSubscription(subscriptionID string) error {
return bom.offsetIntegration.CloseSubscription(subscriptionID)
}
// ListActiveSubscriptions returns all active subscriptions
func (bom *BrokerOffsetManager) ListActiveSubscriptions() ([]*offset.OffsetSubscription, error) {
return bom.offsetIntegration.ListActiveSubscriptions()
}
// GetPartitionOffsetInfo returns comprehensive offset information for a partition
func (bom *BrokerOffsetManager) GetPartitionOffsetInfo(t topic.Topic, p topic.Partition) (*offset.PartitionOffsetInfo, error) {
partition := topicPartitionToSchemaPartition(t, p)
// Use the integration layer to ensure consistency with subscriptions
return bom.offsetIntegration.GetPartitionOffsetInfo(t.Namespace, t.Name, partition)
}
// topicPartitionToSchemaPartition converts topic.Topic and topic.Partition to schema_pb.Partition
func topicPartitionToSchemaPartition(t topic.Topic, p topic.Partition) *schema_pb.Partition {
return &schema_pb.Partition{
RingSize: int32(p.RingSize),
RangeStart: int32(p.RangeStart),
RangeStop: int32(p.RangeStop),
UnixTimeNs: p.UnixTimeNs,
}
}
// OffsetAssignmentResult contains the result of offset assignment for logging/metrics
type OffsetAssignmentResult struct {
Topic topic.Topic
Partition topic.Partition
BaseOffset int64
LastOffset int64
Count int64
Timestamp int64
Error error
}
// AssignOffsetsWithResult assigns offsets and returns detailed result for logging/metrics
func (bom *BrokerOffsetManager) AssignOffsetsWithResult(t topic.Topic, p topic.Partition, count int64) *OffsetAssignmentResult {
baseOffset, lastOffset, err := bom.AssignBatchOffsets(t, p, count)
result := &OffsetAssignmentResult{
Topic: t,
Partition: p,
Count: count,
Error: err,
}
if err == nil {
result.BaseOffset = baseOffset
result.LastOffset = lastOffset
result.Timestamp = time.Now().UnixNano()
}
return result
}
// GetOffsetMetrics returns metrics about offset usage across all partitions
func (bom *BrokerOffsetManager) GetOffsetMetrics() *offset.OffsetMetrics {
// Use the integration layer to ensure consistency with subscriptions
return bom.offsetIntegration.GetOffsetMetrics()
}
// Shutdown gracefully shuts down the offset manager
func (bom *BrokerOffsetManager) Shutdown() {
bom.mu.Lock()
defer bom.mu.Unlock()
// Reset the underlying storage to ensure clean restart behavior
// This is important for testing where we want offsets to start from 0 after shutdown
if bom.storage != nil {
if resettable, ok := bom.storage.(interface{ Reset() error }); ok {
resettable.Reset()
}
}
// Reset the integration layer to ensure clean restart behavior
bom.offsetIntegration.Reset()
}
// Consumer Group Offset Management
// SaveConsumerGroupOffset saves the committed offset for a consumer group
func (bom *BrokerOffsetManager) SaveConsumerGroupOffset(t topic.Topic, p topic.Partition, consumerGroup string, offset int64) error {
if bom.consumerGroupStorage == nil {
+4 -1
View File
@@ -38,7 +38,10 @@ func (b *MessageQueueBroker) newLeaderPartition(t topic.Topic, partition topic.P
}
localPartition := topic.NewLocalPartition(partition, b.option.LogFlushInterval, b.genLogFlushFunc(t, partition, fence), logstore.GenMergedReadFunc(b, t, partition))
localPartition.Fence = fence
b.initializePartitionOffsetFromExistingData(localPartition, t, partition)
if err := b.initializePartitionOffsetFromExistingData(localPartition, t, partition); err != nil {
localPartition.Shutdown()
return nil, err
}
return localPartition, nil
}
+35 -5
View File
@@ -8,6 +8,7 @@ import (
"net/http"
"net/http/httptest"
"slices"
"sort"
"strings"
"sync"
"sync/atomic"
@@ -53,6 +54,34 @@ type fencingFiler struct {
uploadGate chan struct{}
}
func (f *fencingFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error {
f.mu.Lock()
var names []string
children := map[string]*filer_pb.Entry{}
for path, entry := range f.entries {
if dir, name := util.FullPath(path).DirAndName(); dir == req.Directory {
names = append(names, name)
children[name] = proto.Clone(entry).(*filer_pb.Entry)
}
}
f.mu.Unlock()
sort.Strings(names)
sent := uint32(0)
for _, name := range names {
if name < req.StartFromFileName || (name == req.StartFromFileName && !req.InclusiveStartFrom) {
continue
}
if req.Limit > 0 && sent >= req.Limit {
break
}
if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: children[name]}); err != nil {
return err
}
sent++
}
return nil
}
func (f *fencingFiler) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
f.mu.Lock()
if f.stalled {
@@ -167,12 +196,17 @@ func newFencingFiler(t *testing.T) (*fencingFiler, *MessageQueueBroker) {
flushCtx, flushCancel := context.WithCancel(context.Background())
t.Cleanup(flushCancel)
return f, &MessageQueueBroker{
b := &MessageQueueBroker{
option: &MessageQueueBrokerOption{Ip: "127.0.0.1", Port: 17777},
grpcDialOption: grpc.WithTransportCredentials(insecure.NewCredentials()),
currentFiler: pb.NewServerAddressWithGrpcPort(listener.Addr().String(), listener.Addr().(*net.TCPAddr).Port),
flushCtx: flushCtx,
}
b.fca = &filer_client.FilerClientAccessor{
GetGrpcDialOption: b.GetGrpcDialOption,
GetFilers: func() []pb.ServerAddress { return []pb.ServerAddress{b.GetFiler()} },
}
return f, b
}
var (
@@ -313,10 +347,6 @@ func TestTakeFenceGivesUpOnAStalledFiler(t *testing.T) {
func TestReassignedLeaderReplacesItsFencedPartition(t *testing.T) {
f, b := newFencingFiler(t)
b.localTopicManager = topic.NewLocalTopicManager()
b.fca = &filer_client.FilerClientAccessor{
GetGrpcDialOption: b.GetGrpcDialOption,
GetFilers: func() []pb.ServerAddress { return []pb.ServerAddress{b.GetFiler()} },
}
assign := func(epoch int64) {
t.Helper()
if _, err := b.AssignTopicPartitions(context.Background(), &mq_pb.AssignTopicPartitionsRequest{
+32 -146
View File
@@ -4,8 +4,6 @@ import (
"context"
"errors"
"fmt"
"io"
"strings"
"time"
"github.com/seaweedfs/seaweedfs/weed/glog"
@@ -134,20 +132,29 @@ func (b *MessageQueueBroker) getTopicConfFromCache(t topic.Topic) (*mq_pb.Config
}
func (b *MessageQueueBroker) doGetOrGenLocalPartition(t topic.Topic, partition topic.Partition, conf *mq_pb.ConfigureTopicResponse) (localPartition *topic.LocalPartition, isGenerated bool, err error) {
b.accessLock.Lock()
defer b.accessLock.Unlock()
localPartition = b.localTopicManager.GetLocalPartition(t, partition)
for b.retireStaleLeader(t, localPartition, b.assignedLeaderEpoch(partition, conf)) {
for {
b.accessLock.Lock()
localPartition = b.localTopicManager.GetLocalPartition(t, partition)
}
if localPartition == nil {
for b.retireStaleLeader(t, localPartition, b.assignedLeaderEpoch(partition, conf)) {
localPartition = b.localTopicManager.GetLocalPartition(t, partition)
}
if localPartition != nil {
b.accessLock.Unlock()
return localPartition, false, nil
}
if b.localTopicManager.RetiringPartition(t, partition) != nil {
// its flush takes accessLock, so wait without it
b.accessLock.Unlock()
b.localTopicManager.WaitRetired(context.Background(), t, partition)
continue
}
localPartition, isGenerated, err = b.genLocalPartitionFromFiler(t, partition, conf)
b.accessLock.Unlock()
if err != nil {
return nil, false, err
}
return localPartition, isGenerated, nil
}
return localPartition, isGenerated, nil
}
// assignedLeaderEpoch is the epoch of conf's assignment making this broker the
@@ -174,6 +181,7 @@ func (b *MessageQueueBroker) genLocalPartitionFromFiler(t topic.Topic, partition
glog.V(4).Infof("partition details: RangeStart=%d, RangeStop=%d, RingSize=%d, UnixTimeNs=%d", partition.RangeStart, partition.RangeStop, partition.RingSize, partition.UnixTimeNs)
glog.V(4).Infof("assignmentPartition details: RangeStart=%d, RangeStop=%d, RingSize=%d, UnixTimeNs=%d", assignmentPartition.RangeStart, assignmentPartition.RangeStop, assignmentPartition.RingSize, assignmentPartition.UnixTimeNs)
if pb.ServerAddress(assignment.LeaderBroker).Equals(self) && partition.LogicalEquals(assignmentPartition) {
partition = assignmentPartition
glog.V(4).Infof("Creating local partition for %s %s", t, partition)
if localPartition, err = b.newLeaderPartition(t, partition, assignment.Epoch); err != nil {
return nil, false, err
@@ -221,150 +229,28 @@ func (b *MessageQueueBroker) ensureTopicActiveAssignments(t topic.Topic, conf *m
return err
}
// initializePartitionOffsetFromExistingData initializes the LogBuffer offset from existing data on filer
// This ensures offset continuity when SMQ restarts
func (b *MessageQueueBroker) initializePartitionOffsetFromExistingData(localPartition *topic.LocalPartition, t topic.Topic, partition topic.Partition) {
// Create a function to get the highest existing offset from chunk metadata
getHighestOffsetFn := func() (int64, error) {
// Use the existing chunk metadata approach to find the highest offset
if b.fca == nil {
return -1, fmt.Errorf("no filer client accessor available")
}
// Use the same logic as getOffsetRangeFromChunkMetadata but only get the highest offset
// initializePartitionOffsetFromExistingData continues the partition's offsets above
// what is already stored. A partition whose stored offsets cannot be read is not served.
func (b *MessageQueueBroker) initializePartitionOffsetFromExistingData(localPartition *topic.LocalPartition, t topic.Topic, partition topic.Partition) error {
err := localPartition.LogBuffer.InitializeOffsetFromExistingData(func() (int64, error) {
_, highWaterMark, err := b.getOffsetRangeFromChunkMetadata(t, partition)
if err != nil {
return -1, err
}
// The high water mark is the next offset to be assigned, so the highest existing offset is hwm - 1
if highWaterMark > 0 {
return highWaterMark - 1, nil
}
return -1, nil // No existing data
}
// Initialize the LogBuffer offset from existing data
if err := localPartition.LogBuffer.InitializeOffsetFromExistingData(getHighestOffsetFn); err != nil {
glog.V(0).Infof("Failed to initialize offset for partition %s %s: %v", t, partition, err)
return highWaterMark - 1, err
})
if err != nil {
return fmt.Errorf("topic %s partition %s: %w", t, partition, err)
}
return nil
}
// getOffsetRangeFromChunkMetadata reads chunk metadata to find both earliest and latest offsets
// getOffsetRangeFromChunkMetadata reads the offset range recorded on the partition's files.
func (b *MessageQueueBroker) getOffsetRangeFromChunkMetadata(t topic.Topic, partition topic.Partition) (earliestOffset int64, highWaterMark int64, err error) {
if b.fca == nil {
return 0, 0, fmt.Errorf("filer client accessor not available")
}
// Get the topic path and find the latest version
topicPath := fmt.Sprintf("/topics/%s/%s", t.Namespace, t.Name)
// First, list the topic versions to find the latest
var latestVersion string
err = b.fca.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
stream, err := client.ListEntries(context.Background(), &filer_pb.ListEntriesRequest{
Directory: topicPath,
})
if err != nil {
return err
}
for {
resp, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
return err
}
if resp.Entry != nil && resp.Entry.IsDirectory && strings.HasPrefix(resp.Entry.Name, "v") {
if latestVersion == "" || resp.Entry.Name > latestVersion {
latestVersion = resp.Entry.Name
}
}
}
return nil
var scanErr error
earliestOffset, highWaterMark, scanErr = mq.ReadOffsetRange(context.Background(), client, topic.PartitionDir(t, partition))
return scanErr
})
if err != nil {
return 0, 0, fmt.Errorf("failed to list topic versions: %v", err)
}
if latestVersion == "" {
glog.V(0).Infof("No version directory found for topic %s", t)
return 0, 0, nil
}
// Find the partition directory
versionPath := fmt.Sprintf("%s/%s", topicPath, latestVersion)
var partitionDir string
err = b.fca.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
stream, err := client.ListEntries(context.Background(), &filer_pb.ListEntriesRequest{
Directory: versionPath,
})
if err != nil {
return err
}
// Look for the partition directory that matches our partition range
targetPartitionName := fmt.Sprintf("%04d-%04d", partition.RangeStart, partition.RangeStop)
for {
resp, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
return err
}
if resp.Entry != nil && resp.Entry.IsDirectory && resp.Entry.Name == targetPartitionName {
partitionDir = resp.Entry.Name
break
}
}
return nil
})
if err != nil {
return 0, 0, fmt.Errorf("failed to list partition directories: %v", err)
}
if partitionDir == "" {
glog.V(0).Infof("No partition directory found for topic %s partition %s", t, partition)
return 0, 0, nil
}
// Scan all message files to find the highest offset_max and lowest offset_min
partitionPath := fmt.Sprintf("%s/%s", versionPath, partitionDir)
var offsetRange mq.OffsetRange
err = b.fca.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
stream, err := client.ListEntries(context.Background(), &filer_pb.ListEntriesRequest{
Directory: partitionPath,
})
if err != nil {
return err
}
for {
resp, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
return err
}
if resp.Entry != nil && !resp.Entry.IsDirectory && resp.Entry.Name != "checkpoint.offset" {
// Check for offset ranges in Extended attributes (both log files and parquet files)
offsetRange.Add(resp.Entry.Extended)
}
}
return nil
})
if err != nil {
return 0, 0, fmt.Errorf("failed to scan message files: %v", err)
}
earliestOffset, highWaterMark = offsetRange.Bounds()
glog.V(0).Infof("Offset range for topic %s partition %s: earliest=%d, highWaterMark=%d", t, partition, earliestOffset, highWaterMark)
return earliestOffset, highWaterMark, nil
return
}
-199
View File
@@ -1,199 +0,0 @@
package broker
import (
"fmt"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/mq/offset"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
)
// recordEntry holds a record with timestamp for TTL cleanup
type recordEntry struct {
exists bool
timestamp time.Time
}
// InMemoryOffsetStorage provides an in-memory implementation of OffsetStorage for testing ONLY
// This is a copy of the implementation in weed/mq/offset/memory_storage_test.go
type InMemoryOffsetStorage struct {
mu sync.RWMutex
checkpoints map[string]int64 // partition key -> offset
records map[string]map[int64]*recordEntry // partition key -> offset -> entry with timestamp
// Memory leak protection
maxRecordsPerPartition int // Maximum records to keep per partition
recordTTL time.Duration // TTL for record entries
lastCleanup time.Time // Last cleanup time
cleanupInterval time.Duration // How often to run cleanup
}
// NewInMemoryOffsetStorage creates a new in-memory storage with memory leak protection
// FOR TESTING ONLY - do not use in production
func NewInMemoryOffsetStorage() *InMemoryOffsetStorage {
return &InMemoryOffsetStorage{
checkpoints: make(map[string]int64),
records: make(map[string]map[int64]*recordEntry),
maxRecordsPerPartition: 10000, // Limit to 10K records per partition
recordTTL: 1 * time.Hour, // Records expire after 1 hour
cleanupInterval: 5 * time.Minute, // Cleanup every 5 minutes
lastCleanup: time.Now(),
}
}
// SaveCheckpoint saves the checkpoint for a partition
func (s *InMemoryOffsetStorage) SaveCheckpoint(namespace, topicName string, partition *schema_pb.Partition, off int64) error {
s.mu.Lock()
defer s.mu.Unlock()
key := offset.PartitionKey(partition)
s.checkpoints[key] = off
return nil
}
// LoadCheckpoint loads the checkpoint for a partition
func (s *InMemoryOffsetStorage) LoadCheckpoint(namespace, topicName string, partition *schema_pb.Partition) (int64, error) {
s.mu.RLock()
defer s.mu.RUnlock()
key := offset.PartitionKey(partition)
off, exists := s.checkpoints[key]
if !exists {
return -1, fmt.Errorf("no checkpoint found")
}
return off, nil
}
// GetHighestOffset finds the highest offset in storage for a partition
func (s *InMemoryOffsetStorage) GetHighestOffset(namespace, topicName string, partition *schema_pb.Partition) (int64, error) {
s.mu.RLock()
defer s.mu.RUnlock()
key := offset.PartitionKey(partition)
offsets, exists := s.records[key]
if !exists || len(offsets) == 0 {
return -1, fmt.Errorf("no records found")
}
var highest int64 = -1
for off, entry := range offsets {
if entry.exists && off > highest {
highest = off
}
}
return highest, nil
}
// AddRecord simulates storing a record with an offset (for testing)
func (s *InMemoryOffsetStorage) AddRecord(partition *schema_pb.Partition, off int64) {
s.mu.Lock()
defer s.mu.Unlock()
key := offset.PartitionKey(partition)
if s.records[key] == nil {
s.records[key] = make(map[int64]*recordEntry)
}
// Add record with current timestamp
s.records[key][off] = &recordEntry{
exists: true,
timestamp: time.Now(),
}
// Trigger cleanup if needed (memory leak protection)
s.cleanupIfNeeded()
}
// Reset removes all data (implements resettable interface for shutdown)
func (s *InMemoryOffsetStorage) Reset() error {
s.mu.Lock()
defer s.mu.Unlock()
s.checkpoints = make(map[string]int64)
s.records = make(map[string]map[int64]*recordEntry)
s.lastCleanup = time.Now()
return nil
}
// cleanupIfNeeded performs memory leak protection cleanup
// This method assumes the caller already holds the write lock
func (s *InMemoryOffsetStorage) cleanupIfNeeded() {
now := time.Now()
// Only cleanup if enough time has passed
if now.Sub(s.lastCleanup) < s.cleanupInterval {
return
}
s.lastCleanup = now
cutoff := now.Add(-s.recordTTL)
// Clean up expired records and enforce size limits
for partitionKey, offsets := range s.records {
// Remove expired records
for offset, entry := range offsets {
if entry.timestamp.Before(cutoff) {
delete(offsets, offset)
}
}
// Enforce size limit per partition
if len(offsets) > s.maxRecordsPerPartition {
// Keep only the most recent records
type offsetTime struct {
offset int64
time time.Time
}
var entries []offsetTime
for offset, entry := range offsets {
entries = append(entries, offsetTime{offset: offset, time: entry.timestamp})
}
// Sort by timestamp (newest first)
for i := 0; i < len(entries)-1; i++ {
for j := i + 1; j < len(entries); j++ {
if entries[i].time.Before(entries[j].time) {
entries[i], entries[j] = entries[j], entries[i]
}
}
}
// Keep only the newest maxRecordsPerPartition entries
newOffsets := make(map[int64]*recordEntry)
for i := 0; i < s.maxRecordsPerPartition && i < len(entries); i++ {
offset := entries[i].offset
newOffsets[offset] = offsets[offset]
}
s.records[partitionKey] = newOffsets
}
// Remove empty partition maps
if len(offsets) == 0 {
delete(s.records, partitionKey)
}
}
}
// NewInMemoryOffsetStorageForTesting creates an InMemoryOffsetStorage for testing purposes
func NewInMemoryOffsetStorageForTesting() offset.OffsetStorage {
return NewInMemoryOffsetStorage()
}
// NewBrokerOffsetManagerWithStorage creates a new broker offset manager with custom storage
// FOR TESTING ONLY - moved from production code since it's only used in tests
func NewBrokerOffsetManagerWithStorage(storage offset.OffsetStorage) *BrokerOffsetManager {
if storage == nil {
panic("BrokerOffsetManager requires a storage implementation. Use NewBrokerOffsetManagerWithFiler() or provide FilerOffsetStorage/SQLOffsetStorage. InMemoryOffsetStorage is only for testing.")
}
return &BrokerOffsetManager{
offsetIntegration: offset.NewSMQOffsetIntegration(storage),
storage: storage,
consumerGroupStorage: nil, // Will be set separately if needed
}
}
+3 -27
View File
@@ -309,39 +309,15 @@ func (bc *BrokerClient) getOffsetRangeFromChunkMetadata(topic string, partition
return 0, 0, nil
}
// Scan all message files to find the highest offset_max and lowest offset_min
partitionPath := fmt.Sprintf("%s/%s", versionPath, partitionDir)
var offsetRange mq.OffsetRange
err = bc.filerClientAccessor.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
stream, err := client.ListEntries(context.Background(), &filer_pb.ListEntriesRequest{
Directory: partitionPath,
})
if err != nil {
return err
}
for {
resp, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
return err
}
if resp.Entry != nil && !resp.Entry.IsDirectory && resp.Entry.Name != "checkpoint.offset" {
// Check for offset ranges in Extended attributes (both log files and parquet files)
offsetRange.Add(resp.Entry.Extended)
}
}
return nil
var scanErr error
earliestOffset, highWaterMark, scanErr = mq.ReadOffsetRange(context.Background(), client, partitionPath)
return scanErr
})
if err != nil {
return 0, 0, fmt.Errorf("failed to scan message files: %v", err)
}
earliestOffset, highWaterMark = offsetRange.Bounds()
return earliestOffset, highWaterMark, nil
}
-305
View File
@@ -1,305 +0,0 @@
package offset
import (
"fmt"
"testing"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
)
// BenchmarkOffsetAssignment benchmarks sequential offset assignment
func BenchmarkOffsetAssignment(b *testing.B) {
storage := NewInMemoryOffsetStorage()
partition := &schema_pb.Partition{
RingSize: 1024,
RangeStart: 0,
RangeStop: 31,
UnixTimeNs: time.Now().UnixNano(),
}
manager, err := NewPartitionOffsetManager("test-namespace", "test-topic", partition, storage)
if err != nil {
b.Fatalf("Failed to create partition manager: %v", err)
}
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
manager.AssignOffset()
}
})
}
// BenchmarkBatchOffsetAssignment benchmarks batch offset assignment
func BenchmarkBatchOffsetAssignment(b *testing.B) {
storage := NewInMemoryOffsetStorage()
partition := &schema_pb.Partition{
RingSize: 1024,
RangeStart: 0,
RangeStop: 31,
UnixTimeNs: time.Now().UnixNano(),
}
manager, err := NewPartitionOffsetManager("test-namespace", "test-topic", partition, storage)
if err != nil {
b.Fatalf("Failed to create partition manager: %v", err)
}
batchSizes := []int64{1, 10, 100, 1000}
for _, batchSize := range batchSizes {
b.Run(fmt.Sprintf("BatchSize%d", batchSize), func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
manager.AssignOffsets(batchSize)
}
})
}
}
// BenchmarkOffsetSubscription benchmarks subscription operations
func BenchmarkOffsetSubscription(b *testing.B) {
storage := NewInMemoryOffsetStorage()
registry := NewPartitionOffsetRegistry(storage)
subscriber := NewOffsetSubscriber(registry)
partition := &schema_pb.Partition{
RingSize: 1024,
RangeStart: 0,
RangeStop: 31,
UnixTimeNs: time.Now().UnixNano(),
}
// Pre-assign offsets
registry.AssignOffsets("test-namespace", "test-topic", partition, 10000)
b.Run("CreateSubscription", func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
subscriptionID := fmt.Sprintf("bench-sub-%d", i)
_, err := subscriber.CreateSubscription(
subscriptionID,
"test-namespace", "test-topic",
partition,
schema_pb.OffsetType_RESET_TO_EARLIEST,
0,
)
if err != nil {
b.Fatalf("Failed to create subscription: %v", err)
}
subscriber.CloseSubscription(subscriptionID)
}
})
// Create subscription for other benchmarks
sub, err := subscriber.CreateSubscription(
"bench-sub",
"test-namespace", "test-topic",
partition,
schema_pb.OffsetType_RESET_TO_EARLIEST,
0,
)
if err != nil {
b.Fatalf("Failed to create subscription: %v", err)
}
b.Run("GetOffsetRange", func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
sub.GetOffsetRange(100)
}
})
b.Run("AdvanceOffset", func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
sub.AdvanceOffset()
}
})
b.Run("GetLag", func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
sub.GetLag()
}
})
b.Run("SeekToOffset", func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
offset := int64(i % 9000) // Stay within bounds
sub.SeekToOffset(offset)
}
})
}
// BenchmarkSMQOffsetIntegration benchmarks the full integration layer
func BenchmarkSMQOffsetIntegration(b *testing.B) {
storage := NewInMemoryOffsetStorage()
integration := NewSMQOffsetIntegration(storage)
partition := &schema_pb.Partition{
RingSize: 1024,
RangeStart: 0,
RangeStop: 31,
UnixTimeNs: time.Now().UnixNano(),
}
b.Run("PublishRecord", func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
key := fmt.Sprintf("key-%d", i)
integration.PublishRecord("test-namespace", "test-topic", partition, []byte(key), &schema_pb.RecordValue{})
}
})
b.Run("PublishRecordBatch", func(b *testing.B) {
batchSizes := []int{1, 10, 100}
for _, batchSize := range batchSizes {
b.Run(fmt.Sprintf("BatchSize%d", batchSize), func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
records := make([]PublishRecordRequest, batchSize)
for j := 0; j < batchSize; j++ {
records[j] = PublishRecordRequest{
Key: []byte(fmt.Sprintf("batch-%d-key-%d", i, j)),
Value: &schema_pb.RecordValue{},
}
}
integration.PublishRecordBatch("test-namespace", "test-topic", partition, records)
}
})
}
})
// Pre-populate for subscription benchmarks
records := make([]PublishRecordRequest, 1000)
for i := 0; i < 1000; i++ {
records[i] = PublishRecordRequest{
Key: []byte(fmt.Sprintf("pre-key-%d", i)),
Value: &schema_pb.RecordValue{},
}
}
integration.PublishRecordBatch("test-namespace", "test-topic", partition, records)
b.Run("CreateSubscription", func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
subscriptionID := fmt.Sprintf("integration-sub-%d", i)
_, err := integration.CreateSubscription(
subscriptionID,
"test-namespace", "test-topic",
partition,
schema_pb.OffsetType_RESET_TO_EARLIEST,
0,
)
if err != nil {
b.Fatalf("Failed to create subscription: %v", err)
}
integration.CloseSubscription(subscriptionID)
}
})
b.Run("GetHighWaterMark", func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
integration.GetHighWaterMark("test-namespace", "test-topic", partition)
}
})
b.Run("GetPartitionOffsetInfo", func(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
integration.GetPartitionOffsetInfo("test-namespace", "test-topic", partition)
}
})
}
// BenchmarkConcurrentOperations benchmarks concurrent offset operations
func BenchmarkConcurrentOperations(b *testing.B) {
storage := NewInMemoryOffsetStorage()
integration := NewSMQOffsetIntegration(storage)
partition := &schema_pb.Partition{
RingSize: 1024,
RangeStart: 0,
RangeStop: 31,
UnixTimeNs: time.Now().UnixNano(),
}
b.Run("ConcurrentPublish", func(b *testing.B) {
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
i := 0
for pb.Next() {
key := fmt.Sprintf("concurrent-key-%d", i)
integration.PublishRecord("test-namespace", "test-topic", partition, []byte(key), &schema_pb.RecordValue{})
i++
}
})
})
// Pre-populate for concurrent reads
for i := 0; i < 1000; i++ {
key := fmt.Sprintf("read-key-%d", i)
integration.PublishRecord("test-namespace", "test-topic", partition, []byte(key), &schema_pb.RecordValue{})
}
b.Run("ConcurrentRead", func(b *testing.B) {
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
integration.GetHighWaterMark("test-namespace", "test-topic", partition)
}
})
})
b.Run("ConcurrentMixed", func(b *testing.B) {
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
i := 0
for pb.Next() {
if i%10 == 0 {
// 10% writes
key := fmt.Sprintf("mixed-key-%d", i)
integration.PublishRecord("test-namespace", "test-topic", partition, []byte(key), &schema_pb.RecordValue{})
} else {
// 90% reads
integration.GetHighWaterMark("test-namespace", "test-topic", partition)
}
i++
}
})
})
}
// BenchmarkMemoryUsage benchmarks memory usage patterns
func BenchmarkMemoryUsage(b *testing.B) {
b.Run("InMemoryStorage", func(b *testing.B) {
storage := NewInMemoryOffsetStorage()
partition := &schema_pb.Partition{
RingSize: 1024,
RangeStart: 0,
RangeStop: 31,
UnixTimeNs: time.Now().UnixNano(),
}
manager, err := NewPartitionOffsetManager("test-namespace", "test-topic", partition, storage)
if err != nil {
b.Fatalf("Failed to create partition manager: %v", err)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
manager.AssignOffset()
// Note: Checkpointing now happens automatically in background every 2 seconds
}
// Clean up background goroutine
manager.Close()
})
}
-95
View File
@@ -1,95 +0,0 @@
package offset
import (
"context"
"fmt"
"time"
"github.com/seaweedfs/seaweedfs/weed/filer"
"github.com/seaweedfs/seaweedfs/weed/filer_client"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
// FilerOffsetStorage implements OffsetStorage using SeaweedFS filer
// Stores offset data as files in the same directory structure as SMQ
// Path: /topics/{namespace}/{topic}/{version}/{partition}/checkpoint.offset
// The namespace and topic are derived from the actual partition information
type FilerOffsetStorage struct {
filerClientAccessor *filer_client.FilerClientAccessor
}
// NewFilerOffsetStorageWithAccessor creates a new filer-based offset storage using existing filer client accessor
func NewFilerOffsetStorageWithAccessor(filerClientAccessor *filer_client.FilerClientAccessor) *FilerOffsetStorage {
return &FilerOffsetStorage{
filerClientAccessor: filerClientAccessor,
}
}
// SaveCheckpoint saves the checkpoint for a partition
// Stores as: /topics/{namespace}/{topic}/{version}/{partition}/checkpoint.offset
func (f *FilerOffsetStorage) SaveCheckpoint(namespace, topicName string, partition *schema_pb.Partition, offset int64) error {
partitionDir := f.getPartitionDir(namespace, topicName, partition)
fileName := "checkpoint.offset"
// Use SMQ's 8-byte offset format
offsetBytes := make([]byte, 8)
util.Uint64toBytes(offsetBytes, uint64(offset))
return f.filerClientAccessor.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
return filer.SaveInsideFiler(context.Background(), client, partitionDir, fileName, offsetBytes)
})
}
// LoadCheckpoint loads the checkpoint for a partition
func (f *FilerOffsetStorage) LoadCheckpoint(namespace, topicName string, partition *schema_pb.Partition) (int64, error) {
partitionDir := f.getPartitionDir(namespace, topicName, partition)
fileName := "checkpoint.offset"
var offset int64 = -1
err := f.filerClientAccessor.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
data, err := filer.ReadInsideFiler(context.Background(), client, partitionDir, fileName)
if err != nil {
return err
}
if len(data) != 8 {
return fmt.Errorf("invalid checkpoint file format: expected 8 bytes, got %d", len(data))
}
offset = int64(util.BytesToUint64(data))
return nil
})
if err != nil {
return -1, err
}
return offset, nil
}
// GetHighestOffset returns the highest offset stored for a partition
// For filer storage, this is the same as the checkpoint since we don't store individual records
func (f *FilerOffsetStorage) GetHighestOffset(namespace, topicName string, partition *schema_pb.Partition) (int64, error) {
return f.LoadCheckpoint(namespace, topicName, partition)
}
// Reset clears all data for testing
func (f *FilerOffsetStorage) Reset() error {
// For testing, we could delete all offset files, but this is dangerous
// Instead, just return success - individual tests should clean up their own data
return nil
}
// Helper methods
// getPartitionDir returns the directory path for a partition following SMQ convention
// Format: /topics/{namespace}/{topic}/{version}/{partition}
func (f *FilerOffsetStorage) getPartitionDir(namespace, topicName string, partition *schema_pb.Partition) string {
// Generate version from UnixTimeNs
version := time.Unix(0, partition.UnixTimeNs).UTC().Format("v2006-01-02-15-04-05")
// Generate partition range string
partitionRange := fmt.Sprintf("%04d-%04d", partition.RangeStart, partition.RangeStop)
return fmt.Sprintf("%s/%s/%s/%s/%s", filer.TopicsDir, namespace, topicName, version, partitionRange)
}
-387
View File
@@ -1,387 +0,0 @@
package offset
import (
"fmt"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/mq_agent_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
)
// SMQOffsetIntegration provides integration between offset management and SMQ broker
type SMQOffsetIntegration struct {
mu sync.RWMutex
registry *PartitionOffsetRegistry
offsetAssigner *OffsetAssigner
offsetSubscriber *OffsetSubscriber
offsetSeeker *OffsetSeeker
}
// NewSMQOffsetIntegration creates a new SMQ offset integration
func NewSMQOffsetIntegration(storage OffsetStorage) *SMQOffsetIntegration {
registry := NewPartitionOffsetRegistry(storage)
assigner := &OffsetAssigner{registry: registry}
return &SMQOffsetIntegration{
registry: registry,
offsetAssigner: assigner,
offsetSubscriber: NewOffsetSubscriber(registry),
offsetSeeker: NewOffsetSeeker(registry),
}
}
// Close stops all background checkpoint goroutines and performs final checkpoints
func (integration *SMQOffsetIntegration) Close() error {
return integration.registry.Close()
}
// PublishRecord publishes a record and assigns it an offset
func (integration *SMQOffsetIntegration) PublishRecord(
namespace, topicName string,
partition *schema_pb.Partition,
key []byte,
value *schema_pb.RecordValue,
) (*mq_agent_pb.PublishRecordResponse, error) {
// Assign offset for this record
result := integration.offsetAssigner.AssignSingleOffset(namespace, topicName, partition)
if result.Error != nil {
return &mq_agent_pb.PublishRecordResponse{
Error: fmt.Sprintf("Failed to assign offset: %v", result.Error),
}, nil
}
assignment := result.Assignment
// Note: Removed in-memory mapping storage to prevent memory leaks
// Record-to-offset mappings are now handled by persistent storage layer
// Return response with offset information
return &mq_agent_pb.PublishRecordResponse{
AckSequence: assignment.Offset, // Use offset as ack sequence for now
BaseOffset: assignment.Offset,
LastOffset: assignment.Offset,
Error: "",
}, nil
}
// PublishRecordBatch publishes a batch of records and assigns them offsets
func (integration *SMQOffsetIntegration) PublishRecordBatch(
namespace, topicName string,
partition *schema_pb.Partition,
records []PublishRecordRequest,
) (*mq_agent_pb.PublishRecordResponse, error) {
if len(records) == 0 {
return &mq_agent_pb.PublishRecordResponse{
Error: "Empty record batch",
}, nil
}
// Assign batch of offsets
result := integration.offsetAssigner.AssignBatchOffsets(namespace, topicName, partition, int64(len(records)))
if result.Error != nil {
return &mq_agent_pb.PublishRecordResponse{
Error: fmt.Sprintf("Failed to assign batch offsets: %v", result.Error),
}, nil
}
batch := result.Batch
// Note: Removed in-memory mapping storage to prevent memory leaks
// Batch record-to-offset mappings are now handled by persistent storage layer
return &mq_agent_pb.PublishRecordResponse{
AckSequence: batch.LastOffset, // Use last offset as ack sequence
BaseOffset: batch.BaseOffset,
LastOffset: batch.LastOffset,
Error: "",
}, nil
}
// CreateSubscription creates an offset-based subscription
func (integration *SMQOffsetIntegration) CreateSubscription(
subscriptionID string,
namespace, topicName string,
partition *schema_pb.Partition,
offsetType schema_pb.OffsetType,
startOffset int64,
) (*OffsetSubscription, error) {
return integration.offsetSubscriber.CreateSubscription(
subscriptionID,
namespace, topicName,
partition,
offsetType,
startOffset,
)
}
// SubscribeRecords subscribes to records starting from a specific offset
func (integration *SMQOffsetIntegration) SubscribeRecords(
subscription *OffsetSubscription,
maxRecords int64,
) ([]*mq_agent_pb.SubscribeRecordResponse, error) {
if !subscription.IsActive {
return nil, fmt.Errorf("subscription is not active")
}
// Get the range of offsets to read
offsetRange, err := subscription.GetOffsetRange(maxRecords)
if err != nil {
return nil, fmt.Errorf("failed to get offset range: %w", err)
}
if offsetRange.Count == 0 {
// No records available
return []*mq_agent_pb.SubscribeRecordResponse{}, nil
}
// TODO: This is where we would integrate with SMQ's actual storage layer
// For now, return mock responses with offset information
responses := make([]*mq_agent_pb.SubscribeRecordResponse, offsetRange.Count)
for i := int64(0); i < offsetRange.Count; i++ {
offset := offsetRange.StartOffset + i
responses[i] = &mq_agent_pb.SubscribeRecordResponse{
Key: []byte(fmt.Sprintf("key-%d", offset)),
Value: &schema_pb.RecordValue{}, // Mock value
TsNs: offset * 1000000, // Mock timestamp based on offset
Offset: offset,
IsEndOfStream: false,
IsEndOfTopic: false,
Error: "",
}
}
// Advance the subscription
subscription.AdvanceOffsetBy(offsetRange.Count)
return responses, nil
}
// GetHighWaterMark returns the high water mark for a partition
func (integration *SMQOffsetIntegration) GetHighWaterMark(namespace, topicName string, partition *schema_pb.Partition) (int64, error) {
return integration.offsetAssigner.GetHighWaterMark(namespace, topicName, partition)
}
// SeekSubscription seeks a subscription to a specific offset
func (integration *SMQOffsetIntegration) SeekSubscription(
subscriptionID string,
offset int64,
) error {
subscription, err := integration.offsetSubscriber.GetSubscription(subscriptionID)
if err != nil {
return fmt.Errorf("subscription not found: %w", err)
}
return subscription.SeekToOffset(offset)
}
// GetSubscriptionLag returns the lag for a subscription
func (integration *SMQOffsetIntegration) GetSubscriptionLag(subscriptionID string) (int64, error) {
subscription, err := integration.offsetSubscriber.GetSubscription(subscriptionID)
if err != nil {
return 0, fmt.Errorf("subscription not found: %w", err)
}
return subscription.GetLag()
}
// CloseSubscription closes a subscription
func (integration *SMQOffsetIntegration) CloseSubscription(subscriptionID string) error {
return integration.offsetSubscriber.CloseSubscription(subscriptionID)
}
// ValidateOffsetRange validates an offset range for a partition
func (integration *SMQOffsetIntegration) ValidateOffsetRange(
namespace, topicName string,
partition *schema_pb.Partition,
startOffset, endOffset int64,
) error {
return integration.offsetSeeker.ValidateOffsetRange(namespace, topicName, partition, startOffset, endOffset)
}
// GetAvailableOffsetRange returns the available offset range for a partition
func (integration *SMQOffsetIntegration) GetAvailableOffsetRange(namespace, topicName string, partition *schema_pb.Partition) (*OffsetRange, error) {
return integration.offsetSeeker.GetAvailableOffsetRange(namespace, topicName, partition)
}
// PublishRecordRequest represents a record to be published
type PublishRecordRequest struct {
Key []byte
Value *schema_pb.RecordValue
}
// OffsetMetrics provides metrics about offset usage
type OffsetMetrics struct {
PartitionCount int64
TotalOffsets int64
ActiveSubscriptions int64
AverageLatency float64
}
// GetOffsetMetrics returns metrics about offset usage
func (integration *SMQOffsetIntegration) GetOffsetMetrics() *OffsetMetrics {
integration.mu.RLock()
defer integration.mu.RUnlock()
// Count active subscriptions
activeSubscriptions := int64(0)
for _, subscription := range integration.offsetSubscriber.subscriptions {
if subscription.IsActive {
activeSubscriptions++
}
}
// Calculate total offsets from all partition managers instead of in-memory map
var totalOffsets int64
for _, manager := range integration.offsetAssigner.registry.managers {
totalOffsets += manager.GetHighWaterMark()
}
return &OffsetMetrics{
PartitionCount: int64(len(integration.offsetAssigner.registry.managers)),
TotalOffsets: totalOffsets, // Now calculated from storage, not memory maps
ActiveSubscriptions: activeSubscriptions,
AverageLatency: 0.0, // TODO: Implement latency tracking
}
}
// OffsetInfo provides detailed information about an offset
type OffsetInfo struct {
Offset int64
Timestamp int64
Partition *schema_pb.Partition
Exists bool
}
// GetOffsetInfo returns detailed information about a specific offset
func (integration *SMQOffsetIntegration) GetOffsetInfo(
namespace, topicName string,
partition *schema_pb.Partition,
offset int64,
) (*OffsetInfo, error) {
hwm, err := integration.GetHighWaterMark(namespace, topicName, partition)
if err != nil {
return nil, fmt.Errorf("failed to get high water mark: %w", err)
}
exists := offset >= 0 && offset < hwm
// TODO: Get actual timestamp from storage
timestamp := int64(0)
// Note: Timestamp lookup from in-memory map removed to prevent memory leaks
// For now, use a placeholder timestamp. In production, this should come from
// persistent storage if timestamp tracking is needed.
if exists {
timestamp = time.Now().UnixNano() // Placeholder - should come from storage
}
return &OffsetInfo{
Offset: offset,
Timestamp: timestamp,
Partition: partition,
Exists: exists,
}, nil
}
// PartitionOffsetInfo provides offset information for a partition
type PartitionOffsetInfo struct {
Partition *schema_pb.Partition
EarliestOffset int64
LatestOffset int64
HighWaterMark int64
RecordCount int64
ActiveSubscriptions int64
}
// GetPartitionOffsetInfo returns comprehensive offset information for a partition
func (integration *SMQOffsetIntegration) GetPartitionOffsetInfo(namespace, topicName string, partition *schema_pb.Partition) (*PartitionOffsetInfo, error) {
hwm, err := integration.GetHighWaterMark(namespace, topicName, partition)
if err != nil {
return nil, fmt.Errorf("failed to get high water mark: %w", err)
}
earliestOffset := int64(0)
latestOffset := hwm - 1
if hwm == 0 {
latestOffset = -1 // No records
}
// Count active subscriptions for this partition
activeSubscriptions := int64(0)
integration.mu.RLock()
for _, subscription := range integration.offsetSubscriber.subscriptions {
if subscription.IsActive && partitionKey(subscription.Partition) == partitionKey(partition) {
activeSubscriptions++
}
}
integration.mu.RUnlock()
return &PartitionOffsetInfo{
Partition: partition,
EarliestOffset: earliestOffset,
LatestOffset: latestOffset,
HighWaterMark: hwm,
RecordCount: hwm,
ActiveSubscriptions: activeSubscriptions,
}, nil
}
// GetSubscription retrieves an existing subscription
func (integration *SMQOffsetIntegration) GetSubscription(subscriptionID string) (*OffsetSubscription, error) {
return integration.offsetSubscriber.GetSubscription(subscriptionID)
}
// ListActiveSubscriptions returns all active subscriptions
func (integration *SMQOffsetIntegration) ListActiveSubscriptions() ([]*OffsetSubscription, error) {
integration.mu.RLock()
defer integration.mu.RUnlock()
result := make([]*OffsetSubscription, 0)
for _, subscription := range integration.offsetSubscriber.subscriptions {
if subscription.IsActive {
result = append(result, subscription)
}
}
return result, nil
}
// AssignSingleOffset assigns a single offset for a partition
func (integration *SMQOffsetIntegration) AssignSingleOffset(namespace, topicName string, partition *schema_pb.Partition) *AssignmentResult {
return integration.offsetAssigner.AssignSingleOffset(namespace, topicName, partition)
}
// AssignBatchOffsets assigns a batch of offsets for a partition
func (integration *SMQOffsetIntegration) AssignBatchOffsets(namespace, topicName string, partition *schema_pb.Partition, count int64) *AssignmentResult {
return integration.offsetAssigner.AssignBatchOffsets(namespace, topicName, partition, count)
}
// Reset resets the integration layer state (for testing)
func (integration *SMQOffsetIntegration) Reset() {
integration.mu.Lock()
defer integration.mu.Unlock()
// Note: No in-memory maps to clear (removed to prevent memory leaks)
// Close all subscriptions
for _, subscription := range integration.offsetSubscriber.subscriptions {
subscription.IsActive = false
}
integration.offsetSubscriber.subscriptions = make(map[string]*OffsetSubscription)
// Reset the registries by creating new ones with the same storage
// This ensures that partition managers start fresh
registry := NewPartitionOffsetRegistry(integration.offsetAssigner.registry.storage)
integration.offsetAssigner.registry = registry
integration.offsetSubscriber.offsetRegistry = registry
integration.offsetSeeker.offsetRegistry = registry
}
-378
View File
@@ -1,378 +0,0 @@
package offset
import (
"fmt"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
)
// PartitionOffsetManager manages sequential offset assignment for a single partition
type PartitionOffsetManager struct {
mu sync.RWMutex
namespace string
topicName string
partition *schema_pb.Partition
nextOffset int64
// Checkpointing for recovery
lastCheckpoint int64
lastCheckpointedOffset int64
storage OffsetStorage
// Background checkpointing
stopCheckpoint chan struct{}
}
// OffsetStorage interface for persisting offset state
type OffsetStorage interface {
// SaveCheckpoint persists the current offset state for recovery
// Takes topic information along with partition to determine the correct storage location
SaveCheckpoint(namespace, topicName string, partition *schema_pb.Partition, offset int64) error
// LoadCheckpoint retrieves the last saved offset state
LoadCheckpoint(namespace, topicName string, partition *schema_pb.Partition) (int64, error)
// GetHighestOffset scans storage to find the highest assigned offset
GetHighestOffset(namespace, topicName string, partition *schema_pb.Partition) (int64, error)
}
// NewPartitionOffsetManager creates a new offset manager for a partition
func NewPartitionOffsetManager(namespace, topicName string, partition *schema_pb.Partition, storage OffsetStorage) (*PartitionOffsetManager, error) {
manager := &PartitionOffsetManager{
namespace: namespace,
topicName: topicName,
partition: partition,
storage: storage,
stopCheckpoint: make(chan struct{}),
}
// Recover offset state
if err := manager.recover(); err != nil {
return nil, fmt.Errorf("failed to recover offset state: %w", err)
}
// Start background checkpoint goroutine
go manager.runPeriodicCheckpoint()
return manager, nil
}
// Close stops the background checkpoint goroutine and performs a final checkpoint
func (m *PartitionOffsetManager) Close() error {
close(m.stopCheckpoint)
// Perform final checkpoint
m.mu.RLock()
currentOffset := m.nextOffset - 1 // Last assigned offset
lastCheckpointed := m.lastCheckpointedOffset
m.mu.RUnlock()
if currentOffset >= 0 && currentOffset > lastCheckpointed {
return m.storage.SaveCheckpoint(m.namespace, m.topicName, m.partition, currentOffset)
}
return nil
}
// AssignOffset assigns the next sequential offset
func (m *PartitionOffsetManager) AssignOffset() int64 {
m.mu.Lock()
offset := m.nextOffset
m.nextOffset++
m.mu.Unlock()
return offset
}
// AssignOffsets assigns a batch of sequential offsets
func (m *PartitionOffsetManager) AssignOffsets(count int64) (baseOffset int64, lastOffset int64) {
m.mu.Lock()
baseOffset = m.nextOffset
lastOffset = m.nextOffset + count - 1
m.nextOffset += count
m.mu.Unlock()
return baseOffset, lastOffset
}
// GetNextOffset returns the next offset that will be assigned
func (m *PartitionOffsetManager) GetNextOffset() int64 {
m.mu.RLock()
defer m.mu.RUnlock()
return m.nextOffset
}
// GetHighWaterMark returns the high water mark (next offset)
func (m *PartitionOffsetManager) GetHighWaterMark() int64 {
return m.GetNextOffset()
}
// recover restores offset state from storage
func (m *PartitionOffsetManager) recover() error {
var checkpointOffset int64 = -1
var highestOffset int64 = -1
// Try to load checkpoint
if offset, err := m.storage.LoadCheckpoint(m.namespace, m.topicName, m.partition); err == nil && offset >= 0 {
checkpointOffset = offset
}
// Try to scan storage for highest offset
if offset, err := m.storage.GetHighestOffset(m.namespace, m.topicName, m.partition); err == nil && offset >= 0 {
highestOffset = offset
}
// Use the higher of checkpoint or storage scan
if checkpointOffset >= 0 && highestOffset >= 0 {
if highestOffset > checkpointOffset {
m.nextOffset = highestOffset + 1
m.lastCheckpoint = highestOffset
m.lastCheckpointedOffset = highestOffset
} else {
m.nextOffset = checkpointOffset + 1
m.lastCheckpoint = checkpointOffset
m.lastCheckpointedOffset = checkpointOffset
}
} else if checkpointOffset >= 0 {
m.nextOffset = checkpointOffset + 1
m.lastCheckpoint = checkpointOffset
m.lastCheckpointedOffset = checkpointOffset
} else if highestOffset >= 0 {
m.nextOffset = highestOffset + 1
m.lastCheckpoint = highestOffset
m.lastCheckpointedOffset = highestOffset
} else {
// No data exists, start from 0
m.nextOffset = 0
m.lastCheckpoint = -1
m.lastCheckpointedOffset = -1
}
return nil
}
// runPeriodicCheckpoint runs in the background and checkpoints every 2 seconds if the offset changed
func (m *PartitionOffsetManager) runPeriodicCheckpoint() {
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
m.performCheckpointIfChanged()
case <-m.stopCheckpoint:
return
}
}
}
// performCheckpointIfChanged saves checkpoint only if offset has changed since last checkpoint
func (m *PartitionOffsetManager) performCheckpointIfChanged() {
m.mu.RLock()
currentOffset := m.nextOffset - 1 // Last assigned offset
lastCheckpointed := m.lastCheckpointedOffset
m.mu.RUnlock()
// Skip if no messages have been assigned, or no change since last checkpoint
if currentOffset < 0 || currentOffset == lastCheckpointed {
return
}
// Perform checkpoint
if err := m.storage.SaveCheckpoint(m.namespace, m.topicName, m.partition, currentOffset); err != nil {
// Log error but don't fail - checkpointing is for optimization
fmt.Printf("Failed to checkpoint offset %d for %s/%s: %v\n", currentOffset, m.namespace, m.topicName, err)
return
}
// Update last checkpointed offset
m.mu.Lock()
m.lastCheckpointedOffset = currentOffset
m.lastCheckpoint = currentOffset
m.mu.Unlock()
}
// PartitionOffsetRegistry manages offset managers for multiple partitions
type PartitionOffsetRegistry struct {
mu sync.RWMutex
managers map[string]*PartitionOffsetManager
storage OffsetStorage
}
// NewPartitionOffsetRegistry creates a new registry
func NewPartitionOffsetRegistry(storage OffsetStorage) *PartitionOffsetRegistry {
return &PartitionOffsetRegistry{
managers: make(map[string]*PartitionOffsetManager),
storage: storage,
}
}
// GetManager returns the offset manager for a partition, creating it if needed
func (r *PartitionOffsetRegistry) GetManager(namespace, topicName string, partition *schema_pb.Partition) (*PartitionOffsetManager, error) {
// CRITICAL FIX: Use TopicPartitionKey to ensure each topic has its own offset manager
key := TopicPartitionKey(namespace, topicName, partition)
r.mu.RLock()
manager, exists := r.managers[key]
r.mu.RUnlock()
if exists {
return manager, nil
}
// Create new manager
r.mu.Lock()
defer r.mu.Unlock()
// Double-check after acquiring write lock
if manager, exists := r.managers[key]; exists {
return manager, nil
}
manager, err := NewPartitionOffsetManager(namespace, topicName, partition, r.storage)
if err != nil {
return nil, err
}
r.managers[key] = manager
return manager, nil
}
// AssignOffset assigns an offset for the given partition
func (r *PartitionOffsetRegistry) AssignOffset(namespace, topicName string, partition *schema_pb.Partition) (int64, error) {
manager, err := r.GetManager(namespace, topicName, partition)
if err != nil {
return 0, err
}
assignedOffset := manager.AssignOffset()
return assignedOffset, nil
}
// AssignOffsets assigns a batch of offsets for the given partition
func (r *PartitionOffsetRegistry) AssignOffsets(namespace, topicName string, partition *schema_pb.Partition, count int64) (baseOffset, lastOffset int64, err error) {
manager, err := r.GetManager(namespace, topicName, partition)
if err != nil {
return 0, 0, err
}
baseOffset, lastOffset = manager.AssignOffsets(count)
return baseOffset, lastOffset, nil
}
// GetHighWaterMark returns the high water mark for a partition
func (r *PartitionOffsetRegistry) GetHighWaterMark(namespace, topicName string, partition *schema_pb.Partition) (int64, error) {
manager, err := r.GetManager(namespace, topicName, partition)
if err != nil {
return 0, err
}
return manager.GetHighWaterMark(), nil
}
// Close stops all partition managers and performs final checkpoints
func (r *PartitionOffsetRegistry) Close() error {
r.mu.Lock()
defer r.mu.Unlock()
var firstErr error
for _, manager := range r.managers {
if err := manager.Close(); err != nil && firstErr == nil {
firstErr = err
}
}
return firstErr
}
// TopicPartitionKey generates a unique key for a topic-partition combination
// This is the canonical key format used across the offset management system
func TopicPartitionKey(namespace, topicName string, partition *schema_pb.Partition) string {
return fmt.Sprintf("%s/%s/ring:%d:range:%d-%d",
namespace, topicName,
partition.RingSize, partition.RangeStart, partition.RangeStop)
}
// PartitionKey generates a unique key for a partition (without topic context)
// Note: UnixTimeNs is intentionally excluded from the key because it represents
// partition creation time, not partition identity. Using it would cause offset
// tracking to reset whenever a partition is recreated or looked up again.
// DEPRECATED: Use TopicPartitionKey for production code to avoid key collisions
func PartitionKey(partition *schema_pb.Partition) string {
return fmt.Sprintf("ring:%d:range:%d-%d",
partition.RingSize, partition.RangeStart, partition.RangeStop)
}
// partitionKey is the internal lowercase version for backward compatibility within this package
func partitionKey(partition *schema_pb.Partition) string {
return PartitionKey(partition)
}
// OffsetAssignment represents an assigned offset with metadata
type OffsetAssignment struct {
Offset int64
Timestamp int64
Partition *schema_pb.Partition
}
// BatchOffsetAssignment represents a batch of assigned offsets
type BatchOffsetAssignment struct {
BaseOffset int64
LastOffset int64
Count int64
Timestamp int64
Partition *schema_pb.Partition
}
// AssignmentResult contains the result of offset assignment
type AssignmentResult struct {
Assignment *OffsetAssignment
Batch *BatchOffsetAssignment
Error error
}
// OffsetAssigner provides high-level offset assignment operations
type OffsetAssigner struct {
registry *PartitionOffsetRegistry
}
// AssignSingleOffset assigns a single offset with timestamp
func (a *OffsetAssigner) AssignSingleOffset(namespace, topicName string, partition *schema_pb.Partition) *AssignmentResult {
offset, err := a.registry.AssignOffset(namespace, topicName, partition)
if err != nil {
return &AssignmentResult{Error: err}
}
return &AssignmentResult{
Assignment: &OffsetAssignment{
Offset: offset,
Timestamp: time.Now().UnixNano(),
Partition: partition,
},
}
}
// AssignBatchOffsets assigns a batch of offsets with timestamp
func (a *OffsetAssigner) AssignBatchOffsets(namespace, topicName string, partition *schema_pb.Partition, count int64) *AssignmentResult {
baseOffset, lastOffset, err := a.registry.AssignOffsets(namespace, topicName, partition, count)
if err != nil {
return &AssignmentResult{Error: err}
}
return &AssignmentResult{
Batch: &BatchOffsetAssignment{
BaseOffset: baseOffset,
LastOffset: lastOffset,
Count: count,
Timestamp: time.Now().UnixNano(),
Partition: partition,
},
}
}
// GetHighWaterMark returns the high water mark for a partition
func (a *OffsetAssigner) GetHighWaterMark(namespace, topicName string, partition *schema_pb.Partition) (int64, error) {
return a.registry.GetHighWaterMark(namespace, topicName, partition)
}
-228
View File
@@ -1,228 +0,0 @@
package offset
import (
"fmt"
"sync"
"time"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
)
// recordEntry holds a record with timestamp for TTL cleanup
type recordEntry struct {
exists bool
timestamp time.Time
}
// InMemoryOffsetStorage provides an in-memory implementation of OffsetStorage for testing ONLY
// WARNING: This should NEVER be used in production - use FilerOffsetStorage or SQLOffsetStorage instead
type InMemoryOffsetStorage struct {
mu sync.RWMutex
checkpoints map[string]int64 // partition key -> offset
records map[string]map[int64]*recordEntry // partition key -> offset -> entry with timestamp
// Memory leak protection
maxRecordsPerPartition int // Maximum records to keep per partition
recordTTL time.Duration // TTL for record entries
lastCleanup time.Time // Last cleanup time
cleanupInterval time.Duration // How often to run cleanup
}
// NewInMemoryOffsetStorage creates a new in-memory storage with memory leak protection
// FOR TESTING ONLY - do not use in production
func NewInMemoryOffsetStorage() *InMemoryOffsetStorage {
return &InMemoryOffsetStorage{
checkpoints: make(map[string]int64),
records: make(map[string]map[int64]*recordEntry),
maxRecordsPerPartition: 10000, // Limit to 10K records per partition
recordTTL: 1 * time.Hour, // Records expire after 1 hour
cleanupInterval: 5 * time.Minute, // Cleanup every 5 minutes
lastCleanup: time.Now(),
}
}
// SaveCheckpoint saves the checkpoint for a partition
func (s *InMemoryOffsetStorage) SaveCheckpoint(namespace, topicName string, partition *schema_pb.Partition, offset int64) error {
s.mu.Lock()
defer s.mu.Unlock()
// Use TopicPartitionKey for consistency with other storage implementations
key := TopicPartitionKey(namespace, topicName, partition)
s.checkpoints[key] = offset
return nil
}
// LoadCheckpoint loads the checkpoint for a partition
func (s *InMemoryOffsetStorage) LoadCheckpoint(namespace, topicName string, partition *schema_pb.Partition) (int64, error) {
s.mu.RLock()
defer s.mu.RUnlock()
// Use TopicPartitionKey to match SaveCheckpoint
key := TopicPartitionKey(namespace, topicName, partition)
offset, exists := s.checkpoints[key]
if !exists {
return -1, fmt.Errorf("no checkpoint found")
}
return offset, nil
}
// GetHighestOffset finds the highest offset in storage for a partition
func (s *InMemoryOffsetStorage) GetHighestOffset(namespace, topicName string, partition *schema_pb.Partition) (int64, error) {
s.mu.RLock()
defer s.mu.RUnlock()
// Use TopicPartitionKey to match SaveCheckpoint
key := TopicPartitionKey(namespace, topicName, partition)
offsets, exists := s.records[key]
if !exists || len(offsets) == 0 {
return -1, fmt.Errorf("no records found")
}
var highest int64 = -1
for offset, entry := range offsets {
if entry.exists && offset > highest {
highest = offset
}
}
return highest, nil
}
// AddRecord simulates storing a record with an offset (for testing)
func (s *InMemoryOffsetStorage) AddRecord(namespace, topicName string, partition *schema_pb.Partition, offset int64) {
s.mu.Lock()
defer s.mu.Unlock()
// Use TopicPartitionKey to match GetHighestOffset
key := TopicPartitionKey(namespace, topicName, partition)
if s.records[key] == nil {
s.records[key] = make(map[int64]*recordEntry)
}
// Add record with current timestamp
s.records[key][offset] = &recordEntry{
exists: true,
timestamp: time.Now(),
}
// Trigger cleanup if needed (memory leak protection)
s.cleanupIfNeeded()
}
// GetRecordCount returns the number of records for a partition (for testing)
func (s *InMemoryOffsetStorage) GetRecordCount(namespace, topicName string, partition *schema_pb.Partition) int {
s.mu.RLock()
defer s.mu.RUnlock()
// Use TopicPartitionKey to match GetHighestOffset
key := TopicPartitionKey(namespace, topicName, partition)
if offsets, exists := s.records[key]; exists {
count := 0
for _, entry := range offsets {
if entry.exists {
count++
}
}
return count
}
return 0
}
// Clear removes all data (for testing)
func (s *InMemoryOffsetStorage) Clear() {
s.mu.Lock()
defer s.mu.Unlock()
s.checkpoints = make(map[string]int64)
s.records = make(map[string]map[int64]*recordEntry)
s.lastCleanup = time.Now()
}
// Reset removes all data (implements resettable interface for shutdown)
func (s *InMemoryOffsetStorage) Reset() error {
s.Clear()
return nil
}
// cleanupIfNeeded performs memory leak protection cleanup
// This method assumes the caller already holds the write lock
func (s *InMemoryOffsetStorage) cleanupIfNeeded() {
now := time.Now()
// Only cleanup if enough time has passed
if now.Sub(s.lastCleanup) < s.cleanupInterval {
return
}
s.lastCleanup = now
cutoff := now.Add(-s.recordTTL)
// Clean up expired records and enforce size limits
for partitionKey, offsets := range s.records {
// Remove expired records
for offset, entry := range offsets {
if entry.timestamp.Before(cutoff) {
delete(offsets, offset)
}
}
// Enforce size limit per partition
if len(offsets) > s.maxRecordsPerPartition {
// Keep only the most recent records
type offsetTime struct {
offset int64
time time.Time
}
var entries []offsetTime
for offset, entry := range offsets {
entries = append(entries, offsetTime{offset: offset, time: entry.timestamp})
}
// Sort by timestamp (newest first)
for i := 0; i < len(entries)-1; i++ {
for j := i + 1; j < len(entries); j++ {
if entries[i].time.Before(entries[j].time) {
entries[i], entries[j] = entries[j], entries[i]
}
}
}
// Keep only the newest maxRecordsPerPartition entries
newOffsets := make(map[int64]*recordEntry)
for i := 0; i < s.maxRecordsPerPartition && i < len(entries); i++ {
offset := entries[i].offset
newOffsets[offset] = offsets[offset]
}
s.records[partitionKey] = newOffsets
}
// Remove empty partition maps
if len(offsets) == 0 {
delete(s.records, partitionKey)
}
}
}
// GetMemoryStats returns memory usage statistics for monitoring
func (s *InMemoryOffsetStorage) GetMemoryStats() map[string]interface{} {
s.mu.RLock()
defer s.mu.RUnlock()
totalRecords := 0
partitionCount := len(s.records)
for _, offsets := range s.records {
totalRecords += len(offsets)
}
return map[string]interface{}{
"total_partitions": partitionCount,
"total_records": totalRecords,
"max_records_per_partition": s.maxRecordsPerPartition,
"record_ttl_hours": s.recordTTL.Hours(),
"last_cleanup": s.lastCleanup,
}
}
-5
View File
@@ -1,5 +0,0 @@
package offset
// Note: OffsetStorage interface is defined in manager.go
// Production implementations: FilerOffsetStorage (filer_storage.go), SQLOffsetStorage (sql_storage.go)
// Test implementation: InMemoryOffsetStorage (storage_test.go)
-355
View File
@@ -1,355 +0,0 @@
package offset
import (
"fmt"
"sync"
"github.com/seaweedfs/seaweedfs/weed/pb/schema_pb"
)
// OffsetSubscriber handles offset-based subscription logic
type OffsetSubscriber struct {
mu sync.RWMutex
offsetRegistry *PartitionOffsetRegistry
subscriptions map[string]*OffsetSubscription
}
// OffsetSubscription represents an active offset-based subscription
type OffsetSubscription struct {
ID string
Namespace string
TopicName string
Partition *schema_pb.Partition
StartOffset int64
CurrentOffset int64
OffsetType schema_pb.OffsetType
IsActive bool
offsetRegistry *PartitionOffsetRegistry
}
// NewOffsetSubscriber creates a new offset-based subscriber
func NewOffsetSubscriber(offsetRegistry *PartitionOffsetRegistry) *OffsetSubscriber {
return &OffsetSubscriber{
offsetRegistry: offsetRegistry,
subscriptions: make(map[string]*OffsetSubscription),
}
}
// CreateSubscription creates a new offset-based subscription
func (s *OffsetSubscriber) CreateSubscription(
subscriptionID string,
namespace, topicName string,
partition *schema_pb.Partition,
offsetType schema_pb.OffsetType,
startOffset int64,
) (*OffsetSubscription, error) {
s.mu.Lock()
defer s.mu.Unlock()
// Check if subscription already exists
if _, exists := s.subscriptions[subscriptionID]; exists {
return nil, fmt.Errorf("subscription %s already exists", subscriptionID)
}
// Resolve the actual start offset based on type
actualStartOffset, err := s.resolveStartOffset(namespace, topicName, partition, offsetType, startOffset)
if err != nil {
return nil, fmt.Errorf("failed to resolve start offset: %w", err)
}
subscription := &OffsetSubscription{
ID: subscriptionID,
Namespace: namespace,
TopicName: topicName,
Partition: partition,
StartOffset: actualStartOffset,
CurrentOffset: actualStartOffset,
OffsetType: offsetType,
IsActive: true,
offsetRegistry: s.offsetRegistry,
}
s.subscriptions[subscriptionID] = subscription
return subscription, nil
}
// GetSubscription retrieves an existing subscription
func (s *OffsetSubscriber) GetSubscription(subscriptionID string) (*OffsetSubscription, error) {
s.mu.RLock()
defer s.mu.RUnlock()
subscription, exists := s.subscriptions[subscriptionID]
if !exists {
return nil, fmt.Errorf("subscription %s not found", subscriptionID)
}
return subscription, nil
}
// CloseSubscription closes and removes a subscription
func (s *OffsetSubscriber) CloseSubscription(subscriptionID string) error {
s.mu.Lock()
defer s.mu.Unlock()
subscription, exists := s.subscriptions[subscriptionID]
if !exists {
return fmt.Errorf("subscription %s not found", subscriptionID)
}
subscription.IsActive = false
delete(s.subscriptions, subscriptionID)
return nil
}
// resolveStartOffset resolves the actual start offset based on OffsetType
func (s *OffsetSubscriber) resolveStartOffset(
namespace, topicName string,
partition *schema_pb.Partition,
offsetType schema_pb.OffsetType,
requestedOffset int64,
) (int64, error) {
switch offsetType {
case schema_pb.OffsetType_EXACT_OFFSET:
// Validate that the requested offset exists
return s.validateAndGetOffset(namespace, topicName, partition, requestedOffset)
case schema_pb.OffsetType_RESET_TO_OFFSET:
// Use the requested offset, even if it doesn't exist yet
return requestedOffset, nil
case schema_pb.OffsetType_RESET_TO_EARLIEST:
// Start from offset 0
return 0, nil
case schema_pb.OffsetType_RESET_TO_LATEST:
// Start from the current high water mark
hwm, err := s.offsetRegistry.GetHighWaterMark(namespace, topicName, partition)
if err != nil {
return 0, err
}
return hwm, nil
case schema_pb.OffsetType_RESUME_OR_EARLIEST:
// Try to resume from a saved position, fallback to earliest
// For now, just use earliest (consumer group position tracking will be added later)
return 0, nil
case schema_pb.OffsetType_RESUME_OR_LATEST:
// Try to resume from a saved position, fallback to latest
// For now, just use latest
hwm, err := s.offsetRegistry.GetHighWaterMark(namespace, topicName, partition)
if err != nil {
return 0, err
}
return hwm, nil
default:
return 0, fmt.Errorf("unsupported offset type: %v", offsetType)
}
}
// validateAndGetOffset validates that an offset exists and returns it
func (s *OffsetSubscriber) validateAndGetOffset(namespace, topicName string, partition *schema_pb.Partition, offset int64) (int64, error) {
if offset < 0 {
return 0, fmt.Errorf("offset cannot be negative: %d", offset)
}
// Get the current high water mark
hwm, err := s.offsetRegistry.GetHighWaterMark(namespace, topicName, partition)
if err != nil {
return 0, fmt.Errorf("failed to get high water mark: %w", err)
}
// Check if offset is within valid range
if offset >= hwm {
return 0, fmt.Errorf("offset %d is beyond high water mark %d", offset, hwm)
}
return offset, nil
}
// SeekToOffset seeks a subscription to a specific offset
func (sub *OffsetSubscription) SeekToOffset(offset int64) error {
if !sub.IsActive {
return fmt.Errorf("subscription is not active")
}
// Validate the offset
if offset < 0 {
return fmt.Errorf("offset cannot be negative: %d", offset)
}
hwm, err := sub.offsetRegistry.GetHighWaterMark(sub.Namespace, sub.TopicName, sub.Partition)
if err != nil {
return fmt.Errorf("failed to get high water mark: %w", err)
}
if offset > hwm {
return fmt.Errorf("offset %d is beyond high water mark %d", offset, hwm)
}
sub.CurrentOffset = offset
return nil
}
// GetNextOffset returns the next offset to read
func (sub *OffsetSubscription) GetNextOffset() int64 {
return sub.CurrentOffset
}
// AdvanceOffset advances the subscription to the next offset
func (sub *OffsetSubscription) AdvanceOffset() {
sub.CurrentOffset++
}
// GetLag returns the lag between current position and high water mark
func (sub *OffsetSubscription) GetLag() (int64, error) {
if !sub.IsActive {
return 0, fmt.Errorf("subscription is not active")
}
hwm, err := sub.offsetRegistry.GetHighWaterMark(sub.Namespace, sub.TopicName, sub.Partition)
if err != nil {
return 0, fmt.Errorf("failed to get high water mark: %w", err)
}
lag := hwm - sub.CurrentOffset
if lag < 0 {
lag = 0
}
return lag, nil
}
// IsAtEnd checks if the subscription has reached the end of available data
func (sub *OffsetSubscription) IsAtEnd() (bool, error) {
if !sub.IsActive {
return true, fmt.Errorf("subscription is not active")
}
hwm, err := sub.offsetRegistry.GetHighWaterMark(sub.Namespace, sub.TopicName, sub.Partition)
if err != nil {
return false, fmt.Errorf("failed to get high water mark: %w", err)
}
return sub.CurrentOffset >= hwm, nil
}
// OffsetRange represents a range of offsets
type OffsetRange struct {
StartOffset int64
EndOffset int64
Count int64
}
// GetOffsetRange returns a range of offsets for batch reading
func (sub *OffsetSubscription) GetOffsetRange(maxCount int64) (*OffsetRange, error) {
if !sub.IsActive {
return nil, fmt.Errorf("subscription is not active")
}
hwm, err := sub.offsetRegistry.GetHighWaterMark(sub.Namespace, sub.TopicName, sub.Partition)
if err != nil {
return nil, fmt.Errorf("failed to get high water mark: %w", err)
}
startOffset := sub.CurrentOffset
endOffset := startOffset + maxCount - 1
// Don't go beyond high water mark
if endOffset >= hwm {
endOffset = hwm - 1
}
// If start is already at or beyond HWM, return empty range
if startOffset >= hwm {
return &OffsetRange{
StartOffset: startOffset,
EndOffset: startOffset - 1, // Empty range
Count: 0,
}, nil
}
count := endOffset - startOffset + 1
return &OffsetRange{
StartOffset: startOffset,
EndOffset: endOffset,
Count: count,
}, nil
}
// AdvanceOffsetBy advances the subscription by a specific number of offsets
func (sub *OffsetSubscription) AdvanceOffsetBy(count int64) {
sub.CurrentOffset += count
}
// OffsetSeeker provides utilities for offset-based seeking
type OffsetSeeker struct {
offsetRegistry *PartitionOffsetRegistry
}
// NewOffsetSeeker creates a new offset seeker
func NewOffsetSeeker(offsetRegistry *PartitionOffsetRegistry) *OffsetSeeker {
return &OffsetSeeker{
offsetRegistry: offsetRegistry,
}
}
// SeekToTimestamp finds the offset closest to a given timestamp
// This bridges offset-based and timestamp-based seeking
func (seeker *OffsetSeeker) SeekToTimestamp(partition *schema_pb.Partition, timestamp int64) (int64, error) {
// TODO: This requires integration with the storage layer to map timestamps to offsets
// For now, return an error indicating this feature needs implementation
return 0, fmt.Errorf("timestamp-to-offset mapping not implemented yet")
}
// ValidateOffsetRange validates that an offset range is valid
func (seeker *OffsetSeeker) ValidateOffsetRange(namespace, topicName string, partition *schema_pb.Partition, startOffset, endOffset int64) error {
if startOffset < 0 {
return fmt.Errorf("start offset cannot be negative: %d", startOffset)
}
if endOffset < startOffset {
return fmt.Errorf("end offset %d cannot be less than start offset %d", endOffset, startOffset)
}
hwm, err := seeker.offsetRegistry.GetHighWaterMark(namespace, topicName, partition)
if err != nil {
return fmt.Errorf("failed to get high water mark: %w", err)
}
if startOffset >= hwm {
return fmt.Errorf("start offset %d is beyond high water mark %d", startOffset, hwm)
}
if endOffset >= hwm {
return fmt.Errorf("end offset %d is beyond high water mark %d", endOffset, hwm)
}
return nil
}
// GetAvailableOffsetRange returns the range of available offsets for a partition
func (seeker *OffsetSeeker) GetAvailableOffsetRange(namespace, topicName string, partition *schema_pb.Partition) (*OffsetRange, error) {
hwm, err := seeker.offsetRegistry.GetHighWaterMark(namespace, topicName, partition)
if err != nil {
return nil, fmt.Errorf("failed to get high water mark: %w", err)
}
if hwm == 0 {
// No data available
return &OffsetRange{
StartOffset: 0,
EndOffset: -1,
Count: 0,
}, nil
}
return &OffsetRange{
StartOffset: 0,
EndOffset: hwm - 1,
Count: hwm,
}, nil
}
+24 -1
View File
@@ -1,6 +1,12 @@
package mq
import "encoding/binary"
import (
"context"
"encoding/binary"
"math"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
)
// OffsetRange accumulates the offset ranges recorded on a partition's files.
type OffsetRange struct {
@@ -32,3 +38,20 @@ func (r *OffsetRange) Bounds() (earliestOffset, highWaterMark int64) {
}
return
}
// ReadOffsetRange scans every file of a partition directory, not just the
// filer's default listing page, for the offset ranges they record.
func ReadOffsetRange(ctx context.Context, client filer_pb.SeaweedFilerClient, partitionDir string) (earliestOffset, highWaterMark int64, err error) {
var r OffsetRange
err = filer_pb.SeaweedList(ctx, client, partitionDir, "", func(entry *filer_pb.Entry, isLast bool) error {
if !entry.IsDirectory {
r.Add(entry.Extended)
}
return nil
}, "", false, math.MaxInt32)
if err != nil {
return 0, 0, err
}
earliestOffset, highWaterMark = r.Bounds()
return
}
+63
View File
@@ -1,8 +1,15 @@
package mq
import (
"context"
"encoding/binary"
"fmt"
"net"
"testing"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
func rangeAttrs(min, max int64) map[string][]byte {
@@ -34,3 +41,59 @@ func TestOffsetRangeBounds(t *testing.T) {
}
}
}
// listingFiler lists a directory the way the filer does: an unset limit means its
// default page of 1000.
type listingFiler struct {
filer_pb.UnimplementedSeaweedFilerServer
entries []*filer_pb.Entry
}
func (f *listingFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error {
limit := int(req.Limit)
if limit == 0 {
limit = 1000
}
sent := 0
for _, e := range f.entries {
if e.Name < req.StartFromFileName || (e.Name == req.StartFromFileName && !req.InclusiveStartFrom) {
continue
}
if sent == limit {
break
}
if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: e}); err != nil {
return err
}
sent++
}
return nil
}
func TestReadOffsetRangeScansPastTheDefaultPage(t *testing.T) {
filer := &listingFiler{}
for i := int64(0); i < 2500; i++ {
filer.entries = append(filer.entries, &filer_pb.Entry{Name: fmt.Sprintf("2026-11-30-00-00-%06d", i), Extended: rangeAttrs(i*10, i*10+9)})
}
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
server := grpc.NewServer()
filer_pb.RegisterSeaweedFilerServer(server, filer)
go server.Serve(listener)
defer server.Stop()
conn, err := grpc.NewClient(listener.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
earliest, hwm, err := ReadOffsetRange(context.Background(), filer_pb.NewSeaweedFilerClient(conn), "/topics/test/t/v1/0000-2520")
if err != nil {
t.Fatal(err)
}
if earliest != 0 || hwm != 25000 {
t.Fatalf("ReadOffsetRange = %d, %d; want 0, 25000", earliest, hwm)
}
}
+66 -18
View File
@@ -23,7 +23,12 @@ type LocalTopicManager struct {
stopped bool
// partitions shut down whose last flush is still pending
retiringMu sync.Mutex
retiring map[*LocalPartition]struct{}
retiring map[*LocalPartition]*retirement
}
type retirement struct {
topic Topic
flushed chan struct{}
}
// NewLocalTopicManager creates a new LocalTopicManager
@@ -31,7 +36,7 @@ func NewLocalTopicManager() *LocalTopicManager {
return &LocalTopicManager{
topics: cmap.New[*LocalTopic](),
cleanupDone: make(chan struct{}),
retiring: make(map[*LocalPartition]struct{}),
retiring: make(map[*LocalPartition]*retirement),
}
}
@@ -84,7 +89,7 @@ func (manager *LocalTopicManager) cleanupIdlePartitions(idleTimeout time.Duratio
partition.Publishers.Size(),
partition.Subscribers.Size())
manager.retire(partition)
manager.retire(localTopic.Topic, partition)
// Remove from slice
localTopic.Partitions = append(localTopic.Partitions[:i], localTopic.Partitions[i+1:]...)
@@ -131,16 +136,25 @@ func (manager *LocalTopicManager) WaitForCleanupShutdown() {
}
// retire shuts a partition down and makes Shutdown wait for its last flush.
func (manager *LocalTopicManager) retire(p *LocalPartition) {
func (manager *LocalTopicManager) retire(t Topic, p *LocalPartition) {
manager.markRetiring(t, p)
p.Shutdown()
}
func (manager *LocalTopicManager) markRetiring(t Topic, p *LocalPartition) {
manager.retiringMu.Lock()
manager.retiring[p] = struct{}{}
manager.retiringMu.Unlock()
defer manager.retiringMu.Unlock()
if _, ok := manager.retiring[p]; ok {
return
}
r := &retirement{topic: t, flushed: make(chan struct{})}
manager.retiring[p] = r
go func() {
p.LogBuffer.WaitForShutdown()
manager.retiringMu.Lock()
delete(manager.retiring, p)
manager.retiringMu.Unlock()
close(r.flushed)
}()
}
@@ -151,18 +165,21 @@ func (manager *LocalTopicManager) Shutdown() {
manager.stopped = true
manager.stopMu.Unlock()
var partitions []*LocalPartition
var topics []*LocalTopic
manager.topics.IterCb(func(_ string, localTopic *LocalTopic) {
localTopic.partitionLock.RLock()
partitions = append(partitions, localTopic.Partitions...)
localTopic.partitionLock.RUnlock()
topics = append(topics, localTopic)
})
for _, p := range partitions {
manager.retire(p)
for _, localTopic := range topics {
localTopic.partitionLock.RLock()
held := append([]*LocalPartition(nil), localTopic.Partitions...)
localTopic.partitionLock.RUnlock()
for _, p := range held {
manager.retire(localTopic.Topic, p)
}
}
// Anything removed before the snapshot was retired before it, so it is here too.
manager.retiringMu.Lock()
partitions = partitions[:0]
var partitions []*LocalPartition
for p := range manager.retiring {
partitions = append(partitions, p)
}
@@ -212,9 +229,9 @@ func (manager *LocalTopicManager) RemoveTopic(topic Topic) {
manager.topics.Remove(topic.String())
}
// RemoveLocalPartition retires p if it is still registered, so a copy that has
// replaced it stays. It reports false once Shutdown has started, which then
// retires p from its own snapshot.
// RemoveLocalPartition retires p if it is still listed, leaving a copy that has
// replaced it. It reports false once Shutdown has started, which then retires p
// from its own snapshot.
func (manager *LocalTopicManager) RemoveLocalPartition(topic Topic, p *LocalPartition) (removed bool) {
manager.stopMu.RLock()
defer manager.stopMu.RUnlock()
@@ -222,13 +239,44 @@ func (manager *LocalTopicManager) RemoveLocalPartition(topic Topic, p *LocalPart
return false
}
localTopic, ok := manager.topics.Get(topic.String())
if !ok || !localTopic.removePartition(p) {
if !ok || !localTopic.removePartition(p, func() { manager.markRetiring(topic, p) }) {
return false
}
manager.retire(p)
manager.retire(topic, p)
return true
}
// RetiringPartition is a retired partition of this range whose last flush is
// still pending; a replacement must not read the stored offsets before it lands.
func (manager *LocalTopicManager) RetiringPartition(topic Topic, partition Partition) *LocalPartition {
p, _ := manager.findRetiring(topic, partition)
return p
}
func (manager *LocalTopicManager) findRetiring(topic Topic, partition Partition) (*LocalPartition, *retirement) {
manager.retiringMu.Lock()
defer manager.retiringMu.Unlock()
for p, r := range manager.retiring {
if r.topic.String() == topic.String() && p.Partition.LogicalEquals(partition) {
return p, r
}
}
return nil, nil
}
// WaitRetired returns once no retired partition of this range has a flush
// pending, or with ctx's error once ctx is done.
func (manager *LocalTopicManager) WaitRetired(ctx context.Context, topic Topic, partition Partition) error {
for _, r := manager.findRetiring(topic, partition); r != nil; _, r = manager.findRetiring(topic, partition) {
select {
case <-r.flushed:
case <-ctx.Done():
return ctx.Err()
}
}
return nil
}
func (manager *LocalTopicManager) ClosePublishers(topic Topic, unixTsNs int64) (removed bool) {
localTopic, ok := manager.topics.Get(topic.String())
if !ok {
+63 -2
View File
@@ -1,6 +1,11 @@
package topic
import (
"context"
"errors"
"runtime"
"sync"
"sync/atomic"
"testing"
"time"
@@ -187,8 +192,60 @@ func TestPartitionShutdownTwiceWithSubscriber(t *testing.T) {
p.Shutdown()
}
// A client of a replaced copy removing that copy on its way out leaves the
// replacement registered.
// A replacement partition seeds its offsets from disk, so it must wait for the
// retired one's last flush to land.
func TestWaitRetiredWaitsForTheLastFlush(t *testing.T) {
manager := NewLocalTopicManager()
release := make(chan struct{})
var releaseOnce sync.Once
t.Cleanup(func() { releaseOnce.Do(func() { close(release) }) })
var flushed atomic.Bool
flushFn := func(_ *log_buffer.LogBuffer, _, _ time.Time, _ []byte, _, _ int64) {
<-release
flushed.Store(true)
}
tp := NewTopic("test", "moved")
partition := Partition{RingSize: 2520, RangeStart: 0, RangeStop: 2520}
p := NewLocalPartition(partition, 3600, flushFn, nil)
manager.AddLocalPartition(tp, p)
if err := p.LogBuffer.AddDataToBuffer([]byte("k"), []byte("v"), time.Now().UnixNano()); err != nil {
t.Fatal(err)
}
manager.RemoveLocalPartition(tp, p)
if manager.RetiringPartition(tp, partition) == nil {
t.Fatal("a just retired partition should be pending")
}
cancelled, cancel := context.WithCancel(context.Background())
cancel()
if err := manager.WaitRetired(cancelled, tp, partition); !errors.Is(err, context.Canceled) {
t.Fatalf("WaitRetired with a cancelled context returned %v", err)
}
if manager.RetiringPartition(tp, partition) == nil {
t.Fatal("a cancelled wait dropped the pending retirement")
}
before := runtime.NumGoroutine()
for i := 0; i < 100; i++ {
manager.WaitRetired(cancelled, tp, partition)
}
if left := runtime.NumGoroutine() - before; left > 10 {
t.Fatalf("cancelled waits left %d goroutines behind", left)
}
releaseOnce.Do(func() { close(release) })
if err := manager.WaitRetired(context.Background(), tp, partition); err != nil {
t.Fatal(err)
}
if !flushed.Load() {
t.Fatal("WaitRetired returned before the last flush")
}
if manager.RetiringPartition(tp, partition) != nil {
t.Fatal("still pending after WaitRetired")
}
}
// A client of a replaced copy removing it on its way out leaves the replacement
// listed.
func TestRemovingAReplacedPartitionKeepsTheReplacement(t *testing.T) {
manager := NewLocalTopicManager()
tp := NewTopic("test", "replaced")
@@ -198,6 +255,7 @@ func TestRemovingAReplacedPartitionKeepsTheReplacement(t *testing.T) {
if !manager.RemoveLocalPartition(tp, old) {
t.Fatal("partition not removed")
}
manager.WaitRetired(context.Background(), tp, partition)
replacement := NewLocalPartition(partition, 3600, nil, nil)
defer replacement.Shutdown()
manager.AddLocalPartition(tp, replacement)
@@ -208,4 +266,7 @@ func TestRemovingAReplacedPartitionKeepsTheReplacement(t *testing.T) {
if manager.GetLocalPartition(tp, partition) != replacement {
t.Error("the replaced copy's removal took its replacement")
}
if manager.RetiringPartition(tp, partition) != nil {
t.Error("the replacement is pending retirement")
}
}
+9 -31
View File
@@ -10,20 +10,9 @@ import (
"github.com/seaweedfs/seaweedfs/weed/util"
)
// OffsetAssignmentFunc is a function type for assigning offsets to messages
type OffsetAssignmentFunc func() (int64, error)
// PublishWithOffset publishes a message with offset assignment
// This method is used by the Kafka gateway integration for sequential offset assignment
func (p *LocalPartition) PublishWithOffset(message *mq_pb.DataMessage, assignOffsetFn OffsetAssignmentFunc) (int64, error) {
// Assign offset for this message
offset, err := assignOffsetFn()
if err != nil {
return 0, fmt.Errorf("failed to assign offset: %w", err)
}
// Add message to buffer with offset
err = p.addToBufferWithOffset(message, offset)
// PublishWithOffset appends the message and returns the offset the buffer gave it.
func (p *LocalPartition) PublishWithOffset(message *mq_pb.DataMessage) (int64, error) {
offset, err := p.addToBuffer(message)
if err != nil {
return 0, fmt.Errorf("failed to add message to buffer: %w", err)
}
@@ -47,29 +36,24 @@ func (p *LocalPartition) PublishWithOffset(message *mq_pb.DataMessage, assignOff
return offset, nil
}
// addToBufferWithOffset adds a message to the log buffer with a pre-assigned offset
func (p *LocalPartition) addToBufferWithOffset(message *mq_pb.DataMessage, offset int64) error {
// Ensure we have a timestamp
// addToBuffer has the buffer assign the offset under its own lock, so offsets
// stay in append order across publishers.
func (p *LocalPartition) addToBuffer(message *mq_pb.DataMessage) (int64, error) {
processingTsNs := message.TsNs
if processingTsNs == 0 {
processingTsNs = time.Now().UnixNano()
}
// Build a LogEntry that preserves the assigned sequential offset
logEntry := &filer_pb.LogEntry{
TsNs: processingTsNs,
PartitionKeyHash: util.HashToInt32(message.Key),
Data: message.Value,
Key: message.Key,
Offset: offset,
Offset: -1,
}
// Add the entry to the buffer in a way that preserves offset on disk and in-memory
if err := p.LogBuffer.AddLogEntryToBuffer(logEntry); err != nil {
return fmt.Errorf("failed to add log entry to buffer: %w", err)
return 0, fmt.Errorf("failed to add log entry to buffer: %w", err)
}
return nil
return logEntry.Offset, nil
}
// GetOffsetInfo returns offset information for this partition
@@ -84,9 +68,3 @@ func (p *LocalPartition) GetOffsetInfo() map[string]interface{} {
"buffer_offset": p.LogBuffer.GetOffset(),
}
}
// OffsetAwarePublisher wraps a LocalPartition with offset assignment capability
type OffsetAwarePublisher struct {
partition *LocalPartition
assignOffsetFn OffsetAssignmentFunc
}
+6 -2
View File
@@ -34,12 +34,16 @@ func (localTopic *LocalTopic) findPartition(partition Partition) *LocalPartition
glog.V(4).Infof("No matching partition found for %s", partition.String())
return nil
}
func (localTopic *LocalTopic) removePartition(p *LocalPartition) bool {
// removePartition takes p itself out of the list, not a copy that replaced it.
// markRetiring runs first under the same lock, so a lookup finds p either listed
// or retiring.
func (localTopic *LocalTopic) removePartition(p *LocalPartition, markRetiring func()) bool {
localTopic.partitionLock.Lock()
defer localTopic.partitionLock.Unlock()
for i, localPartition := range localTopic.Partitions {
if localPartition == p {
markRetiring()
localTopic.Partitions = append(localTopic.Partitions[:i], localTopic.Partitions[i+1:]...)
return true
}
+27 -35
View File
@@ -443,7 +443,7 @@ func (logBuffer *LogBuffer) InitializeOffsetFromExistingData(getHighestOffsetFn
highestOffset, err := getHighestOffsetFn()
if err != nil {
return nil // Continue with offset 0 if we can't read existing data
return fmt.Errorf("read the highest stored offset: %w", err)
}
if highestOffset >= 0 {
@@ -470,7 +470,8 @@ func (logBuffer *LogBuffer) AddToBuffer(message *mq_pb.DataMessage) error {
return logBuffer.AddDataToBuffer(message.Key, message.Value, message.TsNs)
}
// AddLogEntryToBuffer directly adds a LogEntry to the buffer, preserving offset information
// AddLogEntryToBuffer appends an entry. An entry with a negative Offset is given the
// next offset; an assigned one is kept and moves the next offset past it.
func (logBuffer *LogBuffer) AddLogEntryToBuffer(logEntry *filer_pb.LogEntry) error {
if len(logEntry.Data) > BufferSize {
logBuffer.flushBudget.waitForRoom(len(logEntry.Data))
@@ -512,6 +513,11 @@ func (logBuffer *LogBuffer) AddLogEntryToBuffer(logEntry *filer_pb.LogEntry) err
logBuffer.LastTsNs.Store(processingTsNs)
}
// A negative offset asks the buffer to assign the next one, in append order.
if logEntry.Offset < 0 {
logEntry.Offset = logBuffer.offset
}
// Size is computed without allocating; the entry is marshaled straight into
// the buffer below via MarshalToSizedBufferVT.
size := logEntry.SizeVT()
@@ -522,23 +528,6 @@ func (logBuffer *LogBuffer) AddLogEntryToBuffer(logEntry *filer_pb.LogEntry) err
logBuffer.hasOffsets = false
}
// Track offset ranges for Kafka integration
// Use >= 0 to include offset 0 (first message in a topic)
if logEntry.Offset >= 0 {
if !logBuffer.hasOffsets {
logBuffer.minOffset = logEntry.Offset
logBuffer.maxOffset = logEntry.Offset
logBuffer.hasOffsets = true
} else {
if logEntry.Offset < logBuffer.minOffset {
logBuffer.minOffset = logEntry.Offset
}
if logEntry.Offset > logBuffer.maxOffset {
logBuffer.maxOffset = logEntry.Offset
}
}
}
if logBuffer.startTime.Add(logBuffer.flushInterval).Before(ts) || len(logBuffer.buf)-logBuffer.pos < size+4 {
toFlush = logBuffer.copyToFlush()
logBuffer.startTime = ts
@@ -579,10 +568,27 @@ func (logBuffer *LogBuffer) AddLogEntryToBuffer(logEntry *filer_pb.LogEntry) err
logBuffer.curWindowMaxOriginalTsNs = originalTsNs
}
logBuffer.offset++
logBuffer.trackWindowOffset(logEntry.Offset)
if logEntry.Offset >= logBuffer.offset {
logBuffer.offset = logEntry.Offset + 1
}
return nil
}
// trackWindowOffset widens the current window's offset range. It runs after a
// rollover has sealed the previous window, so each window claims only its own entries.
func (logBuffer *LogBuffer) trackWindowOffset(offset int64) {
if offset < 0 {
return
}
if !logBuffer.hasOffsets {
logBuffer.minOffset, logBuffer.maxOffset, logBuffer.hasOffsets = offset, offset, true
return
}
logBuffer.minOffset = min(logBuffer.minOffset, offset)
logBuffer.maxOffset = max(logBuffer.maxOffset, offset)
}
func (logBuffer *LogBuffer) AddDataToBuffer(partitionKey, data []byte, processingTsNs int64) error {
_, err := logBuffer.AddDataToBufferAndGetTs(partitionKey, data, processingTsNs)
return err
@@ -662,21 +668,6 @@ func (logBuffer *LogBuffer) AddDataToBufferAndGetTs(partitionKey, data []byte, p
logBuffer.hasOffsets = false
}
// Track offset ranges for Kafka integration
// Track the current offset being written
if !logBuffer.hasOffsets {
logBuffer.minOffset = logBuffer.offset
logBuffer.maxOffset = logBuffer.offset
logBuffer.hasOffsets = true
} else {
if logBuffer.offset < logBuffer.minOffset {
logBuffer.minOffset = logBuffer.offset
}
if logBuffer.offset > logBuffer.maxOffset {
logBuffer.maxOffset = logBuffer.offset
}
}
if logBuffer.startTime.Add(logBuffer.flushInterval).Before(ts) || len(logBuffer.buf)-logBuffer.pos < size+4 {
toFlush = logBuffer.copyToFlush()
logBuffer.startTime = ts
@@ -717,6 +708,7 @@ func (logBuffer *LogBuffer) AddDataToBufferAndGetTs(partitionKey, data []byte, p
logBuffer.curWindowMaxOriginalTsNs = originalTsNs
}
logBuffer.trackWindowOffset(logEntry.Offset)
logBuffer.offset++
return logEntry.TsNs, nil
}
@@ -60,8 +60,9 @@ func TestBufferQueryability(t *testing.T) {
t.Fatal("ReadFromBuffer returned nil buffer - data should be queryable immediately")
}
if batchIndex != 1 {
t.Errorf("Expected batchIndex=1, got %d", batchIndex)
// batchIndex is the next offset, one past the entry's
if batchIndex != 2 {
t.Errorf("Expected batchIndex=2, got %d", batchIndex)
}
// Verify we can read the data back
@@ -141,8 +142,8 @@ func TestMultipleEntriesQueryability(t *testing.T) {
t.Fatal("ReadFromBuffer returned nil buffer")
}
if batchIndex != 3 {
t.Errorf("Expected batchIndex=3, got %d", batchIndex)
if batchIndex != 4 {
t.Errorf("Expected batchIndex=4, got %d", batchIndex)
}
// Count entries in buffer
+90
View File
@@ -12,6 +12,7 @@ import (
"github.com/seaweedfs/seaweedfs/weed/pb/mq_pb"
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
"github.com/seaweedfs/seaweedfs/weed/util"
)
func TestNewLogBufferFirstBuffer(t *testing.T) {
@@ -597,3 +598,92 @@ func TestShutdownStopsGoroutinesPromptly(t *testing.T) {
t.Fatal("log buffer goroutines still running 5s after shutdown")
}
}
// Offsets are assigned under the buffer lock, so concurrent appends land in offset order.
func TestAddLogEntryAssignsOffsetsInAppendOrder(t *testing.T) {
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
defer lb.ShutdownLogBuffer()
lb.offset = 100
var wg sync.WaitGroup
for w := 0; w < 8; w++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 100; i++ {
if err := lb.AddLogEntryToBuffer(&filer_pb.LogEntry{TsNs: time.Now().UnixNano(), Key: []byte("k"), Offset: -1}); err != nil {
t.Error(err)
return
}
}
}()
}
wg.Wait()
lb.RLock()
defer lb.RUnlock()
want := int64(100)
for _, pos := range lb.idx {
size := int(util.BytesToUint32(lb.buf[pos : pos+4]))
entry := &filer_pb.LogEntry{}
if err := entry.UnmarshalVT(lb.buf[pos+4 : pos+4+size]); err != nil {
t.Fatal(err)
}
if entry.Offset != want {
t.Fatalf("entry at %d has offset %d, want %d", pos, entry.Offset, want)
}
want++
}
if want != 900 || lb.offset != 900 {
t.Fatalf("appended up to %d, next offset %d; want 900", want, lb.offset)
}
}
func TestAddLogEntryKeepsAssignedOffset(t *testing.T) {
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
defer lb.ShutdownLogBuffer()
entry := &filer_pb.LogEntry{TsNs: time.Now().UnixNano(), Key: []byte("k"), Offset: 500}
if err := lb.AddLogEntryToBuffer(entry); err != nil {
t.Fatal(err)
}
if entry.Offset != 500 || lb.offset != 501 {
t.Fatalf("offset %d, next %d; want 500, 501", entry.Offset, lb.offset)
}
}
// The entry that rolls the window over belongs to the new window, not the sealed one.
func TestWindowOffsetRangeAcrossRollover(t *testing.T) {
type window struct{ min, max int64 }
flushed := make(chan window, 4)
lb := NewLogBuffer("test", time.Second, func(_ *LogBuffer, _, _ time.Time, _ []byte, minOffset, maxOffset int64) {
flushed <- window{minOffset, maxOffset}
}, nil, func() {})
start := time.Now().UnixNano()
for i, ts := range []int64{start, start + int64(time.Millisecond), start + int64(2*time.Second)} {
if err := lb.AddLogEntryToBuffer(&filer_pb.LogEntry{TsNs: ts, Key: []byte("k"), Offset: -1}); err != nil {
t.Fatalf("append %d: %v", i, err)
}
}
lb.ShutdownLogBuffer()
lb.WaitForShutdown()
close(flushed)
var got []window
for w := range flushed {
got = append(got, w)
}
want := []window{{0, 1}, {2, 2}}
if len(got) != len(want) || got[0] != want[0] || got[1] != want[1] {
t.Fatalf("flushed windows %v, want %v", got, want)
}
}
func TestInitializeOffsetReportsUnreadableStore(t *testing.T) {
lb := NewLogBuffer("test", time.Hour, nil, nil, func() {})
defer lb.ShutdownLogBuffer()
err := lb.InitializeOffsetFromExistingData(func() (int64, error) { return -1, fmt.Errorf("filer unavailable") })
if err == nil {
t.Fatal("an unreadable store must not seed offsets from 0")
}
}