Commit 932273f2 authored by nanahira's avatar nanahira

support stacked lock

parent 00e990df
...@@ -3,7 +3,7 @@ import { Settings } from '@nanahira/redlock'; ...@@ -3,7 +3,7 @@ import { Settings } from '@nanahira/redlock';
export type RedisDriverOptions = RedisOptions & { export type RedisDriverOptions = RedisOptions & {
uri?: string; uri?: string;
lock?: Settings & { duration?: number; prefix?: string }; lock?: Settings & { duration?: number; prefix?: string; stacked?: boolean };
queueKey?: string; queueKey?: string;
}; };
......
...@@ -3,6 +3,7 @@ import Redis from 'ioredis'; ...@@ -3,6 +3,7 @@ import Redis from 'ioredis';
import Redlock from '@nanahira/redlock'; import Redlock from '@nanahira/redlock';
import { Awaitable, RedisDriverOptions } from '../def'; import { Awaitable, RedisDriverOptions } from '../def';
import { createPool } from 'generic-pool'; import { createPool } from 'generic-pool';
import BetterLock from 'better-lock';
export class RedisDriver extends BaseDriver { export class RedisDriver extends BaseDriver {
async createRedisClient() { async createRedisClient() {
...@@ -94,8 +95,11 @@ export class RedisDriver extends BaseDriver { ...@@ -94,8 +95,11 @@ export class RedisDriver extends BaseDriver {
await this.pool.use((r) => r.redis.del(keys)); await this.pool.use((r) => r.redis.del(keys));
} }
private betterLock = new BetterLock();
override async lock<R>(keys: string[], cb: () => Promise<R>): Promise<R> { override async lock<R>(keys: string[], cb: () => Promise<R>): Promise<R> {
return this.useTempRedisClient(async (redis) => { const run = () =>
this.useTempRedisClient(async (redis) => {
const redlock = new Redlock([redis], this.options.lock); const redlock = new Redlock([redis], this.options.lock);
return redlock.using( return redlock.using(
keys.map((key) => `${this.options.lock?.prefix || '_lock'}:${key}`), keys.map((key) => `${this.options.lock?.prefix || '_lock'}:${key}`),
...@@ -103,6 +107,11 @@ export class RedisDriver extends BaseDriver { ...@@ -103,6 +107,11 @@ export class RedisDriver extends BaseDriver {
cb, cb,
); );
}); });
if (this.options?.lock?.stacked) {
return this.betterLock.acquire(keys, run);
} else {
return run();
}
} }
override async isFree(keys: string[]): Promise<boolean> { override async isFree(keys: string[]): Promise<boolean> {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment