Skip to content

[Improve] Calculate the sticky key hash by using keyBytes instead of Base64 encoded key #17680

Closed

Description

@syhily

Search before asking

  • I searched in the issues and found nothing similar.

Motivation

The method peekStickyKey in Commands.java is used for acquiring sticky key bytes. But I think the implementation of this method could be wrong.

public static byte[] peekStickyKey(ByteBuf metadataAndPayload, String topic, String subscription) {
    try {
        int readerIdx = metadataAndPayload.readerIndex();
        MessageMetadata metadata = Commands.parseMessageMetadata(metadataAndPayload);
        metadataAndPayload.readerIndex(readerIdx);
        if (metadata.hasOrderingKey()) {
            return metadata.getOrderingKey();
        } else if (metadata.hasPartitionKey()) {
            return metadata.getPartitionKey().getBytes(StandardCharsets.UTF_8);
        }
    } catch (Throwable t) {
        log.error("[{}] [{}] Failed to peek sticky key from the message metadata", topic, subscription, t);
    }
    return Commands.NONE_KEY;
}

The Partition Key in metadata could be defined by using TypedMessageBuilder#setKeyBytes or TypedMessageBuilder#setKey. The key bytes will be encoded into a Base64 string. So I think we can just decode the key bytes instead of String#getBytes(StandardCharsets.UTF_8).

Solution

public static byte[] peekStickyKey(ByteBuf metadataAndPayload, String topic, String subscription) {
    try {
        int readerIdx = metadataAndPayload.readerIndex();
        MessageMetadata metadata = Commands.parseMessageMetadata(metadataAndPayload);
        metadataAndPayload.readerIndex(readerIdx);
        if (metadata.hasOrderingKey()) {
            return metadata.getOrderingKey();
        } else if (metadata.hasPartitionKey()) {
            String partitionKey = metadata.getPartitionKey();
            if (metadata.isPartitionKeyB64Encoded()) {
                return Base64.getDecoder().decode(partitionKey);
            } else {
                return partitionKey.getBytes(StandardCharsets.UTF_8);
            }
        }
    } catch (Throwable t) {
        log.error("[{}] [{}] Failed to peek sticky key from the message metadata", topic, subscription, t);
    }
    return Commands.NONE_KEY;
}

Alternatives

No response

Anything else?

No response

Are you willing to submit a PR?

  • I'm willing to submit a PR!

Activity

  1. syhily commented on Sep 15, 2022

    @syhily
    Author

    @codelipenghui Can you help me check this?

  2. Technoboy- commented on Sep 16, 2022

    @Technoboy-
    Contributor

    I think you are right.

  3. self-assigned this
    on Sep 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions