Skip to content

EVAL/EVALSHA | Cluster mode | Wrong node infer #2811

Open
@chapost1

Description

@chapost1

Description

EVAL && EVALSHA commands infers wrong node by key hash slot on cluster mode.

Usage in abstract:

const sha = /** sha of script that get some key */
const keys = ['1key']
const args = ['arg1', 'arg2']
await cluster.evalSha(sha, {
  keys,
  arguments: args
})

As of my understanding each command uses the FIRST_KEY_INDEX function that's defined in it's module and then based on that the node is inferred based on the hash slot of first key.

On file:

node_modules/@redis/client/dist/lib/cluster/index.js

There is generic function that is used to extract firstKey before inferring client pre command or after MOVE error.

    static extractFirstKey(command, originalArgs, redisArgs) {
        if (command.FIRST_KEY_INDEX === undefined) {
            return undefined;
        }
        else if (typeof command.FIRST_KEY_INDEX === 'number') {
            return redisArgs[command.FIRST_KEY_INDEX];
        }
        return command.FIRST_KEY_INDEX(...originalArgs);
    }

So, in addition to that, the EVAL && EVALSHA modules has this declaration for the function to use.

exports.FIRST_KEY_INDEX = generic_transformers_1.evalFirstKeyIndex;

While the function is:

function evalFirstKeyIndex(options) {
    return options?.keys?.[0];
}

So, in essence what happens is that the evalFirstKeyIndex gets options as a list and it does not having a keys object in it. maybe the second item in the list will have. as in the scope of the extractFirstKey fn the originalArgs is actualy the input of original evalSha call.

It causes the client to get undefined as firstKey so providing firstKey has no effect at all and then when running lua scripts you cannot provide hash keys to begin with which might cause unexpected errors and unresolvable failures.

I solved it in a dirty way just as a POC, I modified in EVALSHA module which is located in:

node_modules/@redis/client/dist/lib/commands/EVALSHA.js

This change:

// exports.FIRST_KEY_INDEX = generic_transformers_1.evalFirstKeyIndex;

// custom function for EVALSHA input...
function evalFirstKeyIndex(...args) {
    if (args && args.length > 0) {
        const options = args[1]
        if (options.keys && options.keys.length > 0) {
            return options.keys[0]
        }
    }
    return undefined
}
exports.FIRST_KEY_INDEX = evalFirstKeyIndex;

And it seem to solve the issue

Node.js Version

v20.11.0

Redis Server Version

7.2.2

Node Redis Version

redis@4.6.7

Platform

Linux

Logs

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions