diff --git a/src/module.c b/src/module.c index 1acda2e7b710f506a96817da9ea3db5a576965ab..ccda683e8e29fd70fd9aa558cc53b392433b228a 100644 --- a/src/module.c +++ b/src/module.c @@ -856,6 +856,22 @@ int RM_ReplicateVerbatim(RedisModuleCtx *ctx) { * DB and Key APIs -- Generic API * -------------------------------------------------------------------------- */ +/* Return the ID of the current client calling the currently active module + * command. The returned ID has a few guarantees: + * + * 1. The ID is different for each different client, so if the same client + * executes a module command multiple times, it can be recognized as + * having the same ID, otherwise the ID will be different. + * 2. The ID increases monotonically. Clients connecting to the server later + * are guaranteed to get IDs greater than any past ID previously seen. + * + * Valid IDs are from 1 to 2^64-1. If 0 is returned it means there is no way + * to fetch the ID in the context the function was currently called. */ +unsigned long long RM_GetClientId(RedisModuleCtx *ctx) { + if (ctx->client == NULL) return 0; + return ctx->client->id; +} + /* Return the currently selected DB. */ int RM_GetSelectedDb(RedisModuleCtx *ctx) { return ctx->client->db->id; @@ -2270,6 +2286,7 @@ void moduleRegisterCoreAPI(void) { REGISTER_API(HashGet); REGISTER_API(IsKeysPositionRequest); REGISTER_API(KeyAtPos); + REGISTER_API(GetClientId); } /* Global initialization at Redis startup. */ diff --git a/src/redismodule.h b/src/redismodule.h index d23f8cbc48a806032257cff1a57edf1eed09cf2c..e54825dc27f5439c235a0bb68560b83bb7e43765 100644 --- a/src/redismodule.h +++ b/src/redismodule.h @@ -149,6 +149,7 @@ int REDISMODULE_API_FUNC(RedisModule_HashSet)(RedisModuleKey *key, int flags, .. int REDISMODULE_API_FUNC(RedisModule_HashGet)(RedisModuleKey *key, int flags, ...); int REDISMODULE_API_FUNC(RedisModule_IsKeysPositionRequest)(RedisModuleCtx *ctx); void REDISMODULE_API_FUNC(RedisModule_KeyAtPos)(RedisModuleCtx *ctx, int pos); +unsigned long long REDISMODULE_API_FUNC(RedisModule_GetClientId)(RedisModuleCtx *ctx); /* This is included inline inside each Redis module. */ static int RedisModule_Init(RedisModuleCtx *ctx, const char *name, int ver, int apiver) { @@ -217,6 +218,7 @@ static int RedisModule_Init(RedisModuleCtx *ctx, const char *name, int ver, int REDISMODULE_GET_API(HashGet); REDISMODULE_GET_API(IsKeysPositionRequest); REDISMODULE_GET_API(KeyAtPos); + REDISMODULE_GET_API(GetClientId); RedisModule_SetModuleAttribs(ctx,name,ver,apiver); return REDISMODULE_OK;