Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: Redis race conditions with .set, .delete. and .clear when useRedisSets=true #881

Merged
merged 2 commits into from
Sep 17, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 29 additions & 9 deletions packages/redis/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,22 +74,37 @@

key = this._getKeyName(key);

if (typeof ttl === 'number') {
await this.redis.set(key, value, 'PX', ttl);
} else {
await this.redis.set(key, value);
}
const set = async (redis: any) => {
if (typeof ttl === 'number') {
await redis.set(key, value, 'PX', ttl);
} else {
await redis.set(key, value);
}
};

if (this.opts.useRedisSets) {
await this.redis.sadd(this._getNamespace(), key);
const trx = await this.redis.multi();
await set(trx);
await trx.sadd(this._getNamespace(), key);
await trx.exec();
} else {
await set(this.redis);
}
}

async delete(key: string): DeleteOutput {
key = this._getKeyName(key);
const items: number = await this.redis.del(key);
let items = 0;
const del = async (redis: any) => redis.del(key);

if (this.opts.useRedisSets) {
await this.redis.srem(this._getNamespace(), key);
const trx = this.redis.multi();
await del(trx);
await trx.srem(this._getNamespace(), key);
const r = await trx.exec();
items = r[0][1];
} else {
items = await del(this.redis);

Check warning on line 107 in packages/redis/src/index.ts

View check run for this annotation

Codecov / codecov/patch

packages/redis/src/index.ts#L107

Added line #L107 was not covered by tests
}

return items > 0;
Expand All @@ -105,7 +120,12 @@
async clear(): ClearOutput {
if (this.opts.useRedisSets) {
const keys: string[] = await this.redis.smembers(this._getNamespace());
await this.redis.del([...keys, this._getNamespace()]);
if (keys.length > 0) {
await Promise.all([
this.redis.del([...keys]),
this.redis.srem(this._getNamespace(), [...keys]),
]);
}
} else {
const pattern = 'sets:*';
const keys: string[] = await this.redis.keys(pattern);
Expand Down