From 52fbbec2fdf42d4fd47b188615d31a79a9a46231 Mon Sep 17 00:00:00 2001 From: pisceslj Date: Fri, 13 Nov 2026 12:14:48 +0800 Subject: [PATCH 1/7] [server] Implement consumer group management APIs Implement list and delete consumer groups and delete consumer offsets on the tablet server. Add group metadata key encoders, per-bucket offset deletion results, and INVALID_REQUEST validation for duplicate group IDs and table buckets. Authorize live source tables before offset deletion and update the authorization documentation. --- .../rpc/gateway/TabletServerGateway.java | 8 +- fluss-rpc/src/main/proto/FlussApi.proto | 2 +- .../fluss/server/tablet/TabletService.java | 92 ++++++- .../consumer/group/ConsumerGroupManager.java | 242 +++++++++++++++++- .../consumer/group/ConsumerOffsetSchema.java | 44 +++- .../result/DeleteConsumerOffsetsResult.java | 60 +++++ .../result/ListConsumerGroupsResult.java | 58 +++++ .../server/utils/ServerRpcMessageUtils.java | 109 ++++++++ .../group/ConsumerGroupManagerFetchTest.java | 2 +- .../group/ConsumerOffsetSchemaTest.java | 47 +++- .../group/GroupManagerManagementTest.java | 114 +++++++++ .../utils/ServerRpcMessageUtilsTest.java | 90 +++++++ website/docs/security/authorization.md | 3 + 13 files changed, 844 insertions(+), 27 deletions(-) create mode 100644 fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/result/DeleteConsumerOffsetsResult.java create mode 100644 fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/result/ListConsumerGroupsResult.java create mode 100644 fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/GroupManagerManagementTest.java diff --git a/fluss-rpc/src/main/java/org/apache/fluss/rpc/gateway/TabletServerGateway.java b/fluss-rpc/src/main/java/org/apache/fluss/rpc/gateway/TabletServerGateway.java index 69f4fa7a03d..727c4bcf421 100644 --- a/fluss-rpc/src/main/java/org/apache/fluss/rpc/gateway/TabletServerGateway.java +++ b/fluss-rpc/src/main/java/org/apache/fluss/rpc/gateway/TabletServerGateway.java @@ -227,7 +227,13 @@ CompletableFuture deleteConsumerOffsets( CompletableFuture listConsumerGroups( ListConsumerGroupsRequest request); - /** Delete consumer groups and all of their committed offsets. */ + /** + * Delete consumer-group metadata. Committed offsets are not removed by this request. + * + *

This is not a cluster-wide request. Callers must route each group to the tablet server + * that owns the group's consumer-offsets bucket; groups not owned by this server are reported + * with {@code NOT_CONSUMER_GROUP_OWNER}. + */ @RPC(api = ApiKeys.DELETE_CONSUMER_GROUPS) CompletableFuture deleteConsumerGroups( DeleteConsumerGroupsRequest request); diff --git a/fluss-rpc/src/main/proto/FlussApi.proto b/fluss-rpc/src/main/proto/FlussApi.proto index 5c04fe2c20b..7385117dab4 100644 --- a/fluss-rpc/src/main/proto/FlussApi.proto +++ b/fluss-rpc/src/main/proto/FlussApi.proto @@ -528,7 +528,7 @@ message ListConsumerGroupsResponse { repeated PbListedGroup groups = 1; } -// Delete consumer groups request and response. +// Delete consumer-group metadata. Committed offsets are not removed by this request. message DeleteConsumerGroupsRequest { // An empty list is a valid no-op and produces an empty successful response. repeated string groups = 1; diff --git a/fluss-server/src/main/java/org/apache/fluss/server/tablet/TabletService.java b/fluss-server/src/main/java/org/apache/fluss/server/tablet/TabletService.java index 37ea46ffe35..4ac543028fd 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/tablet/TabletService.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/tablet/TabletService.java @@ -20,6 +20,7 @@ import org.apache.fluss.cluster.ServerType; import org.apache.fluss.exception.ApiException; import org.apache.fluss.exception.AuthorizationException; +import org.apache.fluss.exception.InvalidRequestException; import org.apache.fluss.exception.InvalidScanRequestException; import org.apache.fluss.exception.InvalidTableException; import org.apache.fluss.exception.NotLeaderOrFollowerException; @@ -142,6 +143,7 @@ import java.util.Collection; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; @@ -158,11 +160,13 @@ import static org.apache.fluss.rpc.util.CommonRpcMessageUtils.hasHistoricalProduce; import static org.apache.fluss.rpc.util.CommonRpcMessageUtils.hasHistoricalPut; import static org.apache.fluss.security.acl.OperationType.DESCRIBE; +import static org.apache.fluss.security.acl.OperationType.DROP; import static org.apache.fluss.security.acl.OperationType.READ; import static org.apache.fluss.security.acl.OperationType.WRITE; import static org.apache.fluss.server.coordinator.CoordinatorContext.INITIAL_COORDINATOR_EPOCH; import static org.apache.fluss.server.log.FetchParams.DEFAULT_MAX_WAIT_MS_WHEN_MIN_BYTES_ENABLE; import static org.apache.fluss.server.utils.ServerRpcMessageUtils.decodeCommitConsumerOffsetsRequest; +import static org.apache.fluss.server.utils.ServerRpcMessageUtils.decodeDeleteConsumerOffsetsRequest; import static org.apache.fluss.server.utils.ServerRpcMessageUtils.decodeGetConsumerOffsetsRequest; import static org.apache.fluss.server.utils.ServerRpcMessageUtils.getFetchLogData; import static org.apache.fluss.server.utils.ServerRpcMessageUtils.getListOffsetsData; @@ -928,28 +932,86 @@ private Map filterOffsetsByAuthorizedTab @Override public CompletableFuture deleteConsumerOffsets( DeleteConsumerOffsetsRequest request) { - CompletableFuture response = new CompletableFuture<>(); - response.completeExceptionally( - new UnsupportedOperationException("deleteConsumerOffsets is not supported yet")); - return response; + final GroupId groupId; + final Replica offsetsReplica; + final List requestedBuckets; + try { + groupId = GroupId.of(request.getGroupId()); + if (authorizer != null) { + authorizer.authorize(currentSession(), DROP, Resource.group(groupId)); + } + offsetsReplica = groupManager.validateGroupId(groupId); + requestedBuckets = decodeDeleteConsumerOffsetsRequest(request); + } catch (ApiException e) { + return FutureUtils.completedExceptionally(e); + } + if (requestedBuckets.isEmpty()) { + return CompletableFuture.completedFuture(new DeleteConsumerOffsetsResponse()); + } + + // The session is bound to the RPC thread. Live source tables require READ before their + // offsets can be deleted. Deleted source tables no longer have a table resource, so their + // cleanup is authorized by the consumer-group permission above. + if (authorizer != null) { + requestedBuckets.stream() + .map(TableBucket::getTableId) + .distinct() + .forEach(this::authorizeLiveSourceTable); + } + + return groupManager + .handleDeleteConsumerOffsets(groupId, offsetsReplica, requestedBuckets) + .thenApply(ServerRpcMessageUtils::makeDeleteConsumerOffsetsResponse); } @Override public CompletableFuture listConsumerGroups( ListConsumerGroupsRequest request) { - CompletableFuture response = new CompletableFuture<>(); - response.completeExceptionally( - new UnsupportedOperationException("listConsumerGroups is not supported yet")); - return response; + if (authorizer != null) { + authorizer.authorize(currentSession(), OperationType.DESCRIBE, Resource.cluster()); + } + return groupManager + .handleListConsumerGroups() + .thenApply(ServerRpcMessageUtils::makeListConsumerGroupsResponse); } @Override public CompletableFuture deleteConsumerGroups( DeleteConsumerGroupsRequest request) { - CompletableFuture response = new CompletableFuture<>(); - response.completeExceptionally( - new UnsupportedOperationException("deleteConsumerGroups is not supported yet")); - return response; + List groupIds = new ArrayList<>(); + for (String groupId : request.getGroupsList()) { + groupIds.add(GroupId.of(groupId)); + } + if (new HashSet<>(groupIds).size() != groupIds.size()) { + CompletableFuture failed = new CompletableFuture<>(); + failed.completeExceptionally( + new InvalidRequestException( + "DeleteConsumerGroups request contains duplicate group IDs")); + return failed; + } + if (groupIds.isEmpty()) { + return CompletableFuture.completedFuture(new DeleteConsumerGroupsResponse()); + } + + if (authorizer != null) { + for (GroupId groupId : groupIds) { + authorizer.authorize(currentSession(), DROP, Resource.group(groupId)); + } + } + + final Map offsetsReplicasByGroup; + try { + offsetsReplicasByGroup = new HashMap<>(); + for (GroupId groupId : groupIds) { + offsetsReplicasByGroup.put(groupId, groupManager.validateGroupId(groupId)); + } + } catch (ApiException e) { + return FutureUtils.completedExceptionally(e); + } + + return groupManager + .handleDeleteConsumerGroups(offsetsReplicasByGroup) + .thenApply(ServerRpcMessageUtils::makeDeleteConsumerGroupsResponse); } @Override @@ -1180,6 +1242,12 @@ private CompletableFuture submitReplicaStateChange( return response; } + private void authorizeLiveSourceTable(long tableId) { + if (metadataCache.getTablePath(tableId).isPresent()) { + authorizeTable(READ, tableId); + } + } + @Override public void authorizeTable(OperationType operationType, long tableId) { if (authorizer != null) { diff --git a/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManager.java b/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManager.java index 080c944c31a..0435b0c384a 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManager.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManager.java @@ -59,6 +59,8 @@ import org.apache.fluss.server.replica.ReplicaManager; import org.apache.fluss.server.replica.ReplicaManager.HostedReplica; import org.apache.fluss.server.replica.ReplicaManager.OnlineReplica; +import org.apache.fluss.server.tablet.consumer.group.result.DeleteConsumerOffsetsResult; +import org.apache.fluss.server.tablet.consumer.group.result.ListConsumerGroupsResult; import org.apache.fluss.server.zk.ZooKeeperClient; import org.apache.fluss.server.zk.data.TabletServerRegistration; import org.apache.fluss.utils.ByteArraySlice; @@ -77,12 +79,15 @@ import java.util.Map; import java.util.Optional; import java.util.OptionalInt; +import java.util.Set; +import java.util.TreeSet; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicReference; import static org.apache.fluss.server.metadata.TableMetadata.DELETED_TABLE_ID; import static org.apache.fluss.server.metadata.TableMetadata.DELETED_TABLE_PATH; +import static org.apache.fluss.server.tablet.consumer.group.ConsumerOffsetSchema.GROUP_METADATA_RECORD_TYPE; import static org.apache.fluss.server.tablet.consumer.group.ConsumerOffsetSchema.OFFSET_COMMIT_RECORD_TYPE; import static org.apache.fluss.server.tablet.consumer.group.ConsumerOffsetTableConfig.OFFSET_COMMIT_REQUIRED_ACKS; import static org.apache.fluss.server.zk.data.LeaderAndIsr.NO_LEADER; @@ -387,7 +392,12 @@ private TableInfo createOrResolveTableInfo() { } } - /** Appends on the calling worker and completes the result when the write is acknowledged. */ + /** + * Appends on the calling worker and completes the result when the write is acknowledged. + * + *

TODO: Decide whether group metadata rows are written by an explicit create-group operation + * or with the first offset commit. List and delete group management depend on these rows. + */ public CompletableFuture> handleCommitConsumerOffsets( GroupId groupId, Replica offsetsReplica, @@ -430,6 +440,57 @@ public CompletableFuture> handleCommitConsumerOffsets( writeResults -> handleWriteCompletion(groupId, results, writeResults)); } + /** + * Deletes selected committed offsets; missing buckets are successful no-ops. Offset reads run + * on the calling thread and tombstone writes are asynchronous. + */ + public CompletableFuture handleDeleteConsumerOffsets( + GroupId groupId, Replica offsetsReplica, List requestedBuckets) { + try { + List keys = new ArrayList<>(requestedBuckets.size()); + for (TableBucket tableBucket : requestedBuckets) { + keys.add( + offsetSchema.encodeOffsetKey( + groupId, + tableBucket.getTableId(), + tableBucket.getPartitionId(), + tableBucket.getBucket())); + } + List values = offsetsReplica.lookups(keys); + List keysToDelete = existingKeys(keys, values); + + // Every requested bucket is reported. Missing offsets are successful no-ops, so they + // start as NONE and only buckets whose writes fail are changed. + Map results = new HashMap<>(); + for (TableBucket tableBucket : requestedBuckets) { + results.put(tableBucket, Errors.NONE); + } + + if (keysToDelete.isEmpty()) { + return CompletableFuture.completedFuture( + DeleteConsumerOffsetsResult.success(results)); + } + return deleteKeys(offsetsReplica, keysToDelete) + .handle( + (ignored, error) -> { + if (error == null) { + return DeleteConsumerOffsetsResult.success(results); + } + + Errors writeError = Errors.forException(error); + for (int i = 0; i < requestedBuckets.size(); i++) { + if (values.get(i) != null) { + results.put(requestedBuckets.get(i), writeError); + } + } + return DeleteConsumerOffsetsResult.success(results); + }); + } catch (Exception e) { + return CompletableFuture.completedFuture( + DeleteConsumerOffsetsResult.failure(Errors.forException(e))); + } + } + /** * Reads all or selected committed offsets from the local leader replica on the calling thread. */ @@ -508,6 +569,183 @@ static void populateSelectedOffsets( } } + /** + * Lists distinct consumer groups from consumer-offset buckets led by this server. Prefix reads + * run on the calling thread once offsets-table metadata is available. + */ + public CompletableFuture handleListConsumerGroups() { + return ensureTableAsync() + .thenApply( + offsetsTableInfo -> { + try { + Set groupIds = new TreeSet<>(); + for (int bucketId = 0; + bucketId < offsetsTableInfo.getNumBuckets(); + bucketId++) { + Replica replica = + localLeaderReplica( + new TableBucket( + offsetsTableInfo.getTableId(), + bucketId)); + if (replica == null) { + continue; + } + populateGroupIds( + replica.prefixLookup( + offsetSchema.encodeGroupMetadataPrefix()), + getValueDecoder(replica.getSchemaGetter()), + groupIds); + } + return ListConsumerGroupsResult.success(new ArrayList<>(groupIds)); + } catch (Exception e) { + LOG.warn("Failed to list consumer groups.", e); + return ListConsumerGroupsResult.failure(Errors.forException(e)); + } + }); + } + + /** + * Deletes consumer-group metadata rows owned by this server. Callers are expected to route each + * group to its owner. Metadata reads run on the calling thread and tombstone writes are + * asynchronous. + */ + public CompletableFuture> handleDeleteConsumerGroups( + Map offsetsReplicasByGroup) { + List> deletions = new ArrayList<>(offsetsReplicasByGroup.size()); + for (Map.Entry entry : offsetsReplicasByGroup.entrySet()) { + GroupId groupId = entry.getKey(); + Replica replica = entry.getValue(); + try { + List keys = + groupRowKeys(replica, groupId, getValueDecoder(replica.getSchemaGetter())); + if (keys.isEmpty()) { + deletions.add( + CompletableFuture.completedFuture(Errors.CONSUMER_GROUP_ID_NOT_FOUND)); + } else { + deletions.add( + deleteKeys(replica, keys) + .handle( + (ignored, error) -> + error == null + ? Errors.NONE + : Errors.forException(error))); + } + } catch (Exception e) { + deletions.add(CompletableFuture.completedFuture(Errors.forException(e))); + } + } + return CompletableFuture.allOf(deletions.toArray(new CompletableFuture[0])) + .thenApply( + allDone -> { + Map results = new HashMap<>(); + int i = 0; + for (GroupId groupId : offsetsReplicasByGroup.keySet()) { + results.put(groupId.getGroupId(), deletions.get(i++).join()); + } + return results; + }); + } + + private List groupRowKeys(Replica replica, GroupId groupId, ValueDecoder valueDecoder) + throws Exception { + return encodeGroupRowKeys( + groupId, + replica.prefixLookup(offsetSchema.encodeGroupMetadataPrefix(groupId)), + valueDecoder); + } + + @VisibleForTesting + static void populateGroupIds( + List values, ValueDecoder valueDecoder, Set groupIds) + throws Exception { + for (ByteArraySlice value : values) { + InternalRow row = valueDecoder.decodeValue(value.toByteArray()).row; + if (row.getInt(0) == GROUP_METADATA_RECORD_TYPE) { + groupIds.add(row.getString(1).toString()); + } + } + } + + @VisibleForTesting + static List encodeGroupRowKeys( + GroupId groupId, List values, ValueDecoder valueDecoder) + throws Exception { + ConsumerOffsetSchema schema = new ConsumerOffsetSchema(); + List keys = new ArrayList<>(); + for (ByteArraySlice value : values) { + InternalRow row = valueDecoder.decodeValue(value.toByteArray()).row; + if (row.getInt(0) != GROUP_METADATA_RECORD_TYPE) { + continue; + } + TableBucket tableBucket = ConsumerOffsetSchema.toTableBucket(row); + keys.add( + schema.encodeGroupMetadataKey( + groupId, + tableBucket.getTableId(), + tableBucket.getPartitionId(), + tableBucket.getBucket())); + } + return keys; + } + + @VisibleForTesting + static List existingKeys(List keys, List values) { + List existing = new ArrayList<>(); + for (int i = 0; i < keys.size(); i++) { + if (values.get(i) != null) { + existing.add(keys.get(i)); + } + } + return existing; + } + + private CompletableFuture deleteKeys(Replica replica, List keys) { + CompletableFuture result = new CompletableFuture<>(); + try { + KvRecordBatchBuilder builder = + KvRecordBatchBuilder.builder( + replica.getTableInfo().getSchemaId(), + Integer.MAX_VALUE, + new UnmanagedPagedOutputView(OFFSET_COMMIT_PAGE_SIZE), + KvFormat.COMPACTED); + for (byte[] key : keys) { + builder.append(key, null); + } + KvRecordBatch batch = DefaultKvRecordBatch.pointToBytesView(builder.build()); + replicaManager.putRecordsToKv( + offsetsConfig.getOffsetCommitTimeoutMs(), + OFFSET_COMMIT_REQUIRED_ACKS, + Collections.singletonMap(replica.getTableBucket(), batch), + null, + MergeMode.DEFAULT, + ApiKeys.PUT_KV.highestSupportedVersion, + writeResults -> { + for (PutKvResultForBucket writeResult : writeResults) { + if (writeResult.getError().error() != Errors.NONE) { + result.completeExceptionally( + mapCommitError(writeResult.getError().error()).exception()); + return; + } + } + result.complete(null); + }); + } catch (Exception e) { + result.completeExceptionally(e); + } + return result; + } + + private Replica localLeaderReplica(TableBucket offsetTableBucket) { + HostedReplica hostedReplica = replicaManager.getReplica(offsetTableBucket); + if (hostedReplica instanceof OnlineReplica) { + Replica replica = ((OnlineReplica) hostedReplica).getReplica(); + if (replica.isLeader()) { + return replica; + } + } + return null; + } + @VisibleForTesting static Map handleWriteCompletion( GroupId groupId, @@ -545,8 +783,8 @@ private KvRecordBatch buildUpsertBatch( TableBucket tableBucket = entry.getKey(); CompactedRow row = offsetSchema.encodeOffsetRow( - groupId, OFFSET_COMMIT_RECORD_TYPE, + groupId, tableBucket.getTableId(), tableBucket.getPartitionId(), tableBucket.getBucket(), diff --git a/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchema.java b/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchema.java index f315437d1a8..5c32b759815 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchema.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchema.java @@ -73,6 +73,9 @@ public final class ConsumerOffsetSchema { private static final List GROUP_LOOKUP_PREFIX_KEYS = Collections.unmodifiableList(Arrays.asList(RECORD_TYPE_COLUMN, GROUP_ID_COLUMN)); + private static final List GROUP_METADATA_PREFIX_KEYS = + Collections.singletonList(RECORD_TYPE_COLUMN); + private static final Schema TABLE_SCHEMA = createTableSchema(); private static final RowType ROW_TYPE = TABLE_SCHEMA.getRowType(); private static final DataType[] DATA_TYPES = ROW_TYPE.getChildren().toArray(new DataType[0]); @@ -93,6 +96,11 @@ public final class ConsumerOffsetSchema { private final ThreadLocal groupLookupPrefixEncoder = ThreadLocal.withInitial( () -> KeyEncoder.ofBucketKeyEncoder(ROW_TYPE, GROUP_LOOKUP_PREFIX_KEYS, null)); + private final ThreadLocal groupMetadataAllPrefixEncoder = + ThreadLocal.withInitial( + () -> + KeyEncoder.ofBucketKeyEncoder( + ROW_TYPE, GROUP_METADATA_PREFIX_KEYS, null)); /** Returns the schema of the consumer-offset system table. */ public static Schema getTableSchema() { @@ -161,6 +169,40 @@ public byte[] encodeOffsetCommitPrefix(GroupId groupId) { BinaryString.fromString(groupId.getGroupId()))); } + /** Encodes the {@code record_type} prefix used to enumerate all group metadata rows. */ + public byte[] encodeGroupMetadataPrefix() { + return groupMetadataAllPrefixEncoder + .get() + .encodeKey(GenericRow.of(GROUP_METADATA_RECORD_TYPE)); + } + + /** + * Encodes the {@code record_type} and {@code group_id} prefix used to enumerate one group's + * metadata rows. + */ + public byte[] encodeGroupMetadataPrefix(GroupId groupId) { + return groupLookupPrefixEncoder + .get() + .encodeKey( + GenericRow.of( + GROUP_METADATA_RECORD_TYPE, + BinaryString.fromString(groupId.getGroupId()))); + } + + /** Encodes the complete primary key of a group metadata row. */ + public byte[] encodeGroupMetadataKey( + GroupId groupId, long tableId, Long partitionId, int bucketId) { + return primaryKeyEncoder + .get() + .encodeKey( + GenericRow.of( + GROUP_METADATA_RECORD_TYPE, + BinaryString.fromString(groupId.getGroupId()), + tableId, + partitionId == null ? NON_PARTITIONED_PARTITION_ID : partitionId, + bucketId)); + } + /** Encodes the complete primary key of an already materialized offset row. */ byte[] encodeOffsetKey(InternalRow row) { return primaryKeyEncoder.get().encodeKey(row); @@ -172,8 +214,8 @@ int bucketFor(GroupId groupId, int bucketCount) { /** The returned row uses this thread's buffer until its next call to this method. */ CompactedRow encodeOffsetRow( - GroupId groupId, int recordType, + GroupId groupId, long tableId, Long partitionId, int bucketId, diff --git a/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/result/DeleteConsumerOffsetsResult.java b/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/result/DeleteConsumerOffsetsResult.java new file mode 100644 index 00000000000..f033fea25d9 --- /dev/null +++ b/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/result/DeleteConsumerOffsetsResult.java @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.fluss.server.tablet.consumer.group.result; + +import org.apache.fluss.annotation.Internal; +import org.apache.fluss.metadata.TableBucket; +import org.apache.fluss.rpc.protocol.Errors; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.apache.fluss.utils.Preconditions.checkNotNull; + +/** Result of deleting committed offsets for selected table buckets. */ +@Internal +public final class DeleteConsumerOffsetsResult { + + private final Errors error; + private final Map bucketErrors; + + private DeleteConsumerOffsetsResult(Errors error, Map bucketErrors) { + this.error = checkNotNull(error, "error must not be null"); + this.bucketErrors = + Collections.unmodifiableMap( + new LinkedHashMap<>( + checkNotNull(bucketErrors, "bucketErrors must not be null"))); + } + + public static DeleteConsumerOffsetsResult success(Map bucketErrors) { + return new DeleteConsumerOffsetsResult(Errors.NONE, bucketErrors); + } + + public static DeleteConsumerOffsetsResult failure(Errors error) { + return new DeleteConsumerOffsetsResult(error, Collections.emptyMap()); + } + + public Errors getError() { + return error; + } + + public Map getBucketErrors() { + return bucketErrors; + } +} diff --git a/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/result/ListConsumerGroupsResult.java b/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/result/ListConsumerGroupsResult.java new file mode 100644 index 00000000000..0456b36e5e7 --- /dev/null +++ b/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/result/ListConsumerGroupsResult.java @@ -0,0 +1,58 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.fluss.server.tablet.consumer.group.result; + +import org.apache.fluss.annotation.Internal; +import org.apache.fluss.rpc.protocol.Errors; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import static org.apache.fluss.utils.Preconditions.checkNotNull; + +/** Result of listing consumer groups stored on a tablet server. */ +@Internal +public final class ListConsumerGroupsResult { + + private final Errors error; + private final List groupIds; + + private ListConsumerGroupsResult(Errors error, List groupIds) { + this.error = checkNotNull(error, "error must not be null"); + this.groupIds = + Collections.unmodifiableList( + new ArrayList<>(checkNotNull(groupIds, "groupIds must not be null"))); + } + + public static ListConsumerGroupsResult success(List groupIds) { + return new ListConsumerGroupsResult(Errors.NONE, groupIds); + } + + public static ListConsumerGroupsResult failure(Errors error) { + return new ListConsumerGroupsResult(error, Collections.emptyList()); + } + + public Errors getError() { + return error; + } + + public List getGroupIds() { + return groupIds; + } +} diff --git a/fluss-server/src/main/java/org/apache/fluss/server/utils/ServerRpcMessageUtils.java b/fluss-server/src/main/java/org/apache/fluss/server/utils/ServerRpcMessageUtils.java index 43c7b968511..f8ad531b18e 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/utils/ServerRpcMessageUtils.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/utils/ServerRpcMessageUtils.java @@ -78,6 +78,9 @@ import org.apache.fluss.rpc.messages.CommitLakeTableSnapshotRequest; import org.apache.fluss.rpc.messages.CommitRemoteLogManifestRequest; import org.apache.fluss.rpc.messages.CreateAclsResponse; +import org.apache.fluss.rpc.messages.DeleteConsumerGroupsResponse; +import org.apache.fluss.rpc.messages.DeleteConsumerOffsetsRequest; +import org.apache.fluss.rpc.messages.DeleteConsumerOffsetsResponse; import org.apache.fluss.rpc.messages.DescribeClusterResponse; import org.apache.fluss.rpc.messages.DropAclsResponse; import org.apache.fluss.rpc.messages.FetchLogRequest; @@ -96,6 +99,7 @@ import org.apache.fluss.rpc.messages.LakeTieringHeartbeatResponse; import org.apache.fluss.rpc.messages.LimitScanResponse; import org.apache.fluss.rpc.messages.ListAclsResponse; +import org.apache.fluss.rpc.messages.ListConsumerGroupsResponse; import org.apache.fluss.rpc.messages.ListOffsetsRequest; import org.apache.fluss.rpc.messages.ListOffsetsResponse; import org.apache.fluss.rpc.messages.ListPartitionInfosResponse; @@ -124,6 +128,11 @@ import org.apache.fluss.rpc.messages.PbCommitConsumerOffsetsResponseTable; import org.apache.fluss.rpc.messages.PbCreateAclRespInfo; import org.apache.fluss.rpc.messages.PbDatabaseSummary; +import org.apache.fluss.rpc.messages.PbDeleteConsumerOffsetsRequestBucket; +import org.apache.fluss.rpc.messages.PbDeleteConsumerOffsetsRequestTable; +import org.apache.fluss.rpc.messages.PbDeleteConsumerOffsetsResponseBucket; +import org.apache.fluss.rpc.messages.PbDeleteConsumerOffsetsResponseTable; +import org.apache.fluss.rpc.messages.PbDeletedGroup; import org.apache.fluss.rpc.messages.PbDescribeConfig; import org.apache.fluss.rpc.messages.PbDropAclsFilterResult; import org.apache.fluss.rpc.messages.PbDropAclsMatchingAcl; @@ -145,6 +154,7 @@ import org.apache.fluss.rpc.messages.PbLakeTableSnapshotInfo; import org.apache.fluss.rpc.messages.PbLakeTableSnapshotMetadata; import org.apache.fluss.rpc.messages.PbListOffsetsRespForBucket; +import org.apache.fluss.rpc.messages.PbListedGroup; import org.apache.fluss.rpc.messages.PbLookupReqForBucket; import org.apache.fluss.rpc.messages.PbLookupRespForBucket; import org.apache.fluss.rpc.messages.PbModifyColumn; @@ -220,6 +230,8 @@ import org.apache.fluss.server.metadata.ServerInfo; import org.apache.fluss.server.metadata.TableMetadata; import org.apache.fluss.server.tablet.consumer.group.ConsumerOffsetAndMetadata; +import org.apache.fluss.server.tablet.consumer.group.result.DeleteConsumerOffsetsResult; +import org.apache.fluss.server.tablet.consumer.group.result.ListConsumerGroupsResult; import org.apache.fluss.server.zk.ZooKeeperClient.TableBucketAndManifest; import org.apache.fluss.server.zk.data.BucketSnapshot; import org.apache.fluss.server.zk.data.LeaderAndIsr; @@ -1501,6 +1513,103 @@ public static CommitConsumerOffsetsResponse makeCommitConsumerOffsetsResponse( return response; } + /** Decodes the buckets whose committed offsets should be deleted. */ + public static List decodeDeleteConsumerOffsetsRequest( + DeleteConsumerOffsetsRequest request) { + List requestedBuckets = new ArrayList<>(); + Set seenBuckets = new HashSet<>(); + for (PbDeleteConsumerOffsetsRequestTable table : request.getTablesList()) { + for (PbDeleteConsumerOffsetsRequestBucket bucket : table.getBucketsList()) { + Long partitionId = bucket.hasPartitionId() ? bucket.getPartitionId() : null; + TableBucket tableBucket = + new TableBucket(table.getTableId(), partitionId, bucket.getBucketId()); + if (!seenBuckets.add(tableBucket)) { + throw new InvalidRequestException( + "Duplicate table bucket in DeleteConsumerOffsets request: " + + tableBucket); + } + requestedBuckets.add(tableBucket); + } + } + return requestedBuckets; + } + + /** Builds the list-groups response. */ + public static ListConsumerGroupsResponse makeListConsumerGroupsResponse( + ListConsumerGroupsResult result) { + if (result.getError() != Errors.NONE) { + throw result.getError().exception(); + } + + ListConsumerGroupsResponse response = new ListConsumerGroupsResponse(); + List groups = new ArrayList<>(); + for (String groupId : result.getGroupIds()) { + groups.add(new PbListedGroup().setGroupId(groupId)); + } + response.addAllGroups(groups); + return response; + } + + /** Builds the per-group delete-groups response. */ + public static DeleteConsumerGroupsResponse makeDeleteConsumerGroupsResponse( + Map results) { + DeleteConsumerGroupsResponse response = new DeleteConsumerGroupsResponse(); + List groups = new ArrayList<>(); + results.forEach( + (groupId, error) -> { + PbDeletedGroup group = new PbDeletedGroup().setGroupId(groupId); + if (error != Errors.NONE) { + group.setErrorCode(error.code()); + if (error.message() != null) { + group.setErrorMessage(error.message()); + } + } + groups.add(group); + }); + response.addAllGroups(groups); + return response; + } + + /** Builds the delete-offsets response. */ + public static DeleteConsumerOffsetsResponse makeDeleteConsumerOffsetsResponse( + DeleteConsumerOffsetsResult result) { + if (result.getError() != Errors.NONE) { + throw result.getError().exception(); + } + + Map> bucketsByTable = new HashMap<>(); + result.getBucketErrors() + .forEach( + (tableBucket, error) -> { + PbDeleteConsumerOffsetsResponseBucket bucket = + new PbDeleteConsumerOffsetsResponseBucket() + .setBucketId(tableBucket.getBucket()); + if (tableBucket.getPartitionId() != null) { + bucket.setPartitionId(tableBucket.getPartitionId()); + } + if (error != Errors.NONE) { + bucket.setErrorCode(error.code()); + if (error.message() != null) { + bucket.setErrorMessage(error.message()); + } + } + bucketsByTable + .computeIfAbsent( + tableBucket.getTableId(), ignored -> new ArrayList<>()) + .add(bucket); + }); + + DeleteConsumerOffsetsResponse response = new DeleteConsumerOffsetsResponse(); + bucketsByTable.forEach( + (tableId, buckets) -> + response.addAllTables( + Collections.singletonList( + new PbDeleteConsumerOffsetsResponseTable() + .setTableId(tableId) + .addAllBuckets(buckets)))); + return response; + } + public static PutKvResponse makePutKvResponse(Collection kvPutResult) { PutKvResponse putKvResponse = new PutKvResponse(); List putKvRespForBucketList = new ArrayList<>(); diff --git a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagerFetchTest.java b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagerFetchTest.java index 58862e68e3b..341c26d5c2f 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagerFetchTest.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagerFetchTest.java @@ -125,8 +125,8 @@ private static byte[] encodedOffset( CompactedRow row = new ConsumerOffsetSchema() .encodeOffsetRow( - GroupId.of(groupId), ConsumerOffsetSchema.OFFSET_COMMIT_RECORD_TYPE, + GroupId.of(groupId), tableBucket.getTableId(), tableBucket.getPartitionId(), tableBucket.getBucket(), diff --git a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchemaTest.java b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchemaTest.java index 311ebf37641..525bff7030e 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchemaTest.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchemaTest.java @@ -67,12 +67,41 @@ void testSchemaMatchesFip() { "metadata"); } + @Test + void testGroupMetadataPrefixAndKeyUseRecordTypeAndGroupId() { + GroupId groupId = GroupId.of("my-group"); + KeyEncoder prefixEncoder = + KeyEncoder.ofBucketKeyEncoder( + ConsumerOffsetSchema.getTableSchema().getRowType(), + Arrays.asList("record_type", "group_id"), + null); + KeyEncoder keyEncoder = + KeyEncoder.ofBucketKeyEncoder( + ConsumerOffsetSchema.getTableSchema().getRowType(), + ConsumerOffsetSchema.getPrimaryKeys(), + null); + + CompactedRow row = + offsetSchema.encodeOffsetRow( + ConsumerOffsetSchema.GROUP_METADATA_RECORD_TYPE, + groupId, + -1L, + null, + -1, + new ConsumerOffsetAndMetadata(-1L, "")); + + assertThat(offsetSchema.encodeGroupMetadataPrefix(groupId)) + .isEqualTo(prefixEncoder.encodeKey(row)); + assertThat(offsetSchema.encodeGroupMetadataKey(groupId, -1L, null, -1)) + .isEqualTo(keyEncoder.encodeKey(row)); + } + @Test void testOffsetCommitValueRoundTrip() { CompactedRow row = offsetSchema.encodeOffsetRow( - GroupId.of("my-group"), ConsumerOffsetSchema.OFFSET_COMMIT_RECORD_TYPE, + GroupId.of("my-group"), 42L, 7L, 3, @@ -92,8 +121,8 @@ void testOffsetCommitValueRoundTrip() { void testOmittedAndEmptyMetadataHaveDistinctEncodings() { CompactedRow absent = offsetSchema.encodeOffsetRow( - GroupId.of("g"), ConsumerOffsetSchema.OFFSET_COMMIT_RECORD_TYPE, + GroupId.of("g"), 1L, null, 0, @@ -103,8 +132,8 @@ void testOmittedAndEmptyMetadataHaveDistinctEncodings() { CompactedRow empty = offsetSchema.encodeOffsetRow( - GroupId.of("g"), ConsumerOffsetSchema.OFFSET_COMMIT_RECORD_TYPE, + GroupId.of("g"), 1L, null, 0, @@ -118,8 +147,8 @@ void testNullPartitionIdEncodesAsMinusOneSentinel() { // Non-partitioned table: partitionId == null materializes as -1 (PK is NOT NULL). CompactedRow row = offsetSchema.encodeOffsetRow( - GroupId.of("g"), ConsumerOffsetSchema.OFFSET_COMMIT_RECORD_TYPE, + GroupId.of("g"), 1L, null, 0, @@ -129,8 +158,8 @@ void testNullPartitionIdEncodesAsMinusOneSentinel() { // Partition id 0 is a valid partition id and must survive the round-trip unchanged. CompactedRow zeroPartition = offsetSchema.encodeOffsetRow( - GroupId.of("g"), ConsumerOffsetSchema.OFFSET_COMMIT_RECORD_TYPE, + GroupId.of("g"), 1L, 0L, 0, @@ -142,8 +171,8 @@ void testNullPartitionIdEncodesAsMinusOneSentinel() { void testEncodeOffsetKeyMatchesRowKeyEncoding() { CompactedRow row = offsetSchema.encodeOffsetRow( - GroupId.of("my-group"), ConsumerOffsetSchema.OFFSET_COMMIT_RECORD_TYPE, + GroupId.of("my-group"), 42L, 7L, 3, @@ -209,8 +238,8 @@ void testGroupBucketKeyMatchesStandardBucketKeyEncoder() { }) { CompactedRow row = offsetSchema.encodeOffsetRow( - GroupId.of(group), ConsumerOffsetSchema.OFFSET_COMMIT_RECORD_TYPE, + GroupId.of(group), -1L, -1L, -1, @@ -237,8 +266,8 @@ void testOffsetCommitPrefixMatchesRecordTypeAndGroupEncoder() { for (String group : new String[] {"a", "my-group", "group-with-unicode", "x"}) { CompactedRow row = offsetSchema.encodeOffsetRow( - GroupId.of(group), ConsumerOffsetSchema.OFFSET_COMMIT_RECORD_TYPE, + GroupId.of(group), -1L, -1L, -1, @@ -284,9 +313,9 @@ void testSharedSchemaEncodesRowsAndKeysAcrossThreads() throws Exception { for (int j = 0; j < iterations; j++) { CompactedRow row = offsetSchema.encodeOffsetRow( - GroupId.of(groupId), ConsumerOffsetSchema .OFFSET_COMMIT_RECORD_TYPE, + GroupId.of(groupId), 42L, 7L, 3, diff --git a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/GroupManagerManagementTest.java b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/GroupManagerManagementTest.java new file mode 100644 index 00000000000..0f87317d669 --- /dev/null +++ b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/GroupManagerManagementTest.java @@ -0,0 +1,114 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to you under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.fluss.server.tablet.consumer.group; + +import org.apache.fluss.metadata.GroupId; +import org.apache.fluss.metadata.TableBucket; +import org.apache.fluss.record.TestingSchemaGetter; +import org.apache.fluss.row.compacted.CompactedRow; +import org.apache.fluss.row.encode.ValueDecoder; +import org.apache.fluss.row.encode.ValueEncoder; +import org.apache.fluss.utils.ByteArraySlice; + +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +import static org.assertj.core.api.Assertions.assertThat; + +/** Tests for consumer-group management helpers. */ +class GroupManagerManagementTest { + + private static final short SCHEMA_ID = 1; + + @Test + void testPopulateGroupIdsDeduplicatesAndSorts() throws Exception { + Set groupIds = new TreeSet<>(); + ConsumerGroupManager.populateGroupIds( + Arrays.asList( + encodedGroupMetadata(GroupId.of("group-b")), + encodedGroupMetadata(GroupId.of("group-a")), + encodedGroupMetadata(GroupId.of("group-b")), + encodedOffset(GroupId.of("group-c"), new TableBucket(1L, 0))), + valueDecoder(), + groupIds); + + assertThat(groupIds).containsExactly("group-a", "group-b"); + } + + @Test + void testEncodeGroupRowKeysUsesMetadataRows() throws Exception { + GroupId groupId = GroupId.of("group-1"); + TableBucket offsetBucket = new TableBucket(1L, 0); + List keys = + ConsumerGroupManager.encodeGroupRowKeys( + groupId, + Arrays.asList( + encodedGroupMetadata(groupId), + encodedOffset(groupId, offsetBucket)), + valueDecoder()); + + assertThat(keys) + .containsExactly( + new ConsumerOffsetSchema().encodeGroupMetadataKey(groupId, -1L, null, -1)); + } + + @Test + void testExistingKeysFiltersPresentValues() { + List keys = Arrays.asList(new byte[] {1}, new byte[] {2}, new byte[] {3}); + List values = + Arrays.asList( + ByteArraySlice.wrap(new byte[] {10}), + null, + ByteArraySlice.wrap(new byte[] {30})); + + assertThat(ConsumerGroupManager.existingKeys(keys, values)) + .containsExactly(keys.get(0), keys.get(2)); + } + + private static ValueDecoder valueDecoder() { + return ConsumerOffsetSchema.createValueDecoder( + new TestingSchemaGetter(SCHEMA_ID, ConsumerOffsetSchema.getTableSchema())); + } + + private static ByteArraySlice encodedGroupMetadata(GroupId groupId) { + return encodedRecord( + groupId, ConsumerOffsetSchema.GROUP_METADATA_RECORD_TYPE, new TableBucket(-1L, -1)); + } + + private static ByteArraySlice encodedOffset(GroupId groupId, TableBucket tableBucket) { + return encodedRecord(groupId, ConsumerOffsetSchema.OFFSET_COMMIT_RECORD_TYPE, tableBucket); + } + + private static ByteArraySlice encodedRecord( + GroupId groupId, int recordType, TableBucket tableBucket) { + CompactedRow row = + new ConsumerOffsetSchema() + .encodeOffsetRow( + recordType, + groupId, + tableBucket.getTableId(), + tableBucket.getPartitionId(), + tableBucket.getBucket(), + new ConsumerOffsetAndMetadata(-1L, "")); + return ByteArraySlice.wrap(ValueEncoder.encodeValue(SCHEMA_ID, row)); + } +} diff --git a/fluss-server/src/test/java/org/apache/fluss/server/utils/ServerRpcMessageUtilsTest.java b/fluss-server/src/test/java/org/apache/fluss/server/utils/ServerRpcMessageUtilsTest.java index b15d985d961..48c1d4f5799 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/utils/ServerRpcMessageUtilsTest.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/utils/ServerRpcMessageUtilsTest.java @@ -36,11 +36,15 @@ import org.apache.fluss.rpc.messages.AlterTableRequest; import org.apache.fluss.rpc.messages.CommitConsumerOffsetsRequest; import org.apache.fluss.rpc.messages.CommitConsumerOffsetsResponse; +import org.apache.fluss.rpc.messages.DeleteConsumerGroupsResponse; +import org.apache.fluss.rpc.messages.DeleteConsumerOffsetsRequest; +import org.apache.fluss.rpc.messages.DeleteConsumerOffsetsResponse; import org.apache.fluss.rpc.messages.DropAclsResponse; import org.apache.fluss.rpc.messages.FetchLogResponse; import org.apache.fluss.rpc.messages.GetConsumerOffsetsRequest; import org.apache.fluss.rpc.messages.GetConsumerOffsetsResponse; import org.apache.fluss.rpc.messages.ListAclsResponse; +import org.apache.fluss.rpc.messages.ListConsumerGroupsResponse; import org.apache.fluss.rpc.messages.LookupResponse; import org.apache.fluss.rpc.messages.PbAclInfo; import org.apache.fluss.rpc.messages.PbBucketMetadata; @@ -48,10 +52,14 @@ import org.apache.fluss.rpc.messages.PbCommitConsumerOffsetsRequestTable; import org.apache.fluss.rpc.messages.PbCommitConsumerOffsetsResponseBucket; import org.apache.fluss.rpc.messages.PbCommitConsumerOffsetsResponseTable; +import org.apache.fluss.rpc.messages.PbDeleteConsumerOffsetsRequestBucket; +import org.apache.fluss.rpc.messages.PbDeleteConsumerOffsetsRequestTable; +import org.apache.fluss.rpc.messages.PbDeletedGroup; import org.apache.fluss.rpc.messages.PbFetchLogRespForBucket; import org.apache.fluss.rpc.messages.PbGetConsumerOffsetsRequestBucket; import org.apache.fluss.rpc.messages.PbGetConsumerOffsetsRequestTable; import org.apache.fluss.rpc.messages.PbGetConsumerOffsetsResponseBucket; +import org.apache.fluss.rpc.messages.PbListedGroup; import org.apache.fluss.rpc.messages.PbPartitionMetadata; import org.apache.fluss.rpc.messages.PbProduceLogReqForBucket; import org.apache.fluss.rpc.messages.PbProduceLogRespForBucket; @@ -81,6 +89,8 @@ import org.apache.fluss.server.metadata.PartitionMetadata; import org.apache.fluss.server.metadata.TableMetadata; import org.apache.fluss.server.tablet.consumer.group.ConsumerOffsetAndMetadata; +import org.apache.fluss.server.tablet.consumer.group.result.DeleteConsumerOffsetsResult; +import org.apache.fluss.server.tablet.consumer.group.result.ListConsumerGroupsResult; import org.apache.fluss.utils.FlussPaths; import org.junit.jupiter.api.Test; @@ -244,6 +254,86 @@ void testBuildGetConsumerOffsetsResponsePreservesOrderAndRequiredMetadata() { assertThat(buckets.get(1).hasMetadata()).isFalse(); } + @Test + void testMakeListConsumerGroupsResponsePreservesOrder() { + ListConsumerGroupsResponse response = + ServerRpcMessageUtils.makeListConsumerGroupsResponse( + ListConsumerGroupsResult.success(Arrays.asList("group-b", "group-a"))); + assertThat(response.getGroupsList()) + .extracting(PbListedGroup::getGroupId) + .containsExactly("group-b", "group-a"); + } + + @Test + void testDecodeDeleteConsumerOffsetsRequestRejectsDuplicateBucket() { + PbDeleteConsumerOffsetsRequestBucket bucket = + new PbDeleteConsumerOffsetsRequestBucket().setBucketId(2); + PbDeleteConsumerOffsetsRequestTable table = + new PbDeleteConsumerOffsetsRequestTable() + .setTableId(3L) + .addAllBuckets(Arrays.asList(bucket, bucket)); + DeleteConsumerOffsetsRequest request = + new DeleteConsumerOffsetsRequest() + .setGroupId("group-1") + .addAllTables(Collections.singletonList(table)); + + assertThatThrownBy(() -> ServerRpcMessageUtils.decodeDeleteConsumerOffsetsRequest(request)) + .isInstanceOf(InvalidRequestException.class) + .hasMessageContaining("Duplicate table bucket"); + } + + @Test + void testMakeDeleteConsumerGroupsResponseReturnsAllResults() { + Map results = new HashMap<>(); + results.put("group-b", Errors.NONE); + results.put("group-a", Errors.CONSUMER_GROUP_ID_NOT_FOUND); + + DeleteConsumerGroupsResponse response = + ServerRpcMessageUtils.makeDeleteConsumerGroupsResponse(results); + List groups = response.getGroupsList(); + assertThat(groups) + .extracting(PbDeletedGroup::getGroupId) + .containsExactlyInAnyOrder("group-a", "group-b"); + assertThat(groups) + .anySatisfy( + group -> { + assertThat(group.getGroupId()).isEqualTo("group-b"); + assertThat(group.hasErrorCode()).isFalse(); + }); + assertThat(groups) + .anySatisfy( + group -> { + assertThat(group.getGroupId()).isEqualTo("group-a"); + assertThat(group.getErrorCode()) + .isEqualTo(Errors.CONSUMER_GROUP_ID_NOT_FOUND.code()); + }); + } + + @Test + void testMakeDeleteConsumerOffsetsResponseReportsEveryRequestedBucket() { + TableBucket successful = new TableBucket(2L, 3); + TableBucket missing = new TableBucket(2L, 1); + TableBucket failed = new TableBucket(2L, 5); + Map bucketErrors = new LinkedHashMap<>(); + bucketErrors.put(successful, Errors.NONE); + bucketErrors.put(missing, Errors.NONE); + bucketErrors.put(failed, Errors.NOT_CONSUMER_GROUP_OWNER); + + DeleteConsumerOffsetsResponse response = + ServerRpcMessageUtils.makeDeleteConsumerOffsetsResponse( + DeleteConsumerOffsetsResult.success(bucketErrors)); + + assertThat(response.getTablesList().get(0).getBucketsList()) + .extracting(bucket -> bucket.getBucketId()) + .containsExactly(3, 1, 5); + assertThat(response.getTablesList().get(0).getBucketsList().get(0).hasErrorCode()) + .isFalse(); + assertThat(response.getTablesList().get(0).getBucketsList().get(1).hasErrorCode()) + .isFalse(); + assertThat(response.getTablesList().get(0).getBucketsList().get(2).getErrorCode()) + .isEqualTo(Errors.NOT_CONSUMER_GROUP_OWNER.code()); + } + @ParameterizedTest @ValueSource(booleans = {false, true}) void testCommitConsumerOffsetsRequestRejectsPartitionSentinelAlias(boolean sentinelFirst) { diff --git a/website/docs/security/authorization.md b/website/docs/security/authorization.md index 0c8aa38a512..d57008ce959 100644 --- a/website/docs/security/authorization.md +++ b/website/docs/security/authorization.md @@ -126,6 +126,9 @@ Below is a summary of the currently public protocols and their relationship with | FIND_CONSUMER_GROUP_OWNER | DESCRIBE | Group | Authorization is checked before initializing the consumer-offset system table. | | COMMIT_CONSUMER_OFFSETS | READ | Group and source Tables | Requires `READ` on the consumer group and `READ` on every source table. Group authorization is checked before owner resolution and source-table authorization. | | GET_CONSUMER_OFFSETS | DESCRIBE | Group and source Tables | Requires `DESCRIBE` on the consumer group and every explicitly requested source table. `allOffsets` requests omit source tables the caller cannot describe. | +| DELETE_CONSUMER_OFFSETS | DROP and READ | Group and live source Tables | Requires `DROP` on the consumer group and `READ` on every live source table. Deleted source tables rely on group-level authorization; missing buckets are successful no-ops. | +| LIST_CONSUMER_GROUPS | DESCRIBE | Cluster | Lists consumer groups owned by the receiving tablet server. This is not a cluster-wide listing. | +| DELETE_CONSUMER_GROUPS | DROP | Group | Deletes consumer-group metadata only; committed offsets are not removed. | | REGISTER_PRODUCER_OFFSETS | WRITE | Table | Requires `WRITE` on all tables in the request. | | GET_PRODUCER_OFFSETS | READ | Table | Offsets for tables without `READ` permission are filtered out. | | DELETE_PRODUCER_OFFSETS | WRITE | Table | Requires `WRITE` on all tables in the producer offset snapshot. | From 226efca2cd34ea87bc27addc5b8740a5a78975fd Mon Sep 17 00:00:00 2001 From: pisceslj Date: Fri, 13 Nov 2026 12:30:11 +0800 Subject: [PATCH 2/7] [rust] Sync generated protobuf code --- fluss-rust/crates/fluss/src/proto/fluss.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fluss-rust/crates/fluss/src/proto/fluss.rs b/fluss-rust/crates/fluss/src/proto/fluss.rs index eb6ab7e38fd..0440a194e8e 100644 --- a/fluss-rust/crates/fluss/src/proto/fluss.rs +++ b/fluss-rust/crates/fluss/src/proto/fluss.rs @@ -679,7 +679,7 @@ pub struct ListConsumerGroupsResponse { #[prost(message, repeated, tag = "1")] pub groups: ::prost::alloc::vec::Vec, } -/// Delete consumer groups request and response. +/// Delete consumer-group metadata. Committed offsets are not removed by this request. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct DeleteConsumerGroupsRequest { /// An empty list is a valid no-op and produces an empty successful response. From 848ec831e767a166ac14a2165713d19ae869f36c Mon Sep 17 00:00:00 2001 From: pisceslj Date: Sun, 15 Nov 2026 22:41:18 +0800 Subject: [PATCH 3/7] [server] Refine consumer group management semantics - Add Group-level visibility to LIST_CONSUMER_GROUPS while preserving Cluster DESCRIBE inheritance. - Make DELETE_CONSUMER_GROUPS remove both group metadata and all committed offsets. - Require Group WRITE and source Table READ for DELETE_CONSUMER_OFFSETS, with group-only cleanup only for confirmed-deleted tables. - Remove redundant result wrappers and the pre-read before offset deletion. - Update RPC Javadocs, proto comments, authorization docs, and generated Rust protobuf code. - Add real RPC integration tests for listing, deletion, authorization, and persisted offsets. --- .../rpc/gateway/TabletServerGateway.java | 19 +- fluss-rpc/src/main/proto/FlussApi.proto | 12 +- fluss-rust/crates/fluss/src/proto/fluss.rs | 12 +- .../metadata/ServerMetadataSnapshot.java | 19 +- .../metadata/TabletServerMetadataCache.java | 29 +- .../fluss/server/tablet/TabletService.java | 110 ++-- .../consumer/group/ConsumerGroupManager.java | 217 ++++---- .../consumer/group/ConsumerOffsetSchema.java | 23 + .../result/DeleteConsumerOffsetsResult.java | 60 --- .../result/ListConsumerGroupsResult.java | 58 --- .../server/utils/ServerRpcMessageUtils.java | 55 +- .../TabletServerMetadataCacheTest.java | 2 + ...merGroupManagementAuthorizationITCase.java | 486 ++++++++++++++++++ .../group/ConsumerGroupManagerTest.java | 29 +- .../group/ConsumerOffsetSchemaTest.java | 11 +- .../group/GroupManagerManagementTest.java | 28 +- .../utils/ServerRpcMessageUtilsTest.java | 7 +- website/docs/security/authorization.md | 6 +- 18 files changed, 807 insertions(+), 376 deletions(-) delete mode 100644 fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/result/DeleteConsumerOffsetsResult.java delete mode 100644 fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/result/ListConsumerGroupsResult.java create mode 100644 fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagementAuthorizationITCase.java diff --git a/fluss-rpc/src/main/java/org/apache/fluss/rpc/gateway/TabletServerGateway.java b/fluss-rpc/src/main/java/org/apache/fluss/rpc/gateway/TabletServerGateway.java index 727c4bcf421..2a68ce374e4 100644 --- a/fluss-rpc/src/main/java/org/apache/fluss/rpc/gateway/TabletServerGateway.java +++ b/fluss-rpc/src/main/java/org/apache/fluss/rpc/gateway/TabletServerGateway.java @@ -212,7 +212,10 @@ CompletableFuture commitConsumerOffsets( CompletableFuture getConsumerOffsets( GetConsumerOffsetsRequest request); - /** Delete committed offsets for selected buckets of a consumer group. */ + /** + * Deletes committed offsets for selected buckets of a consumer group. Requires Group {@code + * WRITE} and Table {@code READ}. + */ @RPC(api = ApiKeys.DELETE_CONSUMER_OFFSETS) CompletableFuture deleteConsumerOffsets( DeleteConsumerOffsetsRequest request); @@ -220,19 +223,21 @@ CompletableFuture deleteConsumerOffsets( /** * Lists consumer groups currently owned by this tablet server. * - *

This is not a cluster-wide listing. Callers that need a cluster-wide view must query every - * tablet server and merge the responses. + *

Cluster {@code DESCRIBE} grants visibility to all locally owned groups; otherwise only + * groups with Group {@code DESCRIBE} are returned. This is not a cluster-wide listing. Callers + * that need a cluster-wide view must query every tablet server and merge the responses. */ @RPC(api = ApiKeys.LIST_CONSUMER_GROUPS) CompletableFuture listConsumerGroups( ListConsumerGroupsRequest request); /** - * Delete consumer-group metadata. Committed offsets are not removed by this request. + * Deletes consumer-group metadata and all committed offsets for each requested group. A later + * offset commit may recreate a deleted group. * - *

This is not a cluster-wide request. Callers must route each group to the tablet server - * that owns the group's consumer-offsets bucket; groups not owned by this server are reported - * with {@code NOT_CONSUMER_GROUP_OWNER}. + *

No source-table permission is required. This is not a cluster-wide request. Callers must + * route each group to the tablet server that owns the group's consumer-offsets bucket; groups + * not owned by this server are reported with {@code NOT_CONSUMER_GROUP_OWNER}. */ @RPC(api = ApiKeys.DELETE_CONSUMER_GROUPS) CompletableFuture deleteConsumerGroups( diff --git a/fluss-rpc/src/main/proto/FlussApi.proto b/fluss-rpc/src/main/proto/FlussApi.proto index 7385117dab4..fad87b02ae3 100644 --- a/fluss-rpc/src/main/proto/FlussApi.proto +++ b/fluss-rpc/src/main/proto/FlussApi.proto @@ -503,7 +503,7 @@ message GetConsumerOffsetsResponse { repeated PbGetConsumerOffsetsResponseTable tables = 1; } -// Delete consumer offsets request and response. +// Delete committed offsets for selected buckets. Requires Group WRITE and Table READ. message DeleteConsumerOffsetsRequest { required string group_id = 1; // An empty list, or tables containing no buckets, is a valid no-op and produces an empty @@ -518,9 +518,10 @@ message DeleteConsumerOffsetsResponse { repeated PbDeleteConsumerOffsetsResponseTable tables = 1; } -// Lists consumer groups currently owned by the tablet server receiving this request. This is not -// a cluster-wide listing; callers that need a cluster-wide view must query every tablet server and -// merge the responses. +// Lists consumer groups currently owned by the tablet server receiving this request. Cluster +// DESCRIBE grants visibility to all locally owned groups; otherwise only groups with Group +// DESCRIBE are returned. This is not a cluster-wide listing; callers that need a cluster-wide +// view must query every tablet server and merge the responses. message ListConsumerGroupsRequest {} // All failures are returned through the RPC ErrorResponse envelope. @@ -528,7 +529,8 @@ message ListConsumerGroupsResponse { repeated PbListedGroup groups = 1; } -// Delete consumer-group metadata. Committed offsets are not removed by this request. +// Deletes consumer-group metadata and all committed offsets. A later offset commit may +// recreate a deleted group. No source-table permission is required. message DeleteConsumerGroupsRequest { // An empty list is a valid no-op and produces an empty successful response. repeated string groups = 1; diff --git a/fluss-rust/crates/fluss/src/proto/fluss.rs b/fluss-rust/crates/fluss/src/proto/fluss.rs index 0440a194e8e..18014339497 100644 --- a/fluss-rust/crates/fluss/src/proto/fluss.rs +++ b/fluss-rust/crates/fluss/src/proto/fluss.rs @@ -650,7 +650,7 @@ pub struct GetConsumerOffsetsResponse { #[prost(message, repeated, tag = "1")] pub tables: ::prost::alloc::vec::Vec, } -/// Delete consumer offsets request and response. +/// Delete committed offsets for selected buckets. Requires Group WRITE and Table READ. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DeleteConsumerOffsetsRequest { #[prost(string, required, tag = "1")] @@ -668,9 +668,10 @@ pub struct DeleteConsumerOffsetsResponse { #[prost(message, repeated, tag = "1")] pub tables: ::prost::alloc::vec::Vec, } -/// Lists consumer groups currently owned by the tablet server receiving this request. This is not -/// a cluster-wide listing; callers that need a cluster-wide view must query every tablet server and -/// merge the responses. +/// Lists consumer groups currently owned by the tablet server receiving this request. Cluster +/// DESCRIBE grants visibility to all locally owned groups; otherwise only groups with Group +/// DESCRIBE are returned. This is not a cluster-wide listing; callers that need a cluster-wide +/// view must query every tablet server and merge the responses. #[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)] pub struct ListConsumerGroupsRequest {} /// All failures are returned through the RPC ErrorResponse envelope. @@ -679,7 +680,8 @@ pub struct ListConsumerGroupsResponse { #[prost(message, repeated, tag = "1")] pub groups: ::prost::alloc::vec::Vec, } -/// Delete consumer-group metadata. Committed offsets are not removed by this request. +/// Deletes consumer-group metadata and all committed offsets. A later offset commit may +/// recreate a deleted group. No source-table permission is required. #[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)] pub struct DeleteConsumerGroupsRequest { /// An empty list is a valid no-op and produces an empty successful response. diff --git a/fluss-server/src/main/java/org/apache/fluss/server/metadata/ServerMetadataSnapshot.java b/fluss-server/src/main/java/org/apache/fluss/server/metadata/ServerMetadataSnapshot.java index 2ead046a951..067511f6b65 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/metadata/ServerMetadataSnapshot.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/metadata/ServerMetadataSnapshot.java @@ -69,6 +69,10 @@ public class ServerMetadataSnapshot { // epoch to prevent an older bucket layout (ALTER bucket.num) from replacing a newer one. private final Map bucketCountEpochByTableId; + // Table IDs that this server has observed as deleted. A missing table ID is unknown state, + // not proof of deletion. + private final Set deletedTableIds; + public ServerMetadataSnapshot( @Nullable ServerInfo coordinatorServer, Map aliveTabletServers, @@ -78,7 +82,8 @@ public ServerMetadataSnapshot( Map> bucketMetadataMapForTables, Map> bucketMetadataMapForPartitions, Map partitionBucketCounts, - Map bucketCountEpochByTableId) { + Map bucketCountEpochByTableId, + Set deletedTableIds) { this.coordinatorServer = coordinatorServer; this.aliveTabletServers = Collections.unmodifiableMap(aliveTabletServers); @@ -97,6 +102,7 @@ public ServerMetadataSnapshot( Collections.unmodifiableMap(bucketMetadataMapForPartitions); this.partitionBucketCounts = Collections.unmodifiableMap(partitionBucketCounts); this.bucketCountEpochByTableId = Collections.unmodifiableMap(bucketCountEpochByTableId); + this.deletedTableIds = Collections.unmodifiableSet(deletedTableIds); } /** Create an empty cluster instance with no nodes and no table-buckets. */ @@ -110,7 +116,8 @@ public static ServerMetadataSnapshot empty() { Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap(), - Collections.emptyMap()); + Collections.emptyMap(), + Collections.emptySet()); } public ServerNode getCoordinatorServer(String listenerName) { @@ -199,6 +206,14 @@ public Map getBucketCountEpochByTableId() { return bucketCountEpochByTableId; } + public boolean isDeletedTable(long tableId) { + return deletedTableIds.contains(tableId); + } + + public Set getDeletedTableIds() { + return deletedTableIds; + } + public Map getPartitionIdByPath() { return partitionIdByPath; } diff --git a/fluss-server/src/main/java/org/apache/fluss/server/metadata/TabletServerMetadataCache.java b/fluss-server/src/main/java/org/apache/fluss/server/metadata/TabletServerMetadataCache.java index 75590192225..2cc5de46df8 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/metadata/TabletServerMetadataCache.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/metadata/TabletServerMetadataCache.java @@ -140,6 +140,11 @@ public Optional getTablePath(long tableId) { return serverMetadataSnapshot.getTablePath(tableId); } + /** Returns whether this server has observed a deletion tombstone for the table ID. */ + public boolean isDeletedTable(long tableId) { + return serverMetadataSnapshot.isDeletedTable(tableId); + } + public Optional getPhysicalTablePath(long partitionId) { return serverMetadataSnapshot.getPhysicalTablePath(partitionId); } @@ -298,7 +303,9 @@ public Set updateClusterMetadata(ClusterMetadata clusterMetadata) { metadataLock, () -> { ServerMetadataSnapshot currentSnapshot = serverMetadataSnapshot; - Set deletedTableIds = new HashSet<>(); + Set knownDeletedTableIds = + new HashSet<>(currentSnapshot.getDeletedTableIds()); + Set newlyDeletedTableIds = new HashSet<>(); // 1. update coordinator server. ServerInfo coordinatorServer = clusterMetadata.getCoordinatorServer(); @@ -330,7 +337,8 @@ public Set updateClusterMetadata(ClusterMetadata clusterMetadata) { Long removedTableId = tableIdByPath.remove(tablePath); if (removedTableId != null) { bucketMetadataMapForTables.remove(removedTableId); - deletedTableIds.add(removedTableId); + newlyDeletedTableIds.add(removedTableId); + knownDeletedTableIds.add(removedTableId); bucketCountEpochByTableId.remove(removedTableId); tableProperties.remove(removedTableId); } @@ -339,7 +347,8 @@ public Set updateClusterMetadata(ClusterMetadata clusterMetadata) { .getTablePath(tableId) .ifPresent(path -> tableIdByPath.remove(path, tableId)); bucketMetadataMapForTables.remove(tableId); - deletedTableIds.add(tableId); + newlyDeletedTableIds.add(tableId); + knownDeletedTableIds.add(tableId); bucketCountEpochByTableId.remove(tableId); tableProperties.remove(tableId); } else { @@ -441,10 +450,11 @@ public Set updateClusterMetadata(ClusterMetadata clusterMetadata) { bucketMetadataMapForTables, bucketMetadataMapForPartitions, partitionBucketCounts, - bucketCountEpochByTableId); + bucketCountEpochByTableId, + knownDeletedTableIds); tablePropertyCache = tableProperties.build(); serverMetadataSnapshot = newSnapshot; - return deletedTableIds; + return newlyDeletedTableIds; }); } @@ -467,7 +477,8 @@ public void clearTableMetadata() { Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap(), - Collections.emptyMap()); + Collections.emptyMap(), + currentSnapshot.getDeletedTableIds()); tablePropertyCache = ServerTablePropertyCache.empty(); serverMetadataSnapshot = newSnapshot; }); @@ -569,7 +580,8 @@ public void updateTableMetadata(TableMetadata tableMetadata) { bucketMetadataMapForTables, bucketMetadataMapForPartitions, currentSnapshot.getPartitionBucketCounts(), - bucketCountEpochByTableId); + bucketCountEpochByTableId, + currentSnapshot.getDeletedTableIds()); tablePropertyCache = tableProperties.build(); serverMetadataSnapshot = newSnapshot; }); @@ -646,7 +658,8 @@ public void updatePartitionMetadata(PartitionMetadata partitionMetadata) { bucketMetadataMapForTables, bucketMetadataMapForPartitions, partitionBucketCounts, - currentSnapshot.getBucketCountEpochByTableId()); + currentSnapshot.getBucketCountEpochByTableId(), + currentSnapshot.getDeletedTableIds()); serverMetadataSnapshot = newSnapshot; }); } diff --git a/fluss-server/src/main/java/org/apache/fluss/server/tablet/TabletService.java b/fluss-server/src/main/java/org/apache/fluss/server/tablet/TabletService.java index 4ac543028fd..68bd0e833f3 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/tablet/TabletService.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/tablet/TabletService.java @@ -135,7 +135,6 @@ import org.apache.fluss.server.tablet.consumer.group.ConsumerOffsetTableConfig; import org.apache.fluss.server.utils.ServerRpcMessageUtils; import org.apache.fluss.server.zk.ZooKeeperClient; -import org.apache.fluss.utils.concurrent.FutureUtils; import javax.annotation.Nullable; @@ -820,37 +819,27 @@ public CompletableFuture findConsumerGroupOwner( FindConsumerGroupOwnerRequest request) { // Copy request/session values before returning: the request buffer is released after this // method and the current session is bound to the RPC worker thread. - try { - final GroupId groupId = GroupId.of(request.getGroupId()); - final String listenerName = currentListenerName(); - if (authorizer != null) { - authorizer.authorize(currentSession(), DESCRIBE, Resource.group(groupId)); - } - - return groupManager - .findOwner(groupId, listenerName) - .thenApply(ServerRpcMessageUtils::makeFindConsumerGroupOwnerResponse); - } catch (ApiException e) { - return FutureUtils.completedExceptionally(e); + final GroupId groupId = GroupId.of(request.getGroupId()); + final String listenerName = currentListenerName(); + if (authorizer != null) { + authorizer.authorize(currentSession(), DESCRIBE, Resource.group(groupId)); } + + return groupManager + .findOwner(groupId, listenerName) + .thenApply(ServerRpcMessageUtils::makeFindConsumerGroupOwnerResponse); } @Override public CompletableFuture commitConsumerOffsets( CommitConsumerOffsetsRequest request) { - final GroupId groupId; - final Replica offsetsReplica; - final Map offsets; - try { - groupId = GroupId.of(request.getGroupId()); - if (authorizer != null) { - authorizer.authorize(currentSession(), READ, Resource.group(groupId)); - } - offsetsReplica = groupManager.validateGroupId(groupId); - offsets = decodeCommitConsumerOffsetsRequest(request); - } catch (ApiException e) { - return FutureUtils.completedExceptionally(e); + final GroupId groupId = GroupId.of(request.getGroupId()); + if (authorizer != null) { + authorizer.authorize(currentSession(), READ, Resource.group(groupId)); } + final Replica offsetsReplica = groupManager.validateGroupId(groupId); + final Map offsets = + decodeCommitConsumerOffsetsRequest(request); if (offsets.isEmpty()) { return CompletableFuture.completedFuture( makeCommitConsumerOffsetsResponse(Collections.emptyMap())); @@ -872,19 +861,12 @@ public CompletableFuture commitConsumerOffsets( @Override public CompletableFuture getConsumerOffsets( GetConsumerOffsetsRequest request) { - final GroupId groupId; - final Replica offsetsReplica; - final List requestedBuckets; - try { - groupId = GroupId.of(request.getGroupId()); - if (authorizer != null) { - authorizer.authorize(currentSession(), DESCRIBE, Resource.group(groupId)); - } - offsetsReplica = groupManager.validateGroupId(groupId); - requestedBuckets = decodeGetConsumerOffsetsRequest(request); - } catch (ApiException e) { - return FutureUtils.completedExceptionally(e); + final GroupId groupId = GroupId.of(request.getGroupId()); + if (authorizer != null) { + authorizer.authorize(currentSession(), DESCRIBE, Resource.group(groupId)); } + final Replica offsetsReplica = groupManager.validateGroupId(groupId); + final List requestedBuckets = decodeGetConsumerOffsetsRequest(request); if (requestedBuckets != null && requestedBuckets.isEmpty()) { return CompletableFuture.completedFuture(new GetConsumerOffsetsResponse()); @@ -932,19 +914,12 @@ private Map filterOffsetsByAuthorizedTab @Override public CompletableFuture deleteConsumerOffsets( DeleteConsumerOffsetsRequest request) { - final GroupId groupId; - final Replica offsetsReplica; - final List requestedBuckets; - try { - groupId = GroupId.of(request.getGroupId()); - if (authorizer != null) { - authorizer.authorize(currentSession(), DROP, Resource.group(groupId)); - } - offsetsReplica = groupManager.validateGroupId(groupId); - requestedBuckets = decodeDeleteConsumerOffsetsRequest(request); - } catch (ApiException e) { - return FutureUtils.completedExceptionally(e); + final GroupId groupId = GroupId.of(request.getGroupId()); + if (authorizer != null) { + authorizer.authorize(currentSession(), WRITE, Resource.group(groupId)); } + final Replica offsetsReplica = groupManager.validateGroupId(groupId); + final List requestedBuckets = decodeDeleteConsumerOffsetsRequest(request); if (requestedBuckets.isEmpty()) { return CompletableFuture.completedFuture(new DeleteConsumerOffsetsResponse()); } @@ -967,12 +942,25 @@ public CompletableFuture deleteConsumerOffsets( @Override public CompletableFuture listConsumerGroups( ListConsumerGroupsRequest request) { - if (authorizer != null) { - authorizer.authorize(currentSession(), OperationType.DESCRIBE, Resource.cluster()); - } + final Session session = currentSession(); return groupManager .handleListConsumerGroups() - .thenApply(ServerRpcMessageUtils::makeListConsumerGroupsResponse); + .thenApply( + groupIds -> { + if (authorizer != null) { + List resources = + groupIds.stream() + .map(Resource::group) + .collect(Collectors.toList()); + groupIds = + authorizer + .filterByAuthorized(session, DESCRIBE, resources) + .stream() + .map(Resource::getName) + .collect(Collectors.toList()); + } + return ServerRpcMessageUtils.makeListConsumerGroupsResponse(groupIds); + }); } @Override @@ -999,14 +987,9 @@ public CompletableFuture deleteConsumerGroups( } } - final Map offsetsReplicasByGroup; - try { - offsetsReplicasByGroup = new HashMap<>(); - for (GroupId groupId : groupIds) { - offsetsReplicasByGroup.put(groupId, groupManager.validateGroupId(groupId)); - } - } catch (ApiException e) { - return FutureUtils.completedExceptionally(e); + final Map offsetsReplicasByGroup = new HashMap<>(); + for (GroupId groupId : groupIds) { + offsetsReplicasByGroup.put(groupId, groupManager.validateGroupId(groupId)); } return groupManager @@ -1245,6 +1228,11 @@ private CompletableFuture submitReplicaStateChange( private void authorizeLiveSourceTable(long tableId) { if (metadataCache.getTablePath(tableId).isPresent()) { authorizeTable(READ, tableId); + } else if (!metadataCache.isDeletedTable(tableId)) { + // A metadata cache miss is unknown state, not proof that the table was deleted. Keep + // Table READ mandatory until the cache observes either the table or its tombstone. + throw new UnknownTableOrBucketException( + "The metadata state of table " + tableId + " is unknown; retry later."); } } diff --git a/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManager.java b/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManager.java index 0435b0c384a..35087600f68 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManager.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManager.java @@ -59,8 +59,6 @@ import org.apache.fluss.server.replica.ReplicaManager; import org.apache.fluss.server.replica.ReplicaManager.HostedReplica; import org.apache.fluss.server.replica.ReplicaManager.OnlineReplica; -import org.apache.fluss.server.tablet.consumer.group.result.DeleteConsumerOffsetsResult; -import org.apache.fluss.server.tablet.consumer.group.result.ListConsumerGroupsResult; import org.apache.fluss.server.zk.ZooKeeperClient; import org.apache.fluss.server.zk.data.TabletServerRegistration; import org.apache.fluss.utils.ByteArraySlice; @@ -82,6 +80,7 @@ import java.util.Set; import java.util.TreeSet; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicReference; @@ -162,7 +161,10 @@ public void onTableMetadataUpdate(List tables) { } } else if (DELETED_TABLE_PATH.equals(info.getTablePath())) { CompletableFuture current = tableInitFuture.get(); - TableInfo cached = getInitializedTable(current); + TableInfo cached = + current == null + ? null + : current.handle((tableInfo, error) -> tableInfo).getNow(null); if (cached != null && cached.getTableId() == info.getTableId()) { tableInitFuture.compareAndSet(current, null); } @@ -173,22 +175,23 @@ public void onTableMetadataUpdate(List tables) { /** Returns the local leader replica or throws a request-level group error. */ public Replica validateGroupId(GroupId groupId) { TableInfo info = getInitializedTable(tableInitFuture.get()); - if (info == null) { - throw new ConsumerGroupOwnerNotAvailableException( - "Table metadata for " - + SystemTables.CONSUMER_OFFSETS - + " is not available yet."); - } return checkOwnership( new TableBucket( info.getTableId(), offsetSchema.bucketFor(groupId, info.getNumBuckets()))); } - @Nullable private static TableInfo getInitializedTable(@Nullable CompletableFuture current) { - return current != null && current.isDone() && !current.isCompletedExceptionally() - ? current.getNow(null) - : null; + TableInfo info = + current == null + ? null + : current.handle((tableInfo, error) -> tableInfo).getNow(null); + if (info == null) { + throw new ConsumerGroupOwnerNotAvailableException( + "Table metadata for " + + SystemTables.CONSUMER_OFFSETS + + " is not available yet."); + } + return info; } /** @@ -393,10 +396,8 @@ private TableInfo createOrResolveTableInfo() { } /** - * Appends on the calling worker and completes the result when the write is acknowledged. - * - *

TODO: Decide whether group metadata rows are written by an explicit create-group operation - * or with the first offset commit. List and delete group management depend on these rows. + * Appends on the calling worker and completes the result when the write is acknowledged. A + * successful batch also upserts the group metadata row used by listing and deletion. */ public CompletableFuture> handleCommitConsumerOffsets( GroupId groupId, @@ -441,54 +442,36 @@ public CompletableFuture> handleCommitConsumerOffsets( } /** - * Deletes selected committed offsets; missing buckets are successful no-ops. Offset reads run - * on the calling thread and tombstone writes are asynchronous. + * Deletes selected committed offsets. Missing offsets are successful no-ops; the KV write path + * skips tombstones whose previous value does not exist. */ - public CompletableFuture handleDeleteConsumerOffsets( + public CompletableFuture> handleDeleteConsumerOffsets( GroupId groupId, Replica offsetsReplica, List requestedBuckets) { - try { - List keys = new ArrayList<>(requestedBuckets.size()); - for (TableBucket tableBucket : requestedBuckets) { - keys.add( - offsetSchema.encodeOffsetKey( - groupId, - tableBucket.getTableId(), - tableBucket.getPartitionId(), - tableBucket.getBucket())); - } - List values = offsetsReplica.lookups(keys); - List keysToDelete = existingKeys(keys, values); - - // Every requested bucket is reported. Missing offsets are successful no-ops, so they - // start as NONE and only buckets whose writes fail are changed. - Map results = new HashMap<>(); - for (TableBucket tableBucket : requestedBuckets) { - results.put(tableBucket, Errors.NONE); - } - - if (keysToDelete.isEmpty()) { - return CompletableFuture.completedFuture( - DeleteConsumerOffsetsResult.success(results)); - } - return deleteKeys(offsetsReplica, keysToDelete) - .handle( - (ignored, error) -> { - if (error == null) { - return DeleteConsumerOffsetsResult.success(results); - } - - Errors writeError = Errors.forException(error); - for (int i = 0; i < requestedBuckets.size(); i++) { - if (values.get(i) != null) { - results.put(requestedBuckets.get(i), writeError); - } - } - return DeleteConsumerOffsetsResult.success(results); - }); - } catch (Exception e) { - return CompletableFuture.completedFuture( - DeleteConsumerOffsetsResult.failure(Errors.forException(e))); + List keys = new ArrayList<>(requestedBuckets.size()); + Map results = new HashMap<>(); + for (TableBucket tableBucket : requestedBuckets) { + keys.add( + offsetSchema.encodeOffsetKey( + groupId, + tableBucket.getTableId(), + tableBucket.getPartitionId(), + tableBucket.getBucket())); + results.put(tableBucket, Errors.NONE); } + + return deleteKeys(offsetsReplica, keys) + .handle( + (ignored, error) -> { + if (error == null) { + return results; + } + + Errors writeError = Errors.forException(error); + for (TableBucket tableBucket : requestedBuckets) { + results.put(tableBucket, writeError); + } + return results; + }); } /** @@ -570,44 +553,37 @@ static void populateSelectedOffsets( } /** - * Lists distinct consumer groups from consumer-offset buckets led by this server. Prefix reads - * run on the calling thread once offsets-table metadata is available. + * Lists distinct consumer groups from consumer-offset buckets led by this server. Listing does + * not initialize the offsets table; prefix reads run on the RPC worker thread. */ - public CompletableFuture handleListConsumerGroups() { - return ensureTableAsync() - .thenApply( - offsetsTableInfo -> { - try { - Set groupIds = new TreeSet<>(); - for (int bucketId = 0; - bucketId < offsetsTableInfo.getNumBuckets(); - bucketId++) { - Replica replica = - localLeaderReplica( - new TableBucket( - offsetsTableInfo.getTableId(), - bucketId)); - if (replica == null) { - continue; - } - populateGroupIds( - replica.prefixLookup( - offsetSchema.encodeGroupMetadataPrefix()), - getValueDecoder(replica.getSchemaGetter()), - groupIds); - } - return ListConsumerGroupsResult.success(new ArrayList<>(groupIds)); - } catch (Exception e) { - LOG.warn("Failed to list consumer groups.", e); - return ListConsumerGroupsResult.failure(Errors.forException(e)); - } - }); + public CompletableFuture> handleListConsumerGroups() { + TableInfo offsetsTableInfo = getInitializedTable(tableInitFuture.get()); + try { + Set groupIds = new TreeSet<>(); + for (int bucketId = 0; bucketId < offsetsTableInfo.getNumBuckets(); bucketId++) { + Replica replica = + localLeaderReplica( + new TableBucket(offsetsTableInfo.getTableId(), bucketId)); + if (replica == null) { + continue; + } + populateGroupIds( + replica.prefixLookup(offsetSchema.encodeGroupMetadataPrefix()), + getValueDecoder(replica.getSchemaGetter()), + groupIds); + } + return CompletableFuture.completedFuture(new ArrayList<>(groupIds)); + } catch (Exception e) { + LOG.warn("Failed to list consumer groups.", e); + throw new CompletionException(e); + } } /** - * Deletes consumer-group metadata rows owned by this server. Callers are expected to route each - * group to its owner. Metadata reads run on the calling thread and tombstone writes are - * asynchronous. + * Deletes consumer-group metadata and all committed offsets owned by this server. Callers are + * expected to route each group to its owner. Reads run on the calling thread and tombstone + * writes are asynchronous. A later offset commit recreates the group; deletion is not fenced + * against concurrent commits. */ public CompletableFuture> handleDeleteConsumerGroups( Map offsetsReplicasByGroup) { @@ -616,8 +592,18 @@ public CompletableFuture> handleDeleteConsumerGroups( GroupId groupId = entry.getKey(); Replica replica = entry.getValue(); try { - List keys = - groupRowKeys(replica, groupId, getValueDecoder(replica.getSchemaGetter())); + ValueDecoder valueDecoder = getValueDecoder(replica.getSchemaGetter()); + List metadataKeys = + encodeGroupRowKeys( + groupId, + replica.prefixLookup( + offsetSchema.encodeGroupMetadataPrefix(groupId)), + valueDecoder); + List offsetKeys = offsetRowKeys(replica, groupId, valueDecoder); + List keys = new ArrayList<>(metadataKeys.size() + offsetKeys.size()); + keys.addAll(metadataKeys); + keys.addAll(offsetKeys); + if (keys.isEmpty()) { deletions.add( CompletableFuture.completedFuture(Errors.CONSUMER_GROUP_ID_NOT_FOUND)); @@ -646,11 +632,11 @@ public CompletableFuture> handleDeleteConsumerGroups( }); } - private List groupRowKeys(Replica replica, GroupId groupId, ValueDecoder valueDecoder) + private List offsetRowKeys(Replica replica, GroupId groupId, ValueDecoder valueDecoder) throws Exception { - return encodeGroupRowKeys( + return encodeOffsetRowKeys( groupId, - replica.prefixLookup(offsetSchema.encodeGroupMetadataPrefix(groupId)), + replica.prefixLookup(offsetSchema.encodeOffsetCommitPrefix(groupId)), valueDecoder); } @@ -689,14 +675,25 @@ static List encodeGroupRowKeys( } @VisibleForTesting - static List existingKeys(List keys, List values) { - List existing = new ArrayList<>(); - for (int i = 0; i < keys.size(); i++) { - if (values.get(i) != null) { - existing.add(keys.get(i)); + static List encodeOffsetRowKeys( + GroupId groupId, List values, ValueDecoder valueDecoder) + throws Exception { + ConsumerOffsetSchema schema = new ConsumerOffsetSchema(); + List keys = new ArrayList<>(); + for (ByteArraySlice value : values) { + InternalRow row = valueDecoder.decodeValue(value.toByteArray()).row; + if (row.getInt(0) != OFFSET_COMMIT_RECORD_TYPE) { + continue; } + TableBucket tableBucket = ConsumerOffsetSchema.toTableBucket(row); + keys.add( + schema.encodeOffsetKey( + groupId, + tableBucket.getTableId(), + tableBucket.getPartitionId(), + tableBucket.getBucket())); } - return existing; + return keys; } private CompletableFuture deleteKeys(Replica replica, List keys) { @@ -779,6 +776,12 @@ private KvRecordBatch buildUpsertBatch( Integer.MAX_VALUE, new UnmanagedPagedOutputView(OFFSET_COMMIT_PAGE_SIZE), KvFormat.COMPACTED); + + // Keep a metadata row for every group that has committed offsets. Listing and deleting + // groups depend on this row; upserting it on each commit is idempotent. + CompactedRow metadataRow = offsetSchema.encodeGroupMetadataRow(groupId); + builder.append(offsetSchema.encodeGroupMetadataKey(groupId), metadataRow); + for (Map.Entry entry : offsets.entrySet()) { TableBucket tableBucket = entry.getKey(); CompactedRow row = diff --git a/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchema.java b/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchema.java index 5c32b759815..f3bdc238c4c 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchema.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchema.java @@ -61,6 +61,12 @@ public final class ConsumerOffsetSchema { /** Sentinel used for non-partitioned tables because primary-key columns cannot be null. */ public static final long NON_PARTITIONED_PARTITION_ID = -1L; + /** Sentinel table ID used by group metadata rows. */ + private static final long GROUP_METADATA_TABLE_ID = -1L; + + /** Sentinel bucket ID used by group metadata rows. */ + private static final int GROUP_METADATA_BUCKET_ID = -1; + private static final List PRIMARY_KEYS = Collections.unmodifiableList( Arrays.asList( @@ -190,6 +196,12 @@ public byte[] encodeGroupMetadataPrefix(GroupId groupId) { } /** Encodes the complete primary key of a group metadata row. */ + public byte[] encodeGroupMetadataKey(GroupId groupId) { + return encodeGroupMetadataKey( + groupId, GROUP_METADATA_TABLE_ID, null, GROUP_METADATA_BUCKET_ID); + } + + /** Encodes the complete primary key of a group metadata row with explicit source columns. */ public byte[] encodeGroupMetadataKey( GroupId groupId, long tableId, Long partitionId, int bucketId) { return primaryKeyEncoder @@ -203,6 +215,17 @@ public byte[] encodeGroupMetadataKey( bucketId)); } + /** Encodes a group metadata row. */ + public CompactedRow encodeGroupMetadataRow(GroupId groupId) { + return encodeOffsetRow( + GROUP_METADATA_RECORD_TYPE, + groupId, + GROUP_METADATA_TABLE_ID, + null, + GROUP_METADATA_BUCKET_ID, + new ConsumerOffsetAndMetadata(-1L, null)); + } + /** Encodes the complete primary key of an already materialized offset row. */ byte[] encodeOffsetKey(InternalRow row) { return primaryKeyEncoder.get().encodeKey(row); diff --git a/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/result/DeleteConsumerOffsetsResult.java b/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/result/DeleteConsumerOffsetsResult.java deleted file mode 100644 index f033fea25d9..00000000000 --- a/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/result/DeleteConsumerOffsetsResult.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to you under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.fluss.server.tablet.consumer.group.result; - -import org.apache.fluss.annotation.Internal; -import org.apache.fluss.metadata.TableBucket; -import org.apache.fluss.rpc.protocol.Errors; - -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; - -import static org.apache.fluss.utils.Preconditions.checkNotNull; - -/** Result of deleting committed offsets for selected table buckets. */ -@Internal -public final class DeleteConsumerOffsetsResult { - - private final Errors error; - private final Map bucketErrors; - - private DeleteConsumerOffsetsResult(Errors error, Map bucketErrors) { - this.error = checkNotNull(error, "error must not be null"); - this.bucketErrors = - Collections.unmodifiableMap( - new LinkedHashMap<>( - checkNotNull(bucketErrors, "bucketErrors must not be null"))); - } - - public static DeleteConsumerOffsetsResult success(Map bucketErrors) { - return new DeleteConsumerOffsetsResult(Errors.NONE, bucketErrors); - } - - public static DeleteConsumerOffsetsResult failure(Errors error) { - return new DeleteConsumerOffsetsResult(error, Collections.emptyMap()); - } - - public Errors getError() { - return error; - } - - public Map getBucketErrors() { - return bucketErrors; - } -} diff --git a/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/result/ListConsumerGroupsResult.java b/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/result/ListConsumerGroupsResult.java deleted file mode 100644 index 0456b36e5e7..00000000000 --- a/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/result/ListConsumerGroupsResult.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to you under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.fluss.server.tablet.consumer.group.result; - -import org.apache.fluss.annotation.Internal; -import org.apache.fluss.rpc.protocol.Errors; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import static org.apache.fluss.utils.Preconditions.checkNotNull; - -/** Result of listing consumer groups stored on a tablet server. */ -@Internal -public final class ListConsumerGroupsResult { - - private final Errors error; - private final List groupIds; - - private ListConsumerGroupsResult(Errors error, List groupIds) { - this.error = checkNotNull(error, "error must not be null"); - this.groupIds = - Collections.unmodifiableList( - new ArrayList<>(checkNotNull(groupIds, "groupIds must not be null"))); - } - - public static ListConsumerGroupsResult success(List groupIds) { - return new ListConsumerGroupsResult(Errors.NONE, groupIds); - } - - public static ListConsumerGroupsResult failure(Errors error) { - return new ListConsumerGroupsResult(error, Collections.emptyList()); - } - - public Errors getError() { - return error; - } - - public List getGroupIds() { - return groupIds; - } -} diff --git a/fluss-server/src/main/java/org/apache/fluss/server/utils/ServerRpcMessageUtils.java b/fluss-server/src/main/java/org/apache/fluss/server/utils/ServerRpcMessageUtils.java index f8ad531b18e..9df85dabe94 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/utils/ServerRpcMessageUtils.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/utils/ServerRpcMessageUtils.java @@ -230,8 +230,6 @@ import org.apache.fluss.server.metadata.ServerInfo; import org.apache.fluss.server.metadata.TableMetadata; import org.apache.fluss.server.tablet.consumer.group.ConsumerOffsetAndMetadata; -import org.apache.fluss.server.tablet.consumer.group.result.DeleteConsumerOffsetsResult; -import org.apache.fluss.server.tablet.consumer.group.result.ListConsumerGroupsResult; import org.apache.fluss.server.zk.ZooKeeperClient.TableBucketAndManifest; import org.apache.fluss.server.zk.data.BucketSnapshot; import org.apache.fluss.server.zk.data.LeaderAndIsr; @@ -1535,15 +1533,10 @@ public static List decodeDeleteConsumerOffsetsRequest( } /** Builds the list-groups response. */ - public static ListConsumerGroupsResponse makeListConsumerGroupsResponse( - ListConsumerGroupsResult result) { - if (result.getError() != Errors.NONE) { - throw result.getError().exception(); - } - + public static ListConsumerGroupsResponse makeListConsumerGroupsResponse(List groupIds) { ListConsumerGroupsResponse response = new ListConsumerGroupsResponse(); List groups = new ArrayList<>(); - for (String groupId : result.getGroupIds()) { + for (String groupId : groupIds) { groups.add(new PbListedGroup().setGroupId(groupId)); } response.addAllGroups(groups); @@ -1572,32 +1565,26 @@ public static DeleteConsumerGroupsResponse makeDeleteConsumerGroupsResponse( /** Builds the delete-offsets response. */ public static DeleteConsumerOffsetsResponse makeDeleteConsumerOffsetsResponse( - DeleteConsumerOffsetsResult result) { - if (result.getError() != Errors.NONE) { - throw result.getError().exception(); - } - + Map bucketErrors) { Map> bucketsByTable = new HashMap<>(); - result.getBucketErrors() - .forEach( - (tableBucket, error) -> { - PbDeleteConsumerOffsetsResponseBucket bucket = - new PbDeleteConsumerOffsetsResponseBucket() - .setBucketId(tableBucket.getBucket()); - if (tableBucket.getPartitionId() != null) { - bucket.setPartitionId(tableBucket.getPartitionId()); - } - if (error != Errors.NONE) { - bucket.setErrorCode(error.code()); - if (error.message() != null) { - bucket.setErrorMessage(error.message()); - } - } - bucketsByTable - .computeIfAbsent( - tableBucket.getTableId(), ignored -> new ArrayList<>()) - .add(bucket); - }); + bucketErrors.forEach( + (tableBucket, error) -> { + PbDeleteConsumerOffsetsResponseBucket bucket = + new PbDeleteConsumerOffsetsResponseBucket() + .setBucketId(tableBucket.getBucket()); + if (tableBucket.getPartitionId() != null) { + bucket.setPartitionId(tableBucket.getPartitionId()); + } + if (error != Errors.NONE) { + bucket.setErrorCode(error.code()); + if (error.message() != null) { + bucket.setErrorMessage(error.message()); + } + } + bucketsByTable + .computeIfAbsent(tableBucket.getTableId(), ignored -> new ArrayList<>()) + .add(bucket); + }); DeleteConsumerOffsetsResponse response = new DeleteConsumerOffsetsResponse(); bucketsByTable.forEach( diff --git a/fluss-server/src/test/java/org/apache/fluss/server/metadata/TabletServerMetadataCacheTest.java b/fluss-server/src/test/java/org/apache/fluss/server/metadata/TabletServerMetadataCacheTest.java index 34440759754..6b94795b95d 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/metadata/TabletServerMetadataCacheTest.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/metadata/TabletServerMetadataCacheTest.java @@ -261,6 +261,8 @@ void testUpdateClusterMetadataRequest() { Collections.emptyList())); assertThat(deletedTableIds).containsExactly(DATA1_TABLE_ID); assertThat(serverMetadataCache.getTablePath(DATA1_TABLE_ID)).isEmpty(); + assertThat(serverMetadataCache.isDeletedTable(DATA1_TABLE_ID)).isTrue(); + assertThat(serverMetadataCache.isDeletedTable(partitionTableId)).isFalse(); // test delete one partition. deletedTableIds = diff --git a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagementAuthorizationITCase.java b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagementAuthorizationITCase.java new file mode 100644 index 00000000000..7ec02eb0cef --- /dev/null +++ b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagementAuthorizationITCase.java @@ -0,0 +1,486 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF Software Foundation licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.fluss.server.tablet.consumer.group; + +import org.apache.fluss.cluster.ServerNode; +import org.apache.fluss.config.ConfigOptions; +import org.apache.fluss.config.Configuration; +import org.apache.fluss.exception.AuthorizationException; +import org.apache.fluss.exception.UnknownTableOrBucketException; +import org.apache.fluss.metadata.Schema; +import org.apache.fluss.metadata.TableBucket; +import org.apache.fluss.metadata.TableDescriptor; +import org.apache.fluss.metadata.TableInfo; +import org.apache.fluss.metadata.TablePath; +import org.apache.fluss.rpc.GatewayClientProxy; +import org.apache.fluss.rpc.gateway.TabletServerGateway; +import org.apache.fluss.rpc.messages.CommitConsumerOffsetsRequest; +import org.apache.fluss.rpc.messages.CommitConsumerOffsetsResponse; +import org.apache.fluss.rpc.messages.CreateAclsRequest; +import org.apache.fluss.rpc.messages.DeleteConsumerGroupsRequest; +import org.apache.fluss.rpc.messages.DeleteConsumerOffsetsRequest; +import org.apache.fluss.rpc.messages.DeleteConsumerOffsetsResponse; +import org.apache.fluss.rpc.messages.FindConsumerGroupOwnerRequest; +import org.apache.fluss.rpc.messages.GetConsumerOffsetsRequest; +import org.apache.fluss.rpc.messages.GetConsumerOffsetsResponse; +import org.apache.fluss.rpc.messages.ListConsumerGroupsRequest; +import org.apache.fluss.rpc.messages.ListConsumerGroupsResponse; +import org.apache.fluss.rpc.messages.PbCommitConsumerOffsetsResponseBucket; +import org.apache.fluss.rpc.messages.PbCommitConsumerOffsetsResponseTable; +import org.apache.fluss.rpc.messages.PbGetConsumerOffsetsResponseBucket; +import org.apache.fluss.rpc.messages.PbGetConsumerOffsetsResponseTable; +import org.apache.fluss.rpc.messages.PbListedGroup; +import org.apache.fluss.rpc.metrics.TestingClientMetricGroup; +import org.apache.fluss.rpc.netty.client.NettyClient; +import org.apache.fluss.security.acl.AccessControlEntry; +import org.apache.fluss.security.acl.AclBinding; +import org.apache.fluss.security.acl.FlussPrincipal; +import org.apache.fluss.security.acl.OperationType; +import org.apache.fluss.security.acl.PermissionType; +import org.apache.fluss.security.acl.Resource; +import org.apache.fluss.server.metadata.ClusterMetadata; +import org.apache.fluss.server.metadata.SystemTables; +import org.apache.fluss.server.metadata.TableMetadata; +import org.apache.fluss.server.metadata.TabletServerMetadataCache; +import org.apache.fluss.server.testutils.FlussClusterExtension; +import org.apache.fluss.server.zk.data.TableRegistration; +import org.apache.fluss.types.DataTypes; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.apache.fluss.rpc.util.CommonRpcMessageUtils.toPbAclInfos; +import static org.apache.fluss.security.acl.OperationType.DESCRIBE; +import static org.apache.fluss.security.acl.OperationType.DROP; +import static org.apache.fluss.security.acl.OperationType.READ; +import static org.apache.fluss.security.acl.OperationType.WRITE; +import static org.apache.fluss.server.metadata.TableMetadata.DELETED_TABLE_ID; +import static org.apache.fluss.server.testutils.RpcMessageTestUtils.createTable; +import static org.apache.fluss.server.testutils.RpcMessageTestUtils.dropTable; +import static org.apache.fluss.testutils.common.CommonTestUtils.retry; +import static org.apache.fluss.testutils.common.CommonTestUtils.waitValue; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** Integration tests for consumer-group management authorization. */ +class ConsumerGroupManagementAuthorizationITCase { + + private static final String FIRST_GROUP = "first-group"; + private static final String SECOND_GROUP = "second-group"; + private static final Duration WAIT_TIMEOUT = Duration.ofMinutes(1); + private static final TablePath SOURCE_TABLE = TablePath.of("group_auth_db", "source"); + private static final TablePath SECOND_SOURCE_TABLE = + TablePath.of("group_auth_db", "second_source"); + + private final FlussClusterExtension cluster = + FlussClusterExtension.builder() + .setCoordinatorServerListeners("FLUSS://localhost:0, CLIENT://localhost:0") + .setTabletServerListeners("FLUSS://localhost:0, CLIENT://localhost:0") + .setClusterConf( + new Configuration() + .set(ConfigOptions.AUTHORIZER_ENABLED, true) + .set(ConfigOptions.OFFSETS_TABLE_NUM_BUCKETS, 1) + .set(ConfigOptions.OFFSETS_TABLE_REPLICATION_FACTOR, 1)) + .build(); + + private NettyClient client; + private TabletServerGateway clientGateway; + private TabletServerGateway internalGateway; + private ServerNode clientNode; + private TableBucket sourceBucket; + private TableBucket secondSourceBucket; + + @BeforeEach + void setUp() throws Exception { + cluster.start(); + + TableDescriptor sourceDescriptor = + TableDescriptor.builder() + .schema(Schema.newBuilder().column("id", DataTypes.INT()).build()) + .distributedBy(1) + .build(); + long tableId = createTable(cluster, SOURCE_TABLE, sourceDescriptor); + sourceBucket = new TableBucket(tableId, 0); + cluster.waitUntilAllReplicaReady(sourceBucket); + + TableDescriptor secondSourceDescriptor = + TableDescriptor.builder() + .schema(Schema.newBuilder().column("id", DataTypes.INT()).build()) + .distributedBy(2) + .build(); + long secondTableId = createTable(cluster, SECOND_SOURCE_TABLE, secondSourceDescriptor); + secondSourceBucket = new TableBucket(secondTableId, 0); + cluster.waitUntilAllReplicaReady(secondSourceBucket); + cluster.waitUntilAllReplicaReady(new TableBucket(secondTableId, 1)); + + clientNode = cluster.getTabletServerNodes("CLIENT").get(0); + client = new NettyClient(new Configuration(), TestingClientMetricGroup.newInstance()); + clientGateway = + GatewayClientProxy.createGatewayProxy( + () -> clientNode, client, TabletServerGateway.class); + internalGateway = cluster.newTabletServerClientForNode(clientNode.id()); + + retry( + WAIT_TIMEOUT, + () -> + assertThat( + internalGateway.findConsumerGroupOwner( + new FindConsumerGroupOwnerRequest() + .setGroupId(FIRST_GROUP))) + .succeedsWithin(WAIT_TIMEOUT) + .extracting(response -> response.getOwner().getNodeId()) + .isEqualTo(clientNode.id())); + + TableRegistration offsetsTable = + waitValue( + () -> cluster.getZooKeeperClient().getTable(SystemTables.CONSUMER_OFFSETS), + WAIT_TIMEOUT, + "Consumer offsets table was not created"); + cluster.waitUntilAllReplicaReady(new TableBucket(offsetsTable.tableId, 0)); + } + + @AfterEach + void tearDown() throws Exception { + try { + if (client != null) { + client.close(); + } + } finally { + cluster.close(); + } + } + + @Test + void testListConsumerGroupsUsesGroupLevelVisibility() throws Exception { + commitOffset(FIRST_GROUP, 10L); + commitOffset(SECOND_GROUP, 20L); + + assertThat(listGroups()).isEmpty(); + + grant(DESCRIBE, Resource.group(FIRST_GROUP)); + assertThat(listGroups()).containsExactly(FIRST_GROUP); + + grant(DESCRIBE, Resource.cluster()); + assertThat(listGroups()).containsExactlyInAnyOrder(FIRST_GROUP, SECOND_GROUP); + } + + @Test + void testDeleteConsumerGroupsRemovesMetadataAndOffsets() throws Exception { + commitOffset(FIRST_GROUP, 10L); + grant(DROP, Resource.group(FIRST_GROUP)); + grant(DESCRIBE, Resource.group(FIRST_GROUP)); + grant(DESCRIBE, Resource.table(SOURCE_TABLE)); + + clientGateway + .deleteConsumerGroups( + new DeleteConsumerGroupsRequest() + .addAllGroups(Collections.singletonList(FIRST_GROUP))) + .get(); + + assertThat(listGroups()).isEmpty(); + assertThat(getAllOffsets(FIRST_GROUP)).isEmpty(); + + // Deletion is not fenced; a later commit recreates the group. + commitOffset(FIRST_GROUP, 20L); + assertThat(listGroups()).containsExactly(FIRST_GROUP); + assertThat(getAllOffsets(FIRST_GROUP)).containsExactly(20L); + } + + @Test + void testDeleteConsumerOffsetsRequiresGroupWriteAndTableRead() throws Exception { + commitOffset(FIRST_GROUP, 10L); + + grant(READ, Resource.group(FIRST_GROUP)); + assertThatThrownBy(() -> clientGateway.deleteConsumerOffsets(deleteRequest()).get()) + .rootCause() + .isInstanceOf(AuthorizationException.class) + .hasMessageContaining("WRITE"); + + grant(WRITE, Resource.group(FIRST_GROUP)); + assertThatThrownBy(() -> clientGateway.deleteConsumerOffsets(deleteRequest()).get()) + .rootCause() + .isInstanceOf(AuthorizationException.class) + .hasMessageContaining("READ"); + + grant(READ, Resource.table(SOURCE_TABLE)); + assertThat(getAllOffsets(FIRST_GROUP)).containsExactly(10L); + clientGateway.deleteConsumerOffsets(deleteRequest()).get(); + assertThat(getAllOffsets(FIRST_GROUP)).isEmpty(); + } + + @Test + void testGroupDropDoesNotReplaceGroupWriteForOffsetDeletion() throws Exception { + commitOffset(FIRST_GROUP, 10L); + grant(DROP, Resource.group(FIRST_GROUP)); + + assertThatThrownBy(() -> clientGateway.deleteConsumerOffsets(deleteRequest()).get()) + .rootCause() + .isInstanceOf(AuthorizationException.class) + .hasMessageContaining("WRITE"); + } + + @Test + void testGroupWriteWithoutDropDeletesOffsetsButNotGroup() throws Exception { + commitOffset(FIRST_GROUP, 10L); + grant(WRITE, Resource.group(FIRST_GROUP)); + grant(READ, Resource.table(SOURCE_TABLE)); + + clientGateway.deleteConsumerOffsets(deleteRequest()).get(); + + grant(DESCRIBE, Resource.group(FIRST_GROUP)); + grant(DESCRIBE, Resource.table(SOURCE_TABLE)); + assertThat(getAllOffsets(FIRST_GROUP)).isEmpty(); + + assertThatThrownBy( + () -> + clientGateway + .deleteConsumerGroups( + new DeleteConsumerGroupsRequest() + .addAllGroups( + Collections.singletonList( + FIRST_GROUP))) + .get()) + .rootCause() + .isInstanceOf(AuthorizationException.class) + .hasMessageContaining("DROP"); + } + + @Test + void testDeleteConsumerOffsetsTreatsMissingOffsetsAsNoOp() throws Exception { + grant(WRITE, Resource.group(FIRST_GROUP)); + grant(READ, Resource.table(SOURCE_TABLE)); + + DeleteConsumerOffsetsResponse response = + clientGateway.deleteConsumerOffsets(deleteRequest()).get(); + + assertThat(response.getTablesList()).hasSize(1); + assertThat(response.getTableAt(0).getBucketsList()).hasSize(1); + assertThat(response.getTableAt(0).getBucketAt(0).hasErrorCode()).isFalse(); + } + + @Test + void testDeletedSourceTableRequiresOnlyGroupWrite() throws Exception { + commitOffset(FIRST_GROUP, 10L); + grant(WRITE, Resource.group(FIRST_GROUP)); + + long tableId = sourceBucket.getTableId(); + dropTable(cluster, SOURCE_TABLE); + retry( + WAIT_TIMEOUT, + () -> assertThat(cluster.getZooKeeperClient().tableExist(SOURCE_TABLE)).isFalse()); + + TableDescriptor descriptor = + TableDescriptor.builder() + .schema(Schema.newBuilder().column("id", DataTypes.INT()).build()) + .distributedBy(1) + .build(); + TableInfo deletedTableInfo = + TableInfo.of(SOURCE_TABLE, DELETED_TABLE_ID, 0, descriptor, null, -1L, -1L); + ClusterMetadata clusterMetadata = + new ClusterMetadata( + null, + Collections.emptySet(), + Collections.singletonList( + new TableMetadata(deletedTableInfo, Collections.emptyList())), + Collections.emptyList()); + cluster.getTabletServerById(clientNode.id()) + .getMetadataCache() + .updateClusterMetadata(clusterMetadata); + + clientGateway.deleteConsumerOffsets(deleteRequest(tableId)).get(); + } + + @Test + void testLiveSourceTableMissingFromMetadataCacheFailsGroupOnlyCleanup() throws Exception { + commitOffset(FIRST_GROUP, 10L); + grant(WRITE, Resource.group(FIRST_GROUP)); + + TabletServerMetadataCache metadataCache = + cluster.getTabletServerById(clientNode.id()).getMetadataCache(); + TableMetadata firstTableMetadata = metadataCache.getTableMetadata(SOURCE_TABLE).get(); + metadataCache.clearTableMetadata(); + metadataCache.updateTableMetadata(firstTableMetadata); + + assertThat(cluster.getZooKeeperClient().tableExist(SECOND_SOURCE_TABLE)).isTrue(); + assertThatThrownBy( + () -> + clientGateway + .deleteConsumerOffsets(deleteRequest(secondSourceBucket)) + .get()) + .rootCause() + .isInstanceOf(UnknownTableOrBucketException.class) + .hasMessageContaining("unknown"); + } + + @Test + void testDeleteConsumerGroupsRemovesOffsetsAcrossTablesAndBuckets() throws Exception { + commitOffset(FIRST_GROUP, sourceBucket, 10L); + commitOffset(FIRST_GROUP, secondSourceBucket, 20L); + commitOffset(FIRST_GROUP, new TableBucket(secondSourceBucket.getTableId(), 1), 30L); + + grant(DROP, Resource.group(FIRST_GROUP)); + grant(DESCRIBE, Resource.group(FIRST_GROUP)); + grant(DESCRIBE, Resource.table(SOURCE_TABLE)); + grant(DESCRIBE, Resource.table(SECOND_SOURCE_TABLE)); + + Map offsets = getAllOffsetsByBucket(FIRST_GROUP); + assertThat(offsets).hasSize(3); + assertThat(offsets.keySet()) + .containsExactlyInAnyOrder( + sourceBucket, + secondSourceBucket, + new TableBucket(secondSourceBucket.getTableId(), 1)); + + clientGateway + .deleteConsumerGroups( + new DeleteConsumerGroupsRequest() + .addAllGroups(Collections.singletonList(FIRST_GROUP))) + .get(); + + assertThat(listGroups()).isEmpty(); + assertThat(getAllOffsetsByBucket(FIRST_GROUP)).isEmpty(); + } + + @Test + void testUnknownSourceTableStateFailsRetriably() throws Exception { + commitOffset(FIRST_GROUP, 10L); + grant(WRITE, Resource.group(FIRST_GROUP)); + + assertThatThrownBy( + () -> + clientGateway + .deleteConsumerOffsets(deleteRequest(Long.MAX_VALUE)) + .get()) + .rootCause() + .isInstanceOf(UnknownTableOrBucketException.class) + .hasMessageContaining("unknown"); + } + + private void commitOffset(String groupId, long offset) throws Exception { + commitOffset(groupId, sourceBucket, offset); + } + + private void commitOffset(String groupId, TableBucket sourceBucket, long offset) + throws Exception { + CommitConsumerOffsetsRequest request = + new CommitConsumerOffsetsRequest().setGroupId(groupId); + request.addTable() + .setTableId(sourceBucket.getTableId()) + .addBucket() + .setBucketId(sourceBucket.getBucket()) + .setOffset(offset); + + CommitConsumerOffsetsResponse response = + internalGateway.commitConsumerOffsets(request).get(); + assertThat(response.getTablesList()).hasSize(1); + PbCommitConsumerOffsetsResponseTable table = response.getTableAt(0); + assertThat(table.getBucketsList()).hasSize(1); + PbCommitConsumerOffsetsResponseBucket bucket = table.getBucketAt(0); + assertThat(bucket.hasErrorCode()).isFalse(); + } + + private List listGroups() throws Exception { + ListConsumerGroupsResponse response = + clientGateway.listConsumerGroups(new ListConsumerGroupsRequest()).get(); + return response.getGroupsList().stream() + .map(PbListedGroup::getGroupId) + .collect(Collectors.toList()); + } + + private List getAllOffsets(String groupId) throws Exception { + return new ArrayList<>( + getAllOffsetsByBucket(groupId).values().stream() + .map(offset -> offset == null ? null : offset.getOffset()) + .collect(Collectors.toList())); + } + + private Map getAllOffsetsByBucket(String groupId) + throws Exception { + GetConsumerOffsetsResponse response = + clientGateway + .getConsumerOffsets( + new GetConsumerOffsetsRequest() + .setGroupId(groupId) + .setAllOffsets(true)) + .get(); + Map offsets = new LinkedHashMap<>(); + for (PbGetConsumerOffsetsResponseTable table : response.getTablesList()) { + for (PbGetConsumerOffsetsResponseBucket bucket : table.getBucketsList()) { + TableBucket tableBucket = + new TableBucket( + table.getTableId(), + bucket.hasPartitionId() ? bucket.getPartitionId() : null, + bucket.getBucketId()); + offsets.put( + tableBucket, + bucket.hasOffset() + ? new ConsumerOffsetAndMetadata( + bucket.getOffset(), + bucket.hasMetadata() ? bucket.getMetadata() : null) + : null); + } + } + return offsets; + } + + private DeleteConsumerOffsetsRequest deleteRequest() { + return deleteRequest(sourceBucket.getTableId()); + } + + private DeleteConsumerOffsetsRequest deleteRequest(long tableId) { + return deleteRequest(new TableBucket(tableId, sourceBucket.getBucket())); + } + + private DeleteConsumerOffsetsRequest deleteRequest(TableBucket tableBucket) { + DeleteConsumerOffsetsRequest request = + new DeleteConsumerOffsetsRequest().setGroupId(FIRST_GROUP); + request.addTable() + .setTableId(tableBucket.getTableId()) + .addBucket() + .setBucketId(tableBucket.getBucket()); + if (tableBucket.getPartitionId() != null) { + request.getTableAt(0).getBucketAt(0).setPartitionId(tableBucket.getPartitionId()); + } + return request; + } + + private void grant(OperationType operation, Resource resource) throws Exception { + List bindings = + Collections.singletonList( + new AclBinding( + resource, + new AccessControlEntry( + FlussPrincipal.ANONYMOUS, + "*", + operation, + PermissionType.ALLOW))); + cluster.newCoordinatorClient() + .createAcls(new CreateAclsRequest().addAllAcls(toPbAclInfos(bindings))) + .get(); + cluster.waitUntilAuthenticationSync(bindings, true); + } +} diff --git a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagerTest.java b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagerTest.java index 927dd395c87..1ada4f238a3 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagerTest.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagerTest.java @@ -17,6 +17,7 @@ package org.apache.fluss.server.tablet.consumer.group; +import org.apache.fluss.exception.ConsumerGroupOwnerNotAvailableException; import org.apache.fluss.exception.InvalidConsumerGroupIdException; import org.apache.fluss.metadata.GroupId; import org.apache.fluss.metadata.PhysicalTablePath; @@ -53,6 +54,7 @@ import java.util.Collections; import java.util.Map; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicInteger; import static org.apache.fluss.server.coordinator.CoordinatorContext.INITIAL_COORDINATOR_EPOCH; import static org.apache.fluss.server.zk.data.LeaderAndIsr.INITIAL_LEADER_EPOCH; @@ -69,6 +71,7 @@ class ConsumerGroupManagerTest extends ReplicaTestBase { private static final TableBucket SOURCE_BUCKET = new TableBucket(1L, 0); private LakeCatalogDynamicLoader lakeCatalogLoader; + private MetadataManager metadataManager; private ConsumerGroupManager groupManager; private TableInfo offsetsTableInfo; private TableBucket offsetsTableBucket; @@ -82,7 +85,7 @@ void createConsumerGroupManager() throws Exception { Collections.singletonList(ConsumerOffsetSchema.getBucketKeyColumn()), Collections.emptyMap()); lakeCatalogLoader = new LakeCatalogDynamicLoader(conf, null, true); - MetadataManager metadataManager = new MetadataManager(zkClient, conf, lakeCatalogLoader); + metadataManager = new MetadataManager(zkClient, conf, lakeCatalogLoader); offsetsTableInfo = metadataManager.getTable(SystemTables.CONSUMER_OFFSETS); groupManager = new ConsumerGroupManager( @@ -116,6 +119,30 @@ void closeLakeCatalogLoader() throws Exception { } } + @Test + void testListConsumerGroupsDoesNotInitializeOffsetTable() { + AtomicInteger initializationTasks = new AtomicInteger(); + ConsumerGroupManager uninitializedManager = + new ConsumerGroupManager( + TABLET_SERVER_ID, + replicaManager, + ConsumerOffsetTableConfig.from(conf), + zkClient, + metadataManager, + serverMetadataCache, + new TabletServerMetadataProvider( + zkClient, metadataManager, serverMetadataCache), + testCoordinatorGateway, + task -> { + initializationTasks.incrementAndGet(); + task.run(); + }); + + assertThatThrownBy(uninitializedManager::handleListConsumerGroups) + .isInstanceOf(ConsumerGroupOwnerNotAvailableException.class); + assertThat(initializationTasks).hasValue(0); + } + @Test void testValueDecoderReuseBySchemaGetter() { SchemaGetter first = new TestingSchemaGetter(1, ConsumerOffsetSchema.getTableSchema()); diff --git a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchemaTest.java b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchemaTest.java index 525bff7030e..3bfdb538d96 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchemaTest.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchemaTest.java @@ -81,18 +81,11 @@ void testGroupMetadataPrefixAndKeyUseRecordTypeAndGroupId() { ConsumerOffsetSchema.getPrimaryKeys(), null); - CompactedRow row = - offsetSchema.encodeOffsetRow( - ConsumerOffsetSchema.GROUP_METADATA_RECORD_TYPE, - groupId, - -1L, - null, - -1, - new ConsumerOffsetAndMetadata(-1L, "")); + CompactedRow row = offsetSchema.encodeGroupMetadataRow(groupId); assertThat(offsetSchema.encodeGroupMetadataPrefix(groupId)) .isEqualTo(prefixEncoder.encodeKey(row)); - assertThat(offsetSchema.encodeGroupMetadataKey(groupId, -1L, null, -1)) + assertThat(offsetSchema.encodeGroupMetadataKey(groupId)) .isEqualTo(keyEncoder.encodeKey(row)); } diff --git a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/GroupManagerManagementTest.java b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/GroupManagerManagementTest.java index 0f87317d669..158574c6381 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/GroupManagerManagementTest.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/GroupManagerManagementTest.java @@ -67,21 +67,27 @@ void testEncodeGroupRowKeysUsesMetadataRows() throws Exception { valueDecoder()); assertThat(keys) - .containsExactly( - new ConsumerOffsetSchema().encodeGroupMetadataKey(groupId, -1L, null, -1)); + .containsExactly(new ConsumerOffsetSchema().encodeGroupMetadataKey(groupId)); } @Test - void testExistingKeysFiltersPresentValues() { - List keys = Arrays.asList(new byte[] {1}, new byte[] {2}, new byte[] {3}); - List values = - Arrays.asList( - ByteArraySlice.wrap(new byte[] {10}), - null, - ByteArraySlice.wrap(new byte[] {30})); + void testEncodeOffsetRowKeysUsesOffsetRows() throws Exception { + GroupId groupId = GroupId.of("group-1"); + TableBucket first = new TableBucket(1L, 0); + TableBucket second = new TableBucket(1L, 1); + List keys = + ConsumerGroupManager.encodeOffsetRowKeys( + groupId, + Arrays.asList( + encodedGroupMetadata(groupId), + encodedOffset(groupId, first), + encodedOffset(groupId, second)), + valueDecoder()); - assertThat(ConsumerGroupManager.existingKeys(keys, values)) - .containsExactly(keys.get(0), keys.get(2)); + assertThat(keys) + .containsExactly( + new ConsumerOffsetSchema().encodeOffsetKey(groupId, 1L, null, 0), + new ConsumerOffsetSchema().encodeOffsetKey(groupId, 1L, null, 1)); } private static ValueDecoder valueDecoder() { diff --git a/fluss-server/src/test/java/org/apache/fluss/server/utils/ServerRpcMessageUtilsTest.java b/fluss-server/src/test/java/org/apache/fluss/server/utils/ServerRpcMessageUtilsTest.java index 48c1d4f5799..80b18fbf713 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/utils/ServerRpcMessageUtilsTest.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/utils/ServerRpcMessageUtilsTest.java @@ -89,8 +89,6 @@ import org.apache.fluss.server.metadata.PartitionMetadata; import org.apache.fluss.server.metadata.TableMetadata; import org.apache.fluss.server.tablet.consumer.group.ConsumerOffsetAndMetadata; -import org.apache.fluss.server.tablet.consumer.group.result.DeleteConsumerOffsetsResult; -import org.apache.fluss.server.tablet.consumer.group.result.ListConsumerGroupsResult; import org.apache.fluss.utils.FlussPaths; import org.junit.jupiter.api.Test; @@ -258,7 +256,7 @@ void testBuildGetConsumerOffsetsResponsePreservesOrderAndRequiredMetadata() { void testMakeListConsumerGroupsResponsePreservesOrder() { ListConsumerGroupsResponse response = ServerRpcMessageUtils.makeListConsumerGroupsResponse( - ListConsumerGroupsResult.success(Arrays.asList("group-b", "group-a"))); + Arrays.asList("group-b", "group-a")); assertThat(response.getGroupsList()) .extracting(PbListedGroup::getGroupId) .containsExactly("group-b", "group-a"); @@ -320,8 +318,7 @@ void testMakeDeleteConsumerOffsetsResponseReportsEveryRequestedBucket() { bucketErrors.put(failed, Errors.NOT_CONSUMER_GROUP_OWNER); DeleteConsumerOffsetsResponse response = - ServerRpcMessageUtils.makeDeleteConsumerOffsetsResponse( - DeleteConsumerOffsetsResult.success(bucketErrors)); + ServerRpcMessageUtils.makeDeleteConsumerOffsetsResponse(bucketErrors); assertThat(response.getTablesList().get(0).getBucketsList()) .extracting(bucket -> bucket.getBucketId()) diff --git a/website/docs/security/authorization.md b/website/docs/security/authorization.md index d57008ce959..883cf28f63e 100644 --- a/website/docs/security/authorization.md +++ b/website/docs/security/authorization.md @@ -126,9 +126,9 @@ Below is a summary of the currently public protocols and their relationship with | FIND_CONSUMER_GROUP_OWNER | DESCRIBE | Group | Authorization is checked before initializing the consumer-offset system table. | | COMMIT_CONSUMER_OFFSETS | READ | Group and source Tables | Requires `READ` on the consumer group and `READ` on every source table. Group authorization is checked before owner resolution and source-table authorization. | | GET_CONSUMER_OFFSETS | DESCRIBE | Group and source Tables | Requires `DESCRIBE` on the consumer group and every explicitly requested source table. `allOffsets` requests omit source tables the caller cannot describe. | -| DELETE_CONSUMER_OFFSETS | DROP and READ | Group and live source Tables | Requires `DROP` on the consumer group and `READ` on every live source table. Deleted source tables rely on group-level authorization; missing buckets are successful no-ops. | -| LIST_CONSUMER_GROUPS | DESCRIBE | Cluster | Lists consumer groups owned by the receiving tablet server. This is not a cluster-wide listing. | -| DELETE_CONSUMER_GROUPS | DROP | Group | Deletes consumer-group metadata only; committed offsets are not removed. | +| DELETE_CONSUMER_OFFSETS | WRITE(Group) and READ(Table) | Group and Table | Table `READ` is required for every existing source table. Confirmed-deleted source tables require only Group `WRITE`; unknown table state fails retriable. | +| LIST_CONSUMER_GROUPS | DESCRIBE | Cluster or Group | Cluster permission grants visibility to all groups; otherwise, only authorized groups are visible. | +| DELETE_CONSUMER_GROUPS | DROP | Group | No source-table permission is required. | | REGISTER_PRODUCER_OFFSETS | WRITE | Table | Requires `WRITE` on all tables in the request. | | GET_PRODUCER_OFFSETS | READ | Table | Offsets for tables without `READ` permission are filtered out. | | DELETE_PRODUCER_OFFSETS | WRITE | Table | Requires `WRITE` on all tables in the producer offset snapshot. | From 73c9db1a7b29e446cd1ce37240dc737b1855001f Mon Sep 17 00:00:00 2001 From: Jark Wu Date: Sun, 15 Nov 2026 23:54:54 +0800 Subject: [PATCH 4/7] Remove READ(Table) ACL requirement for DELETE_CONSUMER_OFFSETS RPC Co-Authored-By: Codex AI-Contributed/Feature: 75/77 AI-Contributed/UT: 123/123 --- .../rpc/gateway/TabletServerGateway.java | 2 +- fluss-rpc/src/main/proto/FlussApi.proto | 2 +- fluss-rust/crates/fluss/src/proto/fluss.rs | 2 +- .../metadata/ServerMetadataSnapshot.java | 19 +-- .../metadata/TabletServerMetadataCache.java | 29 ++--- .../fluss/server/tablet/TabletService.java | 21 --- .../TabletServerMetadataCacheTest.java | 2 - ...merGroupManagementAuthorizationITCase.java | 121 ++++++++---------- website/docs/security/authorization.md | 2 +- 9 files changed, 64 insertions(+), 136 deletions(-) diff --git a/fluss-rpc/src/main/java/org/apache/fluss/rpc/gateway/TabletServerGateway.java b/fluss-rpc/src/main/java/org/apache/fluss/rpc/gateway/TabletServerGateway.java index 2a68ce374e4..7954df46c11 100644 --- a/fluss-rpc/src/main/java/org/apache/fluss/rpc/gateway/TabletServerGateway.java +++ b/fluss-rpc/src/main/java/org/apache/fluss/rpc/gateway/TabletServerGateway.java @@ -214,7 +214,7 @@ CompletableFuture getConsumerOffsets( /** * Deletes committed offsets for selected buckets of a consumer group. Requires Group {@code - * WRITE} and Table {@code READ}. + * WRITE}; no source-table permission is required. */ @RPC(api = ApiKeys.DELETE_CONSUMER_OFFSETS) CompletableFuture deleteConsumerOffsets( diff --git a/fluss-rpc/src/main/proto/FlussApi.proto b/fluss-rpc/src/main/proto/FlussApi.proto index fad87b02ae3..d065335eddd 100644 --- a/fluss-rpc/src/main/proto/FlussApi.proto +++ b/fluss-rpc/src/main/proto/FlussApi.proto @@ -503,7 +503,7 @@ message GetConsumerOffsetsResponse { repeated PbGetConsumerOffsetsResponseTable tables = 1; } -// Delete committed offsets for selected buckets. Requires Group WRITE and Table READ. +// Delete committed offsets for selected buckets. Requires Group WRITE; no source-table permission. message DeleteConsumerOffsetsRequest { required string group_id = 1; // An empty list, or tables containing no buckets, is a valid no-op and produces an empty diff --git a/fluss-rust/crates/fluss/src/proto/fluss.rs b/fluss-rust/crates/fluss/src/proto/fluss.rs index 18014339497..fa0c6189056 100644 --- a/fluss-rust/crates/fluss/src/proto/fluss.rs +++ b/fluss-rust/crates/fluss/src/proto/fluss.rs @@ -650,7 +650,7 @@ pub struct GetConsumerOffsetsResponse { #[prost(message, repeated, tag = "1")] pub tables: ::prost::alloc::vec::Vec, } -/// Delete committed offsets for selected buckets. Requires Group WRITE and Table READ. +/// Delete committed offsets for selected buckets. Requires Group WRITE; no source-table permission. #[derive(Clone, PartialEq, ::prost::Message)] pub struct DeleteConsumerOffsetsRequest { #[prost(string, required, tag = "1")] diff --git a/fluss-server/src/main/java/org/apache/fluss/server/metadata/ServerMetadataSnapshot.java b/fluss-server/src/main/java/org/apache/fluss/server/metadata/ServerMetadataSnapshot.java index 067511f6b65..2ead046a951 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/metadata/ServerMetadataSnapshot.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/metadata/ServerMetadataSnapshot.java @@ -69,10 +69,6 @@ public class ServerMetadataSnapshot { // epoch to prevent an older bucket layout (ALTER bucket.num) from replacing a newer one. private final Map bucketCountEpochByTableId; - // Table IDs that this server has observed as deleted. A missing table ID is unknown state, - // not proof of deletion. - private final Set deletedTableIds; - public ServerMetadataSnapshot( @Nullable ServerInfo coordinatorServer, Map aliveTabletServers, @@ -82,8 +78,7 @@ public ServerMetadataSnapshot( Map> bucketMetadataMapForTables, Map> bucketMetadataMapForPartitions, Map partitionBucketCounts, - Map bucketCountEpochByTableId, - Set deletedTableIds) { + Map bucketCountEpochByTableId) { this.coordinatorServer = coordinatorServer; this.aliveTabletServers = Collections.unmodifiableMap(aliveTabletServers); @@ -102,7 +97,6 @@ public ServerMetadataSnapshot( Collections.unmodifiableMap(bucketMetadataMapForPartitions); this.partitionBucketCounts = Collections.unmodifiableMap(partitionBucketCounts); this.bucketCountEpochByTableId = Collections.unmodifiableMap(bucketCountEpochByTableId); - this.deletedTableIds = Collections.unmodifiableSet(deletedTableIds); } /** Create an empty cluster instance with no nodes and no table-buckets. */ @@ -116,8 +110,7 @@ public static ServerMetadataSnapshot empty() { Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap(), - Collections.emptyMap(), - Collections.emptySet()); + Collections.emptyMap()); } public ServerNode getCoordinatorServer(String listenerName) { @@ -206,14 +199,6 @@ public Map getBucketCountEpochByTableId() { return bucketCountEpochByTableId; } - public boolean isDeletedTable(long tableId) { - return deletedTableIds.contains(tableId); - } - - public Set getDeletedTableIds() { - return deletedTableIds; - } - public Map getPartitionIdByPath() { return partitionIdByPath; } diff --git a/fluss-server/src/main/java/org/apache/fluss/server/metadata/TabletServerMetadataCache.java b/fluss-server/src/main/java/org/apache/fluss/server/metadata/TabletServerMetadataCache.java index 2cc5de46df8..75590192225 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/metadata/TabletServerMetadataCache.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/metadata/TabletServerMetadataCache.java @@ -140,11 +140,6 @@ public Optional getTablePath(long tableId) { return serverMetadataSnapshot.getTablePath(tableId); } - /** Returns whether this server has observed a deletion tombstone for the table ID. */ - public boolean isDeletedTable(long tableId) { - return serverMetadataSnapshot.isDeletedTable(tableId); - } - public Optional getPhysicalTablePath(long partitionId) { return serverMetadataSnapshot.getPhysicalTablePath(partitionId); } @@ -303,9 +298,7 @@ public Set updateClusterMetadata(ClusterMetadata clusterMetadata) { metadataLock, () -> { ServerMetadataSnapshot currentSnapshot = serverMetadataSnapshot; - Set knownDeletedTableIds = - new HashSet<>(currentSnapshot.getDeletedTableIds()); - Set newlyDeletedTableIds = new HashSet<>(); + Set deletedTableIds = new HashSet<>(); // 1. update coordinator server. ServerInfo coordinatorServer = clusterMetadata.getCoordinatorServer(); @@ -337,8 +330,7 @@ public Set updateClusterMetadata(ClusterMetadata clusterMetadata) { Long removedTableId = tableIdByPath.remove(tablePath); if (removedTableId != null) { bucketMetadataMapForTables.remove(removedTableId); - newlyDeletedTableIds.add(removedTableId); - knownDeletedTableIds.add(removedTableId); + deletedTableIds.add(removedTableId); bucketCountEpochByTableId.remove(removedTableId); tableProperties.remove(removedTableId); } @@ -347,8 +339,7 @@ public Set updateClusterMetadata(ClusterMetadata clusterMetadata) { .getTablePath(tableId) .ifPresent(path -> tableIdByPath.remove(path, tableId)); bucketMetadataMapForTables.remove(tableId); - newlyDeletedTableIds.add(tableId); - knownDeletedTableIds.add(tableId); + deletedTableIds.add(tableId); bucketCountEpochByTableId.remove(tableId); tableProperties.remove(tableId); } else { @@ -450,11 +441,10 @@ public Set updateClusterMetadata(ClusterMetadata clusterMetadata) { bucketMetadataMapForTables, bucketMetadataMapForPartitions, partitionBucketCounts, - bucketCountEpochByTableId, - knownDeletedTableIds); + bucketCountEpochByTableId); tablePropertyCache = tableProperties.build(); serverMetadataSnapshot = newSnapshot; - return newlyDeletedTableIds; + return deletedTableIds; }); } @@ -477,8 +467,7 @@ public void clearTableMetadata() { Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap(), - Collections.emptyMap(), - currentSnapshot.getDeletedTableIds()); + Collections.emptyMap()); tablePropertyCache = ServerTablePropertyCache.empty(); serverMetadataSnapshot = newSnapshot; }); @@ -580,8 +569,7 @@ public void updateTableMetadata(TableMetadata tableMetadata) { bucketMetadataMapForTables, bucketMetadataMapForPartitions, currentSnapshot.getPartitionBucketCounts(), - bucketCountEpochByTableId, - currentSnapshot.getDeletedTableIds()); + bucketCountEpochByTableId); tablePropertyCache = tableProperties.build(); serverMetadataSnapshot = newSnapshot; }); @@ -658,8 +646,7 @@ public void updatePartitionMetadata(PartitionMetadata partitionMetadata) { bucketMetadataMapForTables, bucketMetadataMapForPartitions, partitionBucketCounts, - currentSnapshot.getBucketCountEpochByTableId(), - currentSnapshot.getDeletedTableIds()); + currentSnapshot.getBucketCountEpochByTableId()); serverMetadataSnapshot = newSnapshot; }); } diff --git a/fluss-server/src/main/java/org/apache/fluss/server/tablet/TabletService.java b/fluss-server/src/main/java/org/apache/fluss/server/tablet/TabletService.java index 68bd0e833f3..6f90501402e 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/tablet/TabletService.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/tablet/TabletService.java @@ -924,16 +924,6 @@ public CompletableFuture deleteConsumerOffsets( return CompletableFuture.completedFuture(new DeleteConsumerOffsetsResponse()); } - // The session is bound to the RPC thread. Live source tables require READ before their - // offsets can be deleted. Deleted source tables no longer have a table resource, so their - // cleanup is authorized by the consumer-group permission above. - if (authorizer != null) { - requestedBuckets.stream() - .map(TableBucket::getTableId) - .distinct() - .forEach(this::authorizeLiveSourceTable); - } - return groupManager .handleDeleteConsumerOffsets(groupId, offsetsReplica, requestedBuckets) .thenApply(ServerRpcMessageUtils::makeDeleteConsumerOffsetsResponse); @@ -1225,17 +1215,6 @@ private CompletableFuture submitReplicaStateChange( return response; } - private void authorizeLiveSourceTable(long tableId) { - if (metadataCache.getTablePath(tableId).isPresent()) { - authorizeTable(READ, tableId); - } else if (!metadataCache.isDeletedTable(tableId)) { - // A metadata cache miss is unknown state, not proof that the table was deleted. Keep - // Table READ mandatory until the cache observes either the table or its tombstone. - throw new UnknownTableOrBucketException( - "The metadata state of table " + tableId + " is unknown; retry later."); - } - } - @Override public void authorizeTable(OperationType operationType, long tableId) { if (authorizer != null) { diff --git a/fluss-server/src/test/java/org/apache/fluss/server/metadata/TabletServerMetadataCacheTest.java b/fluss-server/src/test/java/org/apache/fluss/server/metadata/TabletServerMetadataCacheTest.java index 6b94795b95d..34440759754 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/metadata/TabletServerMetadataCacheTest.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/metadata/TabletServerMetadataCacheTest.java @@ -261,8 +261,6 @@ void testUpdateClusterMetadataRequest() { Collections.emptyList())); assertThat(deletedTableIds).containsExactly(DATA1_TABLE_ID); assertThat(serverMetadataCache.getTablePath(DATA1_TABLE_ID)).isEmpty(); - assertThat(serverMetadataCache.isDeletedTable(DATA1_TABLE_ID)).isTrue(); - assertThat(serverMetadataCache.isDeletedTable(partitionTableId)).isFalse(); // test delete one partition. deletedTableIds = diff --git a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagementAuthorizationITCase.java b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagementAuthorizationITCase.java index 7ec02eb0cef..d63a8a42563 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagementAuthorizationITCase.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagementAuthorizationITCase.java @@ -21,11 +21,10 @@ import org.apache.fluss.config.ConfigOptions; import org.apache.fluss.config.Configuration; import org.apache.fluss.exception.AuthorizationException; -import org.apache.fluss.exception.UnknownTableOrBucketException; +import org.apache.fluss.metadata.GroupId; import org.apache.fluss.metadata.Schema; import org.apache.fluss.metadata.TableBucket; import org.apache.fluss.metadata.TableDescriptor; -import org.apache.fluss.metadata.TableInfo; import org.apache.fluss.metadata.TablePath; import org.apache.fluss.rpc.GatewayClientProxy; import org.apache.fluss.rpc.gateway.TabletServerGateway; @@ -53,13 +52,12 @@ import org.apache.fluss.security.acl.OperationType; import org.apache.fluss.security.acl.PermissionType; import org.apache.fluss.security.acl.Resource; -import org.apache.fluss.server.metadata.ClusterMetadata; import org.apache.fluss.server.metadata.SystemTables; -import org.apache.fluss.server.metadata.TableMetadata; import org.apache.fluss.server.metadata.TabletServerMetadataCache; import org.apache.fluss.server.testutils.FlussClusterExtension; import org.apache.fluss.server.zk.data.TableRegistration; import org.apache.fluss.types.DataTypes; +import org.apache.fluss.utils.ByteArraySlice; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -78,7 +76,6 @@ import static org.apache.fluss.security.acl.OperationType.DROP; import static org.apache.fluss.security.acl.OperationType.READ; import static org.apache.fluss.security.acl.OperationType.WRITE; -import static org.apache.fluss.server.metadata.TableMetadata.DELETED_TABLE_ID; import static org.apache.fluss.server.testutils.RpcMessageTestUtils.createTable; import static org.apache.fluss.server.testutils.RpcMessageTestUtils.dropTable; import static org.apache.fluss.testutils.common.CommonTestUtils.retry; @@ -113,6 +110,7 @@ class ConsumerGroupManagementAuthorizationITCase { private ServerNode clientNode; private TableBucket sourceBucket; private TableBucket secondSourceBucket; + private TableBucket offsetsTableBucket; @BeforeEach void setUp() throws Exception { @@ -160,7 +158,8 @@ void setUp() throws Exception { () -> cluster.getZooKeeperClient().getTable(SystemTables.CONSUMER_OFFSETS), WAIT_TIMEOUT, "Consumer offsets table was not created"); - cluster.waitUntilAllReplicaReady(new TableBucket(offsetsTable.tableId, 0)); + offsetsTableBucket = new TableBucket(offsetsTable.tableId, 0); + cluster.waitUntilAllReplicaReady(offsetsTableBucket); } @AfterEach @@ -211,7 +210,7 @@ void testDeleteConsumerGroupsRemovesMetadataAndOffsets() throws Exception { } @Test - void testDeleteConsumerOffsetsRequiresGroupWriteAndTableRead() throws Exception { + void testDeleteConsumerOffsetsRequiresOnlyGroupWrite() throws Exception { commitOffset(FIRST_GROUP, 10L); grant(READ, Resource.group(FIRST_GROUP)); @@ -219,17 +218,11 @@ void testDeleteConsumerOffsetsRequiresGroupWriteAndTableRead() throws Exception .rootCause() .isInstanceOf(AuthorizationException.class) .hasMessageContaining("WRITE"); + assertThat(lookupOffset(sourceBucket)).doesNotContainNull(); grant(WRITE, Resource.group(FIRST_GROUP)); - assertThatThrownBy(() -> clientGateway.deleteConsumerOffsets(deleteRequest()).get()) - .rootCause() - .isInstanceOf(AuthorizationException.class) - .hasMessageContaining("READ"); - - grant(READ, Resource.table(SOURCE_TABLE)); - assertThat(getAllOffsets(FIRST_GROUP)).containsExactly(10L); - clientGateway.deleteConsumerOffsets(deleteRequest()).get(); - assertThat(getAllOffsets(FIRST_GROUP)).isEmpty(); + deleteOffsets(sourceBucket); + assertThat(lookupOffset(sourceBucket)).containsOnlyNulls(); } @Test @@ -247,13 +240,9 @@ void testGroupDropDoesNotReplaceGroupWriteForOffsetDeletion() throws Exception { void testGroupWriteWithoutDropDeletesOffsetsButNotGroup() throws Exception { commitOffset(FIRST_GROUP, 10L); grant(WRITE, Resource.group(FIRST_GROUP)); - grant(READ, Resource.table(SOURCE_TABLE)); - clientGateway.deleteConsumerOffsets(deleteRequest()).get(); - - grant(DESCRIBE, Resource.group(FIRST_GROUP)); - grant(DESCRIBE, Resource.table(SOURCE_TABLE)); - assertThat(getAllOffsets(FIRST_GROUP)).isEmpty(); + deleteOffsets(sourceBucket); + assertThat(lookupOffset(sourceBucket)).containsOnlyNulls(); assertThatThrownBy( () -> @@ -272,14 +261,7 @@ void testGroupWriteWithoutDropDeletesOffsetsButNotGroup() throws Exception { @Test void testDeleteConsumerOffsetsTreatsMissingOffsetsAsNoOp() throws Exception { grant(WRITE, Resource.group(FIRST_GROUP)); - grant(READ, Resource.table(SOURCE_TABLE)); - - DeleteConsumerOffsetsResponse response = - clientGateway.deleteConsumerOffsets(deleteRequest()).get(); - - assertThat(response.getTablesList()).hasSize(1); - assertThat(response.getTableAt(0).getBucketsList()).hasSize(1); - assertThat(response.getTableAt(0).getBucketAt(0).hasErrorCode()).isFalse(); + deleteOffsets(sourceBucket); } @Test @@ -287,53 +269,30 @@ void testDeletedSourceTableRequiresOnlyGroupWrite() throws Exception { commitOffset(FIRST_GROUP, 10L); grant(WRITE, Resource.group(FIRST_GROUP)); - long tableId = sourceBucket.getTableId(); dropTable(cluster, SOURCE_TABLE); retry( WAIT_TIMEOUT, () -> assertThat(cluster.getZooKeeperClient().tableExist(SOURCE_TABLE)).isFalse()); - TableDescriptor descriptor = - TableDescriptor.builder() - .schema(Schema.newBuilder().column("id", DataTypes.INT()).build()) - .distributedBy(1) - .build(); - TableInfo deletedTableInfo = - TableInfo.of(SOURCE_TABLE, DELETED_TABLE_ID, 0, descriptor, null, -1L, -1L); - ClusterMetadata clusterMetadata = - new ClusterMetadata( - null, - Collections.emptySet(), - Collections.singletonList( - new TableMetadata(deletedTableInfo, Collections.emptyList())), - Collections.emptyList()); - cluster.getTabletServerById(clientNode.id()) - .getMetadataCache() - .updateClusterMetadata(clusterMetadata); - - clientGateway.deleteConsumerOffsets(deleteRequest(tableId)).get(); + assertThat(lookupOffset(sourceBucket)).doesNotContainNull(); + deleteOffsets(sourceBucket); + assertThat(lookupOffset(sourceBucket)).containsOnlyNulls(); } @Test - void testLiveSourceTableMissingFromMetadataCacheFailsGroupOnlyCleanup() throws Exception { - commitOffset(FIRST_GROUP, 10L); + void testDeleteConsumerOffsetsDoesNotRequireSourceTableMetadata() throws Exception { + commitOffset(FIRST_GROUP, secondSourceBucket, 20L); grant(WRITE, Resource.group(FIRST_GROUP)); TabletServerMetadataCache metadataCache = cluster.getTabletServerById(clientNode.id()).getMetadataCache(); - TableMetadata firstTableMetadata = metadataCache.getTableMetadata(SOURCE_TABLE).get(); metadataCache.clearTableMetadata(); - metadataCache.updateTableMetadata(firstTableMetadata); assertThat(cluster.getZooKeeperClient().tableExist(SECOND_SOURCE_TABLE)).isTrue(); - assertThatThrownBy( - () -> - clientGateway - .deleteConsumerOffsets(deleteRequest(secondSourceBucket)) - .get()) - .rootCause() - .isInstanceOf(UnknownTableOrBucketException.class) - .hasMessageContaining("unknown"); + assertThat(metadataCache.getTablePath(secondSourceBucket.getTableId())).isEmpty(); + assertThat(lookupOffset(secondSourceBucket)).doesNotContainNull(); + deleteOffsets(secondSourceBucket); + assertThat(lookupOffset(secondSourceBucket)).containsOnlyNulls(); } @Test @@ -366,18 +325,38 @@ void testDeleteConsumerGroupsRemovesOffsetsAcrossTablesAndBuckets() throws Excep } @Test - void testUnknownSourceTableStateFailsRetriably() throws Exception { + void testDeleteConsumerOffsetsForUnknownSourceTableIsNoOp() throws Exception { commitOffset(FIRST_GROUP, 10L); grant(WRITE, Resource.group(FIRST_GROUP)); - assertThatThrownBy( - () -> - clientGateway - .deleteConsumerOffsets(deleteRequest(Long.MAX_VALUE)) - .get()) - .rootCause() - .isInstanceOf(UnknownTableOrBucketException.class) - .hasMessageContaining("unknown"); + deleteOffsets(new TableBucket(Long.MAX_VALUE, 0)); + assertThat(lookupOffset(sourceBucket)).doesNotContainNull(); + } + + private void deleteOffsets(TableBucket tableBucket) throws Exception { + DeleteConsumerOffsetsResponse response = + clientGateway.deleteConsumerOffsets(deleteRequest(tableBucket)).get(); + assertThat(response.getTablesList()).hasSize(1); + assertThat(response.getTableAt(0).getTableId()).isEqualTo(tableBucket.getTableId()); + assertThat(response.getTableAt(0).getBucketsList()).hasSize(1); + assertThat(response.getTableAt(0).getBucketAt(0).getBucketId()) + .isEqualTo(tableBucket.getBucket()); + assertThat(response.getTableAt(0).getBucketAt(0).hasErrorCode()).isFalse(); + } + + private List lookupOffset(TableBucket tableBucket) throws Exception { + // Read the stored key directly so source-table visibility cannot hide a failed deletion. + byte[] key = + new ConsumerOffsetSchema() + .encodeOffsetKey( + GroupId.of(FIRST_GROUP), + tableBucket.getTableId(), + tableBucket.getPartitionId(), + tableBucket.getBucket()); + return cluster.getTabletServerById(clientNode.id()) + .getReplicaManager() + .getReplicaOrException(offsetsTableBucket) + .lookups(Collections.singletonList(key)); } private void commitOffset(String groupId, long offset) throws Exception { diff --git a/website/docs/security/authorization.md b/website/docs/security/authorization.md index 883cf28f63e..a6cd39d8099 100644 --- a/website/docs/security/authorization.md +++ b/website/docs/security/authorization.md @@ -126,7 +126,7 @@ Below is a summary of the currently public protocols and their relationship with | FIND_CONSUMER_GROUP_OWNER | DESCRIBE | Group | Authorization is checked before initializing the consumer-offset system table. | | COMMIT_CONSUMER_OFFSETS | READ | Group and source Tables | Requires `READ` on the consumer group and `READ` on every source table. Group authorization is checked before owner resolution and source-table authorization. | | GET_CONSUMER_OFFSETS | DESCRIBE | Group and source Tables | Requires `DESCRIBE` on the consumer group and every explicitly requested source table. `allOffsets` requests omit source tables the caller cannot describe. | -| DELETE_CONSUMER_OFFSETS | WRITE(Group) and READ(Table) | Group and Table | Table `READ` is required for every existing source table. Confirmed-deleted source tables require only Group `WRITE`; unknown table state fails retriable. | +| DELETE_CONSUMER_OFFSETS | WRITE | Group | No source-table permission is required. | | LIST_CONSUMER_GROUPS | DESCRIBE | Cluster or Group | Cluster permission grants visibility to all groups; otherwise, only authorized groups are visible. | | DELETE_CONSUMER_GROUPS | DROP | Group | No source-table permission is required. | | REGISTER_PRODUCER_OFFSETS | WRITE | Table | Requires `WRITE` on all tables in the request. | From 20870bf4d1ff7bcc7ec33276ef72906f38383558 Mon Sep 17 00:00:00 2001 From: Jark Wu Date: Mon, 16 Nov 2026 00:05:22 +0800 Subject: [PATCH 5/7] fix tests Co-Authored-By: Codex AI-Contributed/Feature: 0/0 AI-Contributed/UT: 27/27 --- .../server/tablet/TabletServiceTest.java | 27 +++++-------------- 1 file changed, 6 insertions(+), 21 deletions(-) diff --git a/fluss-server/src/test/java/org/apache/fluss/server/tablet/TabletServiceTest.java b/fluss-server/src/test/java/org/apache/fluss/server/tablet/TabletServiceTest.java index 7b19875d6e9..94c75ceb200 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/tablet/TabletServiceTest.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/tablet/TabletServiceTest.java @@ -112,8 +112,7 @@ void testInvalidGroupIdTakesPrecedence(boolean empty) throws Exception { if (!empty) { request.getTableAt(0).getBucketAt(0).setPartitionId(-1L); } - assertThatThrownBy(() -> service.commitConsumerOffsets(request).join()) - .cause() + assertThatThrownBy(() -> service.commitConsumerOffsets(request)) .isInstanceOf(InvalidConsumerGroupIdException.class); assertThat(executor.numQueuedRunnables()).isZero(); } @@ -130,17 +129,13 @@ void testCommitWhileFindIsInitializing() throws Exception { assertThat(find).isNotDone(); assertThat(executor.numQueuedRunnables()).isOne(); - CompletableFuture unavailable = service.commitConsumerOffsets(request); - assertThat(unavailable).isCompletedExceptionally(); - assertThatThrownBy(unavailable::join) - .cause() + assertThatThrownBy(() -> service.commitConsumerOffsets(request)) .isInstanceOf(ConsumerGroupOwnerNotAvailableException.class); assertThat(executor.numQueuedRunnables()).isOne(); executor.triggerAll(); assertThat(find).isCompleted(); - assertThatThrownBy(() -> service.commitConsumerOffsets(request).join()) - .cause() + assertThatThrownBy(() -> service.commitConsumerOffsets(request)) .isInstanceOf(InvalidPartitionException.class); assertCommitResult( service.commitConsumerOffsets(newCommitRequest(GROUP_ID, 10L)), Errors.NONE); @@ -233,12 +228,7 @@ void testGetConsumerOffsetsRejectsInvalidRequestCombination() throws Exception { GetConsumerOffsetsRequest request = new GetConsumerOffsetsRequest().setGroupId(GROUP_ID).setAllOffsets(true); request.addTable().setTableId(1L).addBucket().setBucketId(0); - CompletableFuture response = - service.getConsumerOffsets(request); - - assertThat(response).isCompletedExceptionally(); - assertThatThrownBy(response::join) - .cause() + assertThatThrownBy(() -> service.getConsumerOffsets(request)) .isInstanceOf(InvalidRequestException.class) .hasMessageContaining("all_offsets"); } @@ -246,14 +236,9 @@ void testGetConsumerOffsetsRejectsInvalidRequestCombination() throws Exception { @Test void testCommitBeforeFindDoesNotScheduleInitialization() throws Exception { TabletService service = createService(); - CompletableFuture response = - service.commitConsumerOffsets(newCommitRequest(GROUP_ID, 10L)); - - assertThat(executor.numQueuedRunnables()).isZero(); - assertThat(response).isCompletedExceptionally(); - assertThatThrownBy(response::join) - .cause() + assertThatThrownBy(() -> service.commitConsumerOffsets(newCommitRequest(GROUP_ID, 10L))) .isInstanceOf(ConsumerGroupOwnerNotAvailableException.class); + assertThat(executor.numQueuedRunnables()).isZero(); assertThat(zkClient.tableExist(SystemTables.CONSUMER_OFFSETS)).isFalse(); } From c35ba297f2e7b7751cdf78a417a7ef6923693af1 Mon Sep 17 00:00:00 2001 From: Jark Wu Date: Mon, 16 Nov 2026 00:08:34 +0800 Subject: [PATCH 6/7] Refactor ConsumerGroupManager to simplify code --- .../fluss/server/tablet/TabletService.java | 30 +-- .../consumer/group/ConsumerGroupManager.java | 229 +++++++----------- .../consumer/group/ConsumerOffsetSchema.java | 47 +--- ...merGroupManagementAuthorizationITCase.java | 37 +++ .../group/ConsumerGroupManagerTest.java | 55 ++++- .../group/ConsumerOffsetSchemaTest.java | 9 +- .../group/GroupManagerManagementTest.java | 120 --------- 7 files changed, 196 insertions(+), 331 deletions(-) delete mode 100644 fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/GroupManagerManagementTest.java diff --git a/fluss-server/src/main/java/org/apache/fluss/server/tablet/TabletService.java b/fluss-server/src/main/java/org/apache/fluss/server/tablet/TabletService.java index 6f90501402e..3f67255fc18 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/tablet/TabletService.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/tablet/TabletService.java @@ -932,25 +932,17 @@ public CompletableFuture deleteConsumerOffsets( @Override public CompletableFuture listConsumerGroups( ListConsumerGroupsRequest request) { - final Session session = currentSession(); - return groupManager - .handleListConsumerGroups() - .thenApply( - groupIds -> { - if (authorizer != null) { - List resources = - groupIds.stream() - .map(Resource::group) - .collect(Collectors.toList()); - groupIds = - authorizer - .filterByAuthorized(session, DESCRIBE, resources) - .stream() - .map(Resource::getName) - .collect(Collectors.toList()); - } - return ServerRpcMessageUtils.makeListConsumerGroupsResponse(groupIds); - }); + List groupIds = groupManager.handleListConsumerGroups(); + if (authorizer != null) { + List resources = + groupIds.stream().map(Resource::group).collect(Collectors.toList()); + groupIds = + authorizer.filterByAuthorized(currentSession(), DESCRIBE, resources).stream() + .map(Resource::getName) + .collect(Collectors.toList()); + } + return CompletableFuture.completedFuture( + ServerRpcMessageUtils.makeListConsumerGroupsResponse(groupIds)); } @Override diff --git a/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManager.java b/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManager.java index 35087600f68..842d0ec91b4 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManager.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManager.java @@ -77,15 +77,13 @@ import java.util.Map; import java.util.Optional; import java.util.OptionalInt; -import java.util.Set; -import java.util.TreeSet; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicReference; import static org.apache.fluss.server.metadata.TableMetadata.DELETED_TABLE_ID; import static org.apache.fluss.server.metadata.TableMetadata.DELETED_TABLE_PATH; +import static org.apache.fluss.server.tablet.consumer.group.ConsumerOffsetSchema.GROUP_METADATA_PREFIX; import static org.apache.fluss.server.tablet.consumer.group.ConsumerOffsetSchema.GROUP_METADATA_RECORD_TYPE; import static org.apache.fluss.server.tablet.consumer.group.ConsumerOffsetSchema.OFFSET_COMMIT_RECORD_TYPE; import static org.apache.fluss.server.tablet.consumer.group.ConsumerOffsetTableConfig.OFFSET_COMMIT_REQUIRED_ACKS; @@ -161,10 +159,7 @@ public void onTableMetadataUpdate(List tables) { } } else if (DELETED_TABLE_PATH.equals(info.getTablePath())) { CompletableFuture current = tableInitFuture.get(); - TableInfo cached = - current == null - ? null - : current.handle((tableInfo, error) -> tableInfo).getNow(null); + TableInfo cached = getInitializedTableOrNull(); if (cached != null && cached.getTableId() == info.getTableId()) { tableInitFuture.compareAndSet(current, null); } @@ -174,17 +169,22 @@ public void onTableMetadataUpdate(List tables) { /** Returns the local leader replica or throws a request-level group error. */ public Replica validateGroupId(GroupId groupId) { - TableInfo info = getInitializedTable(tableInitFuture.get()); + TableInfo info = getInitializedTableOrThrow(); return checkOwnership( new TableBucket( info.getTableId(), offsetSchema.bucketFor(groupId, info.getNumBuckets()))); } - private static TableInfo getInitializedTable(@Nullable CompletableFuture current) { - TableInfo info = - current == null - ? null - : current.handle((tableInfo, error) -> tableInfo).getNow(null); + @Nullable + private TableInfo getInitializedTableOrNull() { + CompletableFuture current = tableInitFuture.get(); + return current == null + ? null + : current.handle((tableInfo, error) -> tableInfo).getNow(null); + } + + private TableInfo getInitializedTableOrThrow() { + TableInfo info = getInitializedTableOrNull(); if (info == null) { throw new ConsumerGroupOwnerNotAvailableException( "Table metadata for " @@ -419,26 +419,14 @@ public CompletableFuture> handleCommitConsumerOffsets( return CompletableFuture.completedFuture(results); } - CompletableFuture> write = new CompletableFuture<>(); try { - KvRecordBatch batch = - buildUpsertBatch( - groupId, validOffsets, offsetsReplica.getTableInfo().getSchemaId()); - Map batchByBucket = - Collections.singletonMap(offsetsReplica.getTableBucket(), batch); - replicaManager.putRecordsToKv( - offsetsConfig.getOffsetCommitTimeoutMs(), - OFFSET_COMMIT_REQUIRED_ACKS, - batchByBucket, - null, - MergeMode.DEFAULT, - ApiKeys.PUT_KV.highestSupportedVersion, - write::complete); + KvRecordBatch batch = buildUpsertBatch(groupId, validOffsets, offsetsReplica); + return writeBatch(offsetsReplica, batch) + .thenApply( + writeResults -> handleWriteCompletion(groupId, results, writeResults)); } catch (Exception e) { return CompletableFuture.completedFuture(handleCommitFailure(groupId, results, e)); } - return write.thenApply( - writeResults -> handleWriteCompletion(groupId, results, writeResults)); } /** @@ -556,27 +544,25 @@ static void populateSelectedOffsets( * Lists distinct consumer groups from consumer-offset buckets led by this server. Listing does * not initialize the offsets table; prefix reads run on the RPC worker thread. */ - public CompletableFuture> handleListConsumerGroups() { - TableInfo offsetsTableInfo = getInitializedTable(tableInitFuture.get()); - try { - Set groupIds = new TreeSet<>(); - for (int bucketId = 0; bucketId < offsetsTableInfo.getNumBuckets(); bucketId++) { - Replica replica = - localLeaderReplica( - new TableBucket(offsetsTableInfo.getTableId(), bucketId)); - if (replica == null) { - continue; + public List handleListConsumerGroups() { + TableInfo offsetsTableInfo = getInitializedTableOrThrow(); + List groupIds = new ArrayList<>(); + for (int bucketId = 0; bucketId < offsetsTableInfo.getNumBuckets(); bucketId++) { + Replica replica = + localLeaderReplica(new TableBucket(offsetsTableInfo.getTableId(), bucketId)); + if (replica == null) { + continue; + } + List groupMetadataList = replica.prefixLookup(GROUP_METADATA_PREFIX); + ValueDecoder valueDecoder = getValueDecoder(replica.getSchemaGetter()); + for (ByteArraySlice groupMetadata : groupMetadataList) { + InternalRow row = valueDecoder.decodeValue(groupMetadata.toByteArray()).row; + if (row.getInt(0) == GROUP_METADATA_RECORD_TYPE) { + groupIds.add(row.getString(1).toString()); } - populateGroupIds( - replica.prefixLookup(offsetSchema.encodeGroupMetadataPrefix()), - getValueDecoder(replica.getSchemaGetter()), - groupIds); } - return CompletableFuture.completedFuture(new ArrayList<>(groupIds)); - } catch (Exception e) { - LOG.warn("Failed to list consumer groups.", e); - throw new CompletionException(e); } + return groupIds; } /** @@ -593,29 +579,23 @@ public CompletableFuture> handleDeleteConsumerGroups( Replica replica = entry.getValue(); try { ValueDecoder valueDecoder = getValueDecoder(replica.getSchemaGetter()); - List metadataKeys = - encodeGroupRowKeys( + byte[] metadataKey = offsetSchema.encodeGroupMetadataKey(groupId); + List offsetKeys = + encodeOffsetRowKeys( groupId, replica.prefixLookup( - offsetSchema.encodeGroupMetadataPrefix(groupId)), + offsetSchema.encodeOffsetCommitPrefix(groupId)), valueDecoder); - List offsetKeys = offsetRowKeys(replica, groupId, valueDecoder); - List keys = new ArrayList<>(metadataKeys.size() + offsetKeys.size()); - keys.addAll(metadataKeys); + List keys = new ArrayList<>(offsetKeys.size() + 1); + keys.add(metadataKey); keys.addAll(offsetKeys); - - if (keys.isEmpty()) { - deletions.add( - CompletableFuture.completedFuture(Errors.CONSUMER_GROUP_ID_NOT_FOUND)); - } else { - deletions.add( - deleteKeys(replica, keys) - .handle( - (ignored, error) -> - error == null - ? Errors.NONE - : Errors.forException(error))); - } + deletions.add( + deleteKeys(replica, keys) + .handle( + (ignored, error) -> + error == null + ? Errors.NONE + : Errors.forException(error))); } catch (Exception e) { deletions.add(CompletableFuture.completedFuture(Errors.forException(e))); } @@ -632,53 +612,9 @@ public CompletableFuture> handleDeleteConsumerGroups( }); } - private List offsetRowKeys(Replica replica, GroupId groupId, ValueDecoder valueDecoder) - throws Exception { - return encodeOffsetRowKeys( - groupId, - replica.prefixLookup(offsetSchema.encodeOffsetCommitPrefix(groupId)), - valueDecoder); - } - @VisibleForTesting - static void populateGroupIds( - List values, ValueDecoder valueDecoder, Set groupIds) - throws Exception { - for (ByteArraySlice value : values) { - InternalRow row = valueDecoder.decodeValue(value.toByteArray()).row; - if (row.getInt(0) == GROUP_METADATA_RECORD_TYPE) { - groupIds.add(row.getString(1).toString()); - } - } - } - - @VisibleForTesting - static List encodeGroupRowKeys( - GroupId groupId, List values, ValueDecoder valueDecoder) - throws Exception { - ConsumerOffsetSchema schema = new ConsumerOffsetSchema(); - List keys = new ArrayList<>(); - for (ByteArraySlice value : values) { - InternalRow row = valueDecoder.decodeValue(value.toByteArray()).row; - if (row.getInt(0) != GROUP_METADATA_RECORD_TYPE) { - continue; - } - TableBucket tableBucket = ConsumerOffsetSchema.toTableBucket(row); - keys.add( - schema.encodeGroupMetadataKey( - groupId, - tableBucket.getTableId(), - tableBucket.getPartitionId(), - tableBucket.getBucket())); - } - return keys; - } - - @VisibleForTesting - static List encodeOffsetRowKeys( - GroupId groupId, List values, ValueDecoder valueDecoder) - throws Exception { - ConsumerOffsetSchema schema = new ConsumerOffsetSchema(); + List encodeOffsetRowKeys( + GroupId groupId, List values, ValueDecoder valueDecoder) { List keys = new ArrayList<>(); for (ByteArraySlice value : values) { InternalRow row = valueDecoder.decodeValue(value.toByteArray()).row; @@ -687,7 +623,7 @@ static List encodeOffsetRowKeys( } TableBucket tableBucket = ConsumerOffsetSchema.toTableBucket(row); keys.add( - schema.encodeOffsetKey( + offsetSchema.encodeOffsetKey( groupId, tableBucket.getTableId(), tableBucket.getPartitionId(), @@ -697,38 +633,38 @@ static List encodeOffsetRowKeys( } private CompletableFuture deleteKeys(Replica replica, List keys) { - CompletableFuture result = new CompletableFuture<>(); try { - KvRecordBatchBuilder builder = - KvRecordBatchBuilder.builder( - replica.getTableInfo().getSchemaId(), - Integer.MAX_VALUE, - new UnmanagedPagedOutputView(OFFSET_COMMIT_PAGE_SIZE), - KvFormat.COMPACTED); + KvRecordBatchBuilder builder = createBatchBuilder(replica); for (byte[] key : keys) { builder.append(key, null); } KvRecordBatch batch = DefaultKvRecordBatch.pointToBytesView(builder.build()); - replicaManager.putRecordsToKv( - offsetsConfig.getOffsetCommitTimeoutMs(), - OFFSET_COMMIT_REQUIRED_ACKS, - Collections.singletonMap(replica.getTableBucket(), batch), - null, - MergeMode.DEFAULT, - ApiKeys.PUT_KV.highestSupportedVersion, - writeResults -> { - for (PutKvResultForBucket writeResult : writeResults) { - if (writeResult.getError().error() != Errors.NONE) { - result.completeExceptionally( - mapCommitError(writeResult.getError().error()).exception()); - return; - } - } - result.complete(null); - }); + return writeBatch(replica, batch) + .thenAccept( + writeResults -> { + for (PutKvResultForBucket writeResult : writeResults) { + Errors error = writeResult.getError().error(); + if (error != Errors.NONE) { + throw mapCommitError(error).exception(); + } + } + }); } catch (Exception e) { - result.completeExceptionally(e); + return FutureUtils.completedExceptionally(e); } + } + + private CompletableFuture> writeBatch( + Replica replica, KvRecordBatch batch) { + CompletableFuture> result = new CompletableFuture<>(); + replicaManager.putRecordsToKv( + offsetsConfig.getOffsetCommitTimeoutMs(), + OFFSET_COMMIT_REQUIRED_ACKS, + Collections.singletonMap(replica.getTableBucket(), batch), + null, + MergeMode.DEFAULT, + ApiKeys.PUT_KV.highestSupportedVersion, + result::complete); return result; } @@ -768,14 +704,9 @@ private static Map handleCommitFailure( } private KvRecordBatch buildUpsertBatch( - GroupId groupId, Map offsets, int schemaId) + GroupId groupId, Map offsets, Replica replica) throws Exception { - KvRecordBatchBuilder builder = - KvRecordBatchBuilder.builder( - schemaId, - Integer.MAX_VALUE, - new UnmanagedPagedOutputView(OFFSET_COMMIT_PAGE_SIZE), - KvFormat.COMPACTED); + KvRecordBatchBuilder builder = createBatchBuilder(replica); // Keep a metadata row for every group that has committed offsets. Listing and deleting // groups depend on this row; upserting it on each commit is idempotent. @@ -798,6 +729,14 @@ private KvRecordBatch buildUpsertBatch( return DefaultKvRecordBatch.pointToBytesView(builder.build()); } + private static KvRecordBatchBuilder createBatchBuilder(Replica replica) { + return KvRecordBatchBuilder.builder( + replica.getTableInfo().getSchemaId(), + Integer.MAX_VALUE, + new UnmanagedPagedOutputView(OFFSET_COMMIT_PAGE_SIZE), + KvFormat.COMPACTED); + } + /** * Returns the group's owner replica, the local online leader for its offsets-table bucket. If * the local replica is missing, offline, or a follower, the cached leader determines the diff --git a/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchema.java b/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchema.java index f3bdc238c4c..584d7388c02 100644 --- a/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchema.java +++ b/fluss-server/src/main/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchema.java @@ -79,13 +79,16 @@ public final class ConsumerOffsetSchema { private static final List GROUP_LOOKUP_PREFIX_KEYS = Collections.unmodifiableList(Arrays.asList(RECORD_TYPE_COLUMN, GROUP_ID_COLUMN)); - private static final List GROUP_METADATA_PREFIX_KEYS = - Collections.singletonList(RECORD_TYPE_COLUMN); - private static final Schema TABLE_SCHEMA = createTableSchema(); private static final RowType ROW_TYPE = TABLE_SCHEMA.getRowType(); private static final DataType[] DATA_TYPES = ROW_TYPE.getChildren().toArray(new DataType[0]); + /** Encoded prefix for all group metadata rows. Must not be modified. */ + static final byte[] GROUP_METADATA_PREFIX = + KeyEncoder.ofBucketKeyEncoder( + ROW_TYPE, Collections.singletonList(RECORD_TYPE_COLUMN), null) + .encodeKey(GenericRow.of(GROUP_METADATA_RECORD_TYPE)); + private final ThreadLocal rowEncoder = ThreadLocal.withInitial(() -> new CompactedRowEncoder(DATA_TYPES)); // sys.consumer_offsets has no lake format, so ofPrimaryKeyEncoder uses compacted keys @@ -102,11 +105,6 @@ public final class ConsumerOffsetSchema { private final ThreadLocal groupLookupPrefixEncoder = ThreadLocal.withInitial( () -> KeyEncoder.ofBucketKeyEncoder(ROW_TYPE, GROUP_LOOKUP_PREFIX_KEYS, null)); - private final ThreadLocal groupMetadataAllPrefixEncoder = - ThreadLocal.withInitial( - () -> - KeyEncoder.ofBucketKeyEncoder( - ROW_TYPE, GROUP_METADATA_PREFIX_KEYS, null)); /** Returns the schema of the consumer-offset system table. */ public static Schema getTableSchema() { @@ -175,44 +173,17 @@ public byte[] encodeOffsetCommitPrefix(GroupId groupId) { BinaryString.fromString(groupId.getGroupId()))); } - /** Encodes the {@code record_type} prefix used to enumerate all group metadata rows. */ - public byte[] encodeGroupMetadataPrefix() { - return groupMetadataAllPrefixEncoder - .get() - .encodeKey(GenericRow.of(GROUP_METADATA_RECORD_TYPE)); - } - - /** - * Encodes the {@code record_type} and {@code group_id} prefix used to enumerate one group's - * metadata rows. - */ - public byte[] encodeGroupMetadataPrefix(GroupId groupId) { - return groupLookupPrefixEncoder - .get() - .encodeKey( - GenericRow.of( - GROUP_METADATA_RECORD_TYPE, - BinaryString.fromString(groupId.getGroupId()))); - } - /** Encodes the complete primary key of a group metadata row. */ public byte[] encodeGroupMetadataKey(GroupId groupId) { - return encodeGroupMetadataKey( - groupId, GROUP_METADATA_TABLE_ID, null, GROUP_METADATA_BUCKET_ID); - } - - /** Encodes the complete primary key of a group metadata row with explicit source columns. */ - public byte[] encodeGroupMetadataKey( - GroupId groupId, long tableId, Long partitionId, int bucketId) { return primaryKeyEncoder .get() .encodeKey( GenericRow.of( GROUP_METADATA_RECORD_TYPE, BinaryString.fromString(groupId.getGroupId()), - tableId, - partitionId == null ? NON_PARTITIONED_PARTITION_ID : partitionId, - bucketId)); + GROUP_METADATA_TABLE_ID, + NON_PARTITIONED_PARTITION_ID, + GROUP_METADATA_BUCKET_ID)); } /** Encodes a group metadata row. */ diff --git a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagementAuthorizationITCase.java b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagementAuthorizationITCase.java index d63a8a42563..2fceb78d9e5 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagementAuthorizationITCase.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagementAuthorizationITCase.java @@ -32,6 +32,7 @@ import org.apache.fluss.rpc.messages.CommitConsumerOffsetsResponse; import org.apache.fluss.rpc.messages.CreateAclsRequest; import org.apache.fluss.rpc.messages.DeleteConsumerGroupsRequest; +import org.apache.fluss.rpc.messages.DeleteConsumerGroupsResponse; import org.apache.fluss.rpc.messages.DeleteConsumerOffsetsRequest; import org.apache.fluss.rpc.messages.DeleteConsumerOffsetsResponse; import org.apache.fluss.rpc.messages.FindConsumerGroupOwnerRequest; @@ -46,6 +47,7 @@ import org.apache.fluss.rpc.messages.PbListedGroup; import org.apache.fluss.rpc.metrics.TestingClientMetricGroup; import org.apache.fluss.rpc.netty.client.NettyClient; +import org.apache.fluss.rpc.protocol.Errors; import org.apache.fluss.security.acl.AccessControlEntry; import org.apache.fluss.security.acl.AclBinding; import org.apache.fluss.security.acl.FlussPrincipal; @@ -65,6 +67,7 @@ import java.time.Duration; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; @@ -209,6 +212,40 @@ void testDeleteConsumerGroupsRemovesMetadataAndOffsets() throws Exception { assertThat(getAllOffsets(FIRST_GROUP)).containsExactly(20L); } + @Test + void testDeleteConsumerGroupsDistinguishesEmptyAndMissingGroups() throws Exception { + commitOffset(FIRST_GROUP, 10L); + grant(WRITE, Resource.group(FIRST_GROUP)); + grant(DROP, Resource.group(FIRST_GROUP)); + grant(DROP, Resource.group(SECOND_GROUP)); + + deleteOffsets(sourceBucket); + assertThat(lookupOffset(sourceBucket)).containsOnlyNulls(); + assertThat(listGroups()).containsExactly(FIRST_GROUP); + + DeleteConsumerGroupsResponse response = + clientGateway + .deleteConsumerGroups( + new DeleteConsumerGroupsRequest() + .addAllGroups(Arrays.asList(FIRST_GROUP, SECOND_GROUP))) + .get(); + + assertThat(response.getGroupsList()) + .hasSize(2) + .anySatisfy( + group -> { + assertThat(group.getGroupId()).isEqualTo(FIRST_GROUP); + assertThat(group.hasErrorCode()).isFalse(); + }) + .anySatisfy( + group -> { + assertThat(group.getGroupId()).isEqualTo(SECOND_GROUP); + assertThat(group.getErrorCode()) + .isEqualTo(Errors.CONSUMER_GROUP_ID_NOT_FOUND.code()); + }); + assertThat(listGroups()).isEmpty(); + } + @Test void testDeleteConsumerOffsetsRequiresOnlyGroupWrite() throws Exception { commitOffset(FIRST_GROUP, 10L); diff --git a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagerTest.java b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagerTest.java index 1ada4f238a3..07e29b436e4 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagerTest.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagerTest.java @@ -25,7 +25,9 @@ import org.apache.fluss.metadata.TableBucket; import org.apache.fluss.metadata.TableInfo; import org.apache.fluss.record.TestingSchemaGetter; +import org.apache.fluss.row.compacted.CompactedRow; import org.apache.fluss.row.encode.ValueDecoder; +import org.apache.fluss.row.encode.ValueEncoder; import org.apache.fluss.rpc.protocol.Errors; import org.apache.fluss.server.coordinator.LakeCatalogDynamicLoader; import org.apache.fluss.server.coordinator.MetadataManager; @@ -39,6 +41,7 @@ import org.apache.fluss.server.replica.ReplicaTestBase; import org.apache.fluss.server.zk.data.LeaderAndIsr; import org.apache.fluss.server.zk.data.ZkVersion; +import org.apache.fluss.utils.ByteArraySlice; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -52,6 +55,7 @@ import java.time.Duration; import java.util.Arrays; import java.util.Collections; +import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; @@ -62,13 +66,14 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -/** Tests for consumer-group routing and local ownership checks. */ +/** Tests for consumer-group routing, local ownership checks, and management. */ class ConsumerGroupManagerTest extends ReplicaTestBase { private static final String GROUP_ID = "ownership-test"; private static final long OFFSETS_TABLE_ID = 100L; private static final int OTHER_SERVER_ID = TABLET_SERVER_ID + 1; private static final TableBucket SOURCE_BUCKET = new TableBucket(1L, 0); + private static final short SCHEMA_ID = 1; private LakeCatalogDynamicLoader lakeCatalogLoader; private MetadataManager metadataManager; @@ -253,6 +258,26 @@ void testFollowerRejectsCommitWithStaleCachedLocalOwner() throws Exception { assertThat(replica.getLogTablet().localLogEndOffset()).isEqualTo(logEndOffset); } + @Test + void testEncodeOffsetRowKeysUsesOffsetRows() { + GroupId groupId = GroupId.of("group-1"); + TableBucket first = new TableBucket(1L, 0); + TableBucket second = new TableBucket(1L, 1); + List keys = + groupManager.encodeOffsetRowKeys( + groupId, + Arrays.asList( + encodedGroupMetadata(groupId), + encodedOffset(groupId, first), + encodedOffset(groupId, second)), + valueDecoder()); + + assertThat(keys) + .containsExactly( + new ConsumerOffsetSchema().encodeOffsetKey(groupId, 1L, null, 0), + new ConsumerOffsetSchema().encodeOffsetKey(groupId, 1L, null, 1)); + } + private void cacheLeader(@Nullable Integer leaderId) { serverMetadataCache.updateTableMetadata( new TableMetadata( @@ -281,4 +306,32 @@ private void assertCommitResult(Errors expectedError) throws Exception { .succeedsWithin(Duration.ofSeconds(10)) .isEqualTo(Collections.singletonMap(SOURCE_BUCKET, expectedError)); } + + private static ValueDecoder valueDecoder() { + return ConsumerOffsetSchema.createValueDecoder( + new TestingSchemaGetter(SCHEMA_ID, ConsumerOffsetSchema.getTableSchema())); + } + + private static ByteArraySlice encodedGroupMetadata(GroupId groupId) { + return encodedRecord( + groupId, ConsumerOffsetSchema.GROUP_METADATA_RECORD_TYPE, new TableBucket(-1L, -1)); + } + + private static ByteArraySlice encodedOffset(GroupId groupId, TableBucket tableBucket) { + return encodedRecord(groupId, ConsumerOffsetSchema.OFFSET_COMMIT_RECORD_TYPE, tableBucket); + } + + private static ByteArraySlice encodedRecord( + GroupId groupId, int recordType, TableBucket tableBucket) { + CompactedRow row = + new ConsumerOffsetSchema() + .encodeOffsetRow( + recordType, + groupId, + tableBucket.getTableId(), + tableBucket.getPartitionId(), + tableBucket.getBucket(), + new ConsumerOffsetAndMetadata(-1L, "")); + return ByteArraySlice.wrap(ValueEncoder.encodeValue(SCHEMA_ID, row)); + } } diff --git a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchemaTest.java b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchemaTest.java index 3bfdb538d96..b44abdc9388 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchemaTest.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerOffsetSchemaTest.java @@ -68,13 +68,8 @@ void testSchemaMatchesFip() { } @Test - void testGroupMetadataPrefixAndKeyUseRecordTypeAndGroupId() { + void testGroupMetadataKeyMatchesRowKeyEncoding() { GroupId groupId = GroupId.of("my-group"); - KeyEncoder prefixEncoder = - KeyEncoder.ofBucketKeyEncoder( - ConsumerOffsetSchema.getTableSchema().getRowType(), - Arrays.asList("record_type", "group_id"), - null); KeyEncoder keyEncoder = KeyEncoder.ofBucketKeyEncoder( ConsumerOffsetSchema.getTableSchema().getRowType(), @@ -83,8 +78,6 @@ void testGroupMetadataPrefixAndKeyUseRecordTypeAndGroupId() { CompactedRow row = offsetSchema.encodeGroupMetadataRow(groupId); - assertThat(offsetSchema.encodeGroupMetadataPrefix(groupId)) - .isEqualTo(prefixEncoder.encodeKey(row)); assertThat(offsetSchema.encodeGroupMetadataKey(groupId)) .isEqualTo(keyEncoder.encodeKey(row)); } diff --git a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/GroupManagerManagementTest.java b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/GroupManagerManagementTest.java deleted file mode 100644 index 158574c6381..00000000000 --- a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/GroupManagerManagementTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to you under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.apache.fluss.server.tablet.consumer.group; - -import org.apache.fluss.metadata.GroupId; -import org.apache.fluss.metadata.TableBucket; -import org.apache.fluss.record.TestingSchemaGetter; -import org.apache.fluss.row.compacted.CompactedRow; -import org.apache.fluss.row.encode.ValueDecoder; -import org.apache.fluss.row.encode.ValueEncoder; -import org.apache.fluss.utils.ByteArraySlice; - -import org.junit.jupiter.api.Test; - -import java.util.Arrays; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; - -import static org.assertj.core.api.Assertions.assertThat; - -/** Tests for consumer-group management helpers. */ -class GroupManagerManagementTest { - - private static final short SCHEMA_ID = 1; - - @Test - void testPopulateGroupIdsDeduplicatesAndSorts() throws Exception { - Set groupIds = new TreeSet<>(); - ConsumerGroupManager.populateGroupIds( - Arrays.asList( - encodedGroupMetadata(GroupId.of("group-b")), - encodedGroupMetadata(GroupId.of("group-a")), - encodedGroupMetadata(GroupId.of("group-b")), - encodedOffset(GroupId.of("group-c"), new TableBucket(1L, 0))), - valueDecoder(), - groupIds); - - assertThat(groupIds).containsExactly("group-a", "group-b"); - } - - @Test - void testEncodeGroupRowKeysUsesMetadataRows() throws Exception { - GroupId groupId = GroupId.of("group-1"); - TableBucket offsetBucket = new TableBucket(1L, 0); - List keys = - ConsumerGroupManager.encodeGroupRowKeys( - groupId, - Arrays.asList( - encodedGroupMetadata(groupId), - encodedOffset(groupId, offsetBucket)), - valueDecoder()); - - assertThat(keys) - .containsExactly(new ConsumerOffsetSchema().encodeGroupMetadataKey(groupId)); - } - - @Test - void testEncodeOffsetRowKeysUsesOffsetRows() throws Exception { - GroupId groupId = GroupId.of("group-1"); - TableBucket first = new TableBucket(1L, 0); - TableBucket second = new TableBucket(1L, 1); - List keys = - ConsumerGroupManager.encodeOffsetRowKeys( - groupId, - Arrays.asList( - encodedGroupMetadata(groupId), - encodedOffset(groupId, first), - encodedOffset(groupId, second)), - valueDecoder()); - - assertThat(keys) - .containsExactly( - new ConsumerOffsetSchema().encodeOffsetKey(groupId, 1L, null, 0), - new ConsumerOffsetSchema().encodeOffsetKey(groupId, 1L, null, 1)); - } - - private static ValueDecoder valueDecoder() { - return ConsumerOffsetSchema.createValueDecoder( - new TestingSchemaGetter(SCHEMA_ID, ConsumerOffsetSchema.getTableSchema())); - } - - private static ByteArraySlice encodedGroupMetadata(GroupId groupId) { - return encodedRecord( - groupId, ConsumerOffsetSchema.GROUP_METADATA_RECORD_TYPE, new TableBucket(-1L, -1)); - } - - private static ByteArraySlice encodedOffset(GroupId groupId, TableBucket tableBucket) { - return encodedRecord(groupId, ConsumerOffsetSchema.OFFSET_COMMIT_RECORD_TYPE, tableBucket); - } - - private static ByteArraySlice encodedRecord( - GroupId groupId, int recordType, TableBucket tableBucket) { - CompactedRow row = - new ConsumerOffsetSchema() - .encodeOffsetRow( - recordType, - groupId, - tableBucket.getTableId(), - tableBucket.getPartitionId(), - tableBucket.getBucket(), - new ConsumerOffsetAndMetadata(-1L, "")); - return ByteArraySlice.wrap(ValueEncoder.encodeValue(SCHEMA_ID, row)); - } -} From 74d5d8127b70b5767352e517f90fcca777587993 Mon Sep 17 00:00:00 2001 From: Jark Wu Date: Mon, 16 Nov 2026 01:02:35 +0800 Subject: [PATCH 7/7] fix test Co-Authored-By: Codex AI-Contributed/Feature: 0/0 AI-Contributed/UT: 19/19 --- ...merGroupManagementAuthorizationITCase.java | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) diff --git a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagementAuthorizationITCase.java b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagementAuthorizationITCase.java index 2fceb78d9e5..0af9dc67de5 100644 --- a/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagementAuthorizationITCase.java +++ b/fluss-server/src/test/java/org/apache/fluss/server/tablet/consumer/group/ConsumerGroupManagementAuthorizationITCase.java @@ -42,12 +42,12 @@ import org.apache.fluss.rpc.messages.ListConsumerGroupsResponse; import org.apache.fluss.rpc.messages.PbCommitConsumerOffsetsResponseBucket; import org.apache.fluss.rpc.messages.PbCommitConsumerOffsetsResponseTable; +import org.apache.fluss.rpc.messages.PbDeletedGroup; import org.apache.fluss.rpc.messages.PbGetConsumerOffsetsResponseBucket; import org.apache.fluss.rpc.messages.PbGetConsumerOffsetsResponseTable; import org.apache.fluss.rpc.messages.PbListedGroup; import org.apache.fluss.rpc.metrics.TestingClientMetricGroup; import org.apache.fluss.rpc.netty.client.NettyClient; -import org.apache.fluss.rpc.protocol.Errors; import org.apache.fluss.security.acl.AccessControlEntry; import org.apache.fluss.security.acl.AclBinding; import org.apache.fluss.security.acl.FlussPrincipal; @@ -213,7 +213,7 @@ void testDeleteConsumerGroupsRemovesMetadataAndOffsets() throws Exception { } @Test - void testDeleteConsumerGroupsDistinguishesEmptyAndMissingGroups() throws Exception { + void testDeleteConsumerGroupsSucceedsForEmptyAndMissingGroups() throws Exception { commitOffset(FIRST_GROUP, 10L); grant(WRITE, Resource.group(FIRST_GROUP)); grant(DROP, Resource.group(FIRST_GROUP)); @@ -231,18 +231,9 @@ void testDeleteConsumerGroupsDistinguishesEmptyAndMissingGroups() throws Excepti .get(); assertThat(response.getGroupsList()) - .hasSize(2) - .anySatisfy( - group -> { - assertThat(group.getGroupId()).isEqualTo(FIRST_GROUP); - assertThat(group.hasErrorCode()).isFalse(); - }) - .anySatisfy( - group -> { - assertThat(group.getGroupId()).isEqualTo(SECOND_GROUP); - assertThat(group.getErrorCode()) - .isEqualTo(Errors.CONSUMER_GROUP_ID_NOT_FOUND.code()); - }); + .allSatisfy(group -> assertThat(group.hasErrorCode()).isFalse()) + .extracting(PbDeletedGroup::getGroupId) + .containsExactlyInAnyOrder(FIRST_GROUP, SECOND_GROUP); assertThat(listGroups()).isEmpty(); }