Skip to content

Commit

Permalink
increase coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
AmrSaber committed Dec 7, 2024
1 parent cb6c190 commit 6b6cf9f
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 15 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
node_modules
.vscode
dist
dist
coverage
24 changes: 10 additions & 14 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,28 +141,24 @@ export async function tryLock(
const release: ReleaseFunc = async function () {
if (released) return;

if (!isRedisClient(redis)) {
await redis.eval(releaseScript, {
keys: [lockKey, REDIS_RELEASES_CHANNEL],
arguments: [lockValue],
});
const evalParams = {
keys: [lockKey, REDIS_RELEASES_CHANNEL],
arguments: [lockValue],
};

if (!isRedisClient(redis)) {
await redis.eval(releaseScript, evalParams);
released = true;
return;
}

// If it's redis client, cache the script and use its SHA
if (scriptHash == null) scriptHash = await redis.scriptLoad(releaseScript);

await redis
.evalSha(scriptHash, {
keys: [lockKey, REDIS_RELEASES_CHANNEL],
arguments: [lockValue],
})
.catch((err: Error) => {
if (err.message.includes('NOSCRIPT')) scriptHash = null; // Signal script flushed
else throw err;
});
await redis.evalSha(scriptHash, evalParams).catch((err: Error) => {
if (err.message.includes('NOSCRIPT')) scriptHash = null; // Signal script flushed
else throw err;
});

if (scriptHash == null) await release(); // If script flushed, try again
released = true;
Expand Down
16 changes: 16 additions & 0 deletions unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,22 @@ describe('Lock tests', () => {
expect(release.fencingToken).toEqual(-1);
});

test('release works without script cache', async () => {
const scriptLoad = redis.scriptLoad;
// @ts-ignore
redis.scriptLoad = null;

let [hasLock, release] = await tryLock(redis, lockName);
expect(hasLock).toEqual(true);

await release();

[hasLock, release] = await tryLock(redis, lockName);
expect(hasLock).toEqual(true);

redis.scriptLoad = scriptLoad;
});

test('it issues monotonic fencing tokens', async () => {
let lastToken: number | null = null;

Expand Down

0 comments on commit 6b6cf9f

Please sign in to comment.