Skip to content

Commit c06d945

Browse files
committed
test: complete Redis locking and fencing coverage
1 parent 6e8993c commit c06d945

10 files changed

Lines changed: 668 additions & 351 deletions

File tree

‎docs/PLAN.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ If two processes insert concurrently, Postgres accepts one insert and rejects th
129129

130130
### Redis distributed lock and fencing
131131

132-
First, implement a Redis lease:
132+
First, implement a Redis lock:
133133

134134
```text
135135
SET lock:<key> <owner-token> NX PX <ttl>
@@ -141,7 +141,7 @@ The owner-token check makes release safe, but it does not make an expired owner
141141

142142
```text
143143
A acquires the lock
144-
A pauses until its lease expires
144+
A pauses until its lock expires
145145
B acquires the lock and writes
146146
A resumes and tries to write
147147
```
@@ -150,14 +150,14 @@ A must not be allowed to write after B. Checking the token during release only s
150150

151151
The owner token above is a random identity: it answers "is this still my lock?" A fencing token is different. It is an increasing number that records the order in which owners acquired the lock.
152152

153-
Postgres remembers the highest fencing token it has accepted and rejects a write carrying an older token. A resumed owner can therefore be recognized as stale even after its Redis lease expires.
153+
Postgres remembers the highest fencing token it has accepted and rejects a write carrying an older token. A resumed owner can therefore be recognized as stale even after its Redis lock expires.
154154

155155
Fencing and optimistic locking both use conditional database writes, but their values mean different things:
156156

157157
- An optimistic-lock version is read from the database row. The write succeeds only if that row still has the same version.
158158
- A fencing token represents the order in which owners acquired the lock. The database rejects an owner older than one it has already accepted.
159159

160-
Using `UPDATE ... WHERE version = $expected` alongside Redis can still be a valid design, but it combines the Redis lease with optimistic locking. It is not, by itself, a fencing-token implementation.
160+
Using `UPDATE ... WHERE version = $expected` alongside Redis can still be a valid design, but it combines the Redis lock with optimistic locking. It is not, by itself, a fencing-token implementation.
161161

162162
## Test-harness decisions
163163

‎docs/comparison.md‎

Lines changed: 113 additions & 284 deletions
Large diffs are not rendered by default.

‎docs/tests-overview.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ DB constraint ✓ ✓
5858

5959
That will make the limitation of an in-memory mutex extremely concrete. The mutex isn’t defective; its synchronization boundary is simply the Node process.
6060

61-
A lease-only Redis lock can pass ordinary contention tests across processes while its TTL remains valid, but it fails the expired-holder scenario shown below. The checkmarks therefore apply to Redis combined with storage-layer validation, such as fencing.
61+
A lock-only Redis lock can pass ordinary contention tests across processes while its TTL remains valid, but it fails the expired-holder scenario shown below. The checkmarks therefore apply to Redis combined with storage-layer validation, such as fencing.
6262

6363
## Redis progression
6464

@@ -69,7 +69,7 @@ token-safe release
6969
↓
7070
"so distributed locking is solved?"
7171
↓
72-
NO — lease expires while A is paused
72+
NO — lock expires while A is paused
7373
↓
7474
B obtains lock
7575
↓
@@ -111,7 +111,7 @@ test/
111111
redis-fencing/
112112
contract.test.ts
113113
lock-ownership.test.ts
114-
lease-expiry.test.ts
114+
lock-expiry.test.ts
115115
fencing.test.ts
116116
topology.test.ts
117117
@@ -134,6 +134,6 @@ The worker and parent-side IPC barrier are shared infrastructure: build them
134134
for the keyed-mutex topology test, then reuse them for the remaining strategy
135135
directories.
136136

137-
Redis has additional files because acquiring and safely releasing a lease,
137+
Redis has additional files because acquiring and safely releasing a lock,
138138
demonstrating expiry failure, and rejecting stale writers through fencing are
139139
separate claims.

‎src/strategies/redis-fencing.ts‎

Lines changed: 44 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@ import type { Redis } from "ioredis";
33
import type { Pool } from "pg";
44
import type { Checkout } from "../checkout.ts";
55

6-
const DEFAULT_LEASE_TTL_MS = 5_000;
6+
const DEFAULT_LOCK_TTL_MS = 5_000;
77

8-
const ACQUIRE_LEASE_SCRIPT = `
8+
const ACQUIRE_LOCK_SCRIPT = `
99
local acquired = redis.call(
1010
"SET",
1111
KEYS[1],
@@ -28,33 +28,33 @@ const ACQUIRE_LEASE_SCRIPT = `
2828
return fencingToken
2929
`;
3030

31-
const RELEASE_LEASE_SCRIPT = `
31+
const RELEASE_LOCK_SCRIPT = `
3232
if redis.call("GET", KEYS[1]) == ARGV[1] then
3333
return redis.call("DEL", KEYS[1])
3434
end
3535
3636
return 0
3737
`;
3838

39-
export interface RedisLease {
39+
export interface RedisLock {
4040
ownerToken: string;
4141
fencingToken: number;
4242
}
4343

44-
export interface RedisLeaseOptions {
44+
export interface RedisLockOptions {
4545
lockNamespace: string;
4646
resourceId: number;
4747
ttlMs: number;
4848
}
4949

5050
export interface RedisFencingCheckoutOptions {
5151
lockNamespace: string;
52-
leaseTtlMs?: number;
53-
afterLeaseAcquired?(lease: Readonly<RedisLease>): Promise<void>;
52+
lockTtlMs?: number;
53+
afterLockAcquired?(lock: Readonly<RedisLock>): Promise<void>;
5454
}
5555

56-
interface RedisLeaseKeys {
57-
leaseKey: string;
56+
interface RedisLockKeys {
57+
lockKey: string;
5858
fencingTokenKey: string;
5959
}
6060

@@ -64,58 +64,58 @@ function assertLockNamespace(lockNamespace: string): void {
6464
}
6565
}
6666

67-
function assertLeaseTtl(ttlMs: number): void {
67+
function assertLockTtl(ttlMs: number): void {
6868
if (!Number.isSafeInteger(ttlMs) || ttlMs <= 0) {
69-
throw new RangeError("leaseTtlMs must be a positive safe integer");
69+
throw new RangeError("lockTtlMs must be a positive safe integer");
7070
}
7171
}
7272

7373
function resourceKeyPrefix(lockNamespace: string): string {
7474
return `redis-fencing:{${lockNamespace}:locker:`;
7575
}
7676

77-
/** Match every lease and persistent fencing-token key in one namespace. */
77+
/** Match every lock and persistent fencing-token key in one namespace. */
7878
export function redisFencingNamespaceKeyPattern(
7979
lockNamespace: string,
8080
): string {
8181
assertLockNamespace(lockNamespace);
8282
return `${resourceKeyPrefix(lockNamespace)}*}:*`;
8383
}
8484

85-
function leaseKeys(
85+
function lockKeys(
8686
lockNamespace: string,
8787
resourceId: number,
88-
): RedisLeaseKeys {
88+
): RedisLockKeys {
8989
// The braces form a Redis Cluster hash tag. Both keys therefore occupy the
9090
// same hash slot, which allows the acquisition script to use them together.
9191
const resource = `${resourceKeyPrefix(lockNamespace)}${resourceId}}`;
9292
return {
93-
leaseKey: `${resource}:lease`,
93+
lockKey: `${resource}:lock`,
9494
fencingTokenKey: `${resource}:token`,
9595
};
9696
}
9797

9898
/**
99-
* Attempt to acquire one expiring Redis lease and allocate its fencing token.
100-
* A null result means another owner currently holds the lease.
99+
* Attempt to acquire one expiring Redis lock and allocate its fencing token.
100+
* A null result means another owner currently holds the lock.
101101
*/
102-
export async function acquireRedisLease(
102+
export async function acquireRedisLock(
103103
redis: Redis,
104-
options: RedisLeaseOptions,
105-
): Promise<RedisLease | null> {
104+
options: RedisLockOptions,
105+
): Promise<RedisLock | null> {
106106
assertLockNamespace(options.lockNamespace);
107-
assertLeaseTtl(options.ttlMs);
107+
assertLockTtl(options.ttlMs);
108108

109109
if (!Number.isSafeInteger(options.resourceId)) {
110110
throw new RangeError("resourceId must be a safe integer");
111111
}
112112

113113
const ownerToken = randomUUID();
114-
const keys = leaseKeys(options.lockNamespace, options.resourceId);
114+
const keys = lockKeys(options.lockNamespace, options.resourceId);
115115
const result: unknown = await redis.eval(
116-
ACQUIRE_LEASE_SCRIPT,
116+
ACQUIRE_LOCK_SCRIPT,
117117
2,
118-
keys.leaseKey,
118+
keys.lockKey,
119119
keys.fencingTokenKey,
120120
ownerToken,
121121
options.ttlMs,
@@ -136,30 +136,30 @@ export async function acquireRedisLease(
136136
}
137137

138138
/**
139-
* Release a lease only if Redis still contains this owner's random token.
139+
* Release a lock only if Redis still contains this owner's random token.
140140
* The comparison and deletion share one Lua script so they are atomic.
141141
*/
142-
export async function releaseRedisLease(
142+
export async function releaseRedisLock(
143143
redis: Redis,
144-
options: Pick<RedisLeaseOptions, "lockNamespace" | "resourceId">,
145-
lease: RedisLease,
144+
options: Pick<RedisLockOptions, "lockNamespace" | "resourceId">,
145+
lock: RedisLock,
146146
): Promise<boolean> {
147147
assertLockNamespace(options.lockNamespace);
148148
if (!Number.isSafeInteger(options.resourceId)) {
149149
throw new RangeError("resourceId must be a safe integer");
150150
}
151151

152-
const keys = leaseKeys(options.lockNamespace, options.resourceId);
152+
const keys = lockKeys(options.lockNamespace, options.resourceId);
153153
const result: unknown = await redis.eval(
154-
RELEASE_LEASE_SCRIPT,
154+
RELEASE_LOCK_SCRIPT,
155155
1,
156-
keys.leaseKey,
157-
lease.ownerToken,
156+
keys.lockKey,
157+
lock.ownerToken,
158158
);
159159

160160
if (result !== 0 && result !== 1) {
161161
throw new Error(
162-
`Redis returned an invalid lease-release result: ${String(result)}`,
162+
`Redis returned an invalid lock-release result: ${String(result)}`,
163163
);
164164
}
165165

@@ -172,20 +172,20 @@ export function createRedisFencingCheckout(
172172
options: RedisFencingCheckoutOptions,
173173
): Checkout {
174174
assertLockNamespace(options.lockNamespace);
175-
const leaseTtlMs = options.leaseTtlMs ?? DEFAULT_LEASE_TTL_MS;
176-
assertLeaseTtl(leaseTtlMs);
175+
const lockTtlMs = options.lockTtlMs ?? DEFAULT_LOCK_TTL_MS;
176+
assertLockTtl(lockTtlMs);
177177

178178
return async (userId, lockerId) => {
179-
const leaseOptions = {
179+
const lockOptions = {
180180
lockNamespace: options.lockNamespace,
181181
resourceId: lockerId,
182-
ttlMs: leaseTtlMs,
182+
ttlMs: lockTtlMs,
183183
};
184-
const lease = await acquireRedisLease(redis, leaseOptions);
185-
if (lease === null) return { outcome: "unavailable" };
184+
const lock = await acquireRedisLock(redis, lockOptions);
185+
if (lock === null) return { outcome: "unavailable" };
186186

187187
try {
188-
await options.afterLeaseAcquired?.(lease);
188+
await options.afterLockAcquired?.(lock);
189189

190190
const client = await pool.connect();
191191
let transactionOpen = false;
@@ -203,7 +203,7 @@ export function createRedisFencingCheckout(
203203
SET last_fencing_token = $2
204204
WHERE id = $1 AND last_fencing_token < $2
205205
`,
206-
[lockerId, lease.fencingToken],
206+
[lockerId, lock.fencingToken],
207207
);
208208

209209
if (accepted.rowCount === 0) {
@@ -262,9 +262,9 @@ export function createRedisFencingCheckout(
262262
client.release();
263263
}
264264
} finally {
265-
// If the TTL elapsed or another owner replaced this lease, the Lua
266-
// script returns false and deliberately leaves the newer lease intact.
267-
await releaseRedisLease(redis, leaseOptions, lease);
265+
// If the TTL elapsed or another owner replaced this lock, the Lua
266+
// script returns false and deliberately leaves the newer lock intact.
267+
await releaseRedisLock(redis, lockOptions, lock);
268268
}
269269
};
270270
}

0 commit comments

Comments
 (0)