Skip to content

Commit 742cd0d

Browse files
authored
feat(publisher, lock, bun)!: align the Redis extension surface and lock options (#2529)
Pre-stable API cleanup for the publisher and lock helpers. ## Publisher - `BaseRedisPublisher`'s protected `eventPrefix` is now `keyPrefix`, matching lock and ratelimit. - `xTrimExactness` is `private` instead of `protected`. It is a test hook. - The `subscribe` JSDoc example now awaits the subscription and the unsubscribe call. ## Lock - Added `RedisLockerOptions`, `UpstashLockerOptions` and `experimental_BunRedisLockerOptions`. - The `lock` middleware accepts an `error` option, like `ratelimit`. The default is still `CONFLICT`. - `MemoryLocker` now requires `ttl`, like every other locker. ## Breaking - Subclasses of `BaseRedisPublisher` must rename `eventPrefix` to `keyPrefix` and can no longer read `xTrimExactness`. - `new MemoryLocker()` without `ttl` no longer compiles. ## Notes for review - The default Redis `prefix` stays `''`. The first commit changed it and the second reverts that, so squash on merge. - Requiring `ttl` in `MemoryLocker` is for consistency only. A memory lock dies with its process, so it could stay optional. - Not run locally: the Bun test suite and the live Redis/Upstash integration tests.
1 parent aa2aa65 commit 742cd0d

18 files changed

Lines changed: 137 additions & 67 deletions

File tree

‎apps/content/docs/helpers/lock.mdx‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ import { MemoryLocker } from '@orpc/experimental-lock/memory'
3030
declare function generateReport(id: string): Promise<{ url: string }>
3131
declare const cache: { get: (key: string) => Promise<{ url: string } | undefined> }
3232
// ---cut---
33-
const locker = new MemoryLocker()
33+
const locker = new MemoryLocker({ ttl: 30_000 })
3434

3535
const report = await locker.lock('report:123', async ({ waited }) => {
3636
if (waited) {
@@ -48,8 +48,8 @@ const report = await locker.lock('report:123', async ({ waited }) => {
4848

4949
### Options
5050

51-
- `ttl`: how long the lock is held before it expires automatically, in milliseconds. Guards against holders that never release the lock. Each adapter has its own default.
52-
- `timeout`: how long to wait for the lock to become available, in milliseconds. `lock` rejects with a `LockTimeoutError` once it elapses.
51+
- `ttl`: how long the lock is held before it expires automatically, in milliseconds. Guards against holders that never release the lock. Defaults to the adapter's `ttl`.
52+
- `timeout`: how long to wait for the lock to become available, in milliseconds. `lock` rejects with a `LockTimeoutError` once it elapses. Defaults to the adapter's `timeout`.
5353
- `signal`: stops waiting early and rejects with the abort reason. Has no effect once the lock is acquired.
5454

5555
```ts
@@ -60,6 +60,10 @@ await locker.lock('report:123', () => generateReport('123'), {
6060
})
6161
```
6262

63+
:::info
64+
Every adapter requires a `ttl`, since the right value depends on how long your work takes.
65+
:::
66+
6367
## Lock Middleware
6468

6569
The `lock` helper creates middleware that runs [procedures](/docs/procedure) under a lock, so that calls sharing the same key never run concurrently. When the lock cannot be acquired before the timeout elapses, the procedure rejects with a `CONFLICT` error. The request `signal` is forwarded, so a call stops waiting as soon as the client disconnects.
@@ -98,11 +102,24 @@ const procedure = os
98102
return await generateReport(input.id)
99103
})
100104

101-
const locker = new MemoryLocker()
105+
const locker = new MemoryLocker({ ttl: 30_000 })
102106

103107
const result = await call(procedure, { id: '123' }, { context: { locker } })
104108
```
105109

110+
:::tip[Custom Error]
111+
Use `error` to throw your own error instead of `CONFLICT`. A custom code responds with `400` unless you map it in [`errorStatusMap`](/docs/rpc/handler#custom-error-response), and is [defined](/docs/error-handling#orpcerror-compatibility) when its `code` and `data` match an error the procedure declares.
112+
113+
```ts
114+
lock({
115+
locker,
116+
key,
117+
error: (error) => new ORPCError('LOCKED', { data: { key: error.key } }),
118+
})
119+
```
120+
121+
:::
122+
106123
:::warning[Streaming Procedures]
107124
The lock middleware does not support streaming responses, such as procedures that return an [AsyncIteratorObject](/docs/async-iterator-object) (for example `async function*` handlers) or a [`ReadableStream<Uint8Array>`](/docs/binary-data#readablestreamuint8array). The lock is released once the handler returns the stream, so the work the stream does while it is consumed, such as the body of an `async function*` handler, runs without the lock. Streams sharing a key can then run concurrently. Nested calls made from inside the stream with the same context, `locker`, and `key` also skip locking through deduplication, even though no lock is held.
108125
:::
@@ -124,8 +141,6 @@ const locker = new MemoryLocker({
124141
/**
125142
* How long a lock is held before it expires automatically, in milliseconds.
126143
* Can be overridden per call.
127-
*
128-
* @default undefined (held until released)
129144
*/
130145
ttl: 30_000,
131146

‎packages/bun/src/redis-lock.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import type { BaseRedisLockerOptions } from '@orpc/experimental-lock/base-redis'
22
import { BaseRedisLocker } from '@orpc/experimental-lock/base-redis'
33
import type { RedisClient } from 'bun'
44

5+
export interface experimental_BunRedisLockerOptions extends BaseRedisLockerOptions {}
6+
57
/**
68
* Locker adapter for Bun's built-in Redis client. Acquires locks with `SET NX PX`
79
* and releases them atomically with a Lua script. It shares locks with `RedisLocker`.
@@ -11,7 +13,7 @@ import type { RedisClient } from 'bun'
1113
export class experimental_BunRedisLocker extends BaseRedisLocker {
1214
constructor(
1315
private readonly redis: RedisClient,
14-
private readonly options: BaseRedisLockerOptions,
16+
private readonly options: experimental_BunRedisLockerOptions,
1517
) {
1618
super(options)
1719
}

‎packages/bun/src/redis-publisher.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ export class BunRedisPublisher<T extends Record<string, object>> extends BaseRed
5151
prefix(prefix: string): BunRedisPublisher<T> {
5252
const publisher = new BunRedisPublisher<T>(this.redis, {
5353
...this.options,
54-
prefix: `${this.eventPrefix}${prefix}`,
54+
prefix: `${this.keyPrefix}${prefix}`,
5555
})
5656

5757
// Share the lazily created subscriber, which reports its errors to `onErrors` of this publisher.

‎packages/lock/src/adapters/memory.test.ts‎

Lines changed: 12 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { MemoryLocker } from './memory'
55

66
describe('memoryLocker', () => {
77
it('runs the callback right away when the lock is free and releases it afterwards', async () => {
8-
const locker = new MemoryLocker()
8+
const locker = new MemoryLocker({ ttl: 60_000 })
99
const fn = vi.fn(() => 'ok')
1010

1111
await expect(locker.lock('key', fn)).resolves.toBe('ok')
@@ -15,7 +15,7 @@ describe('memoryLocker', () => {
1515
})
1616

1717
it('serves waiters in order once the holder releases', async () => {
18-
const locker = new MemoryLocker()
18+
const locker = new MemoryLocker({ ttl: 60_000 })
1919
const { promise: release, resolve } = promiseWithResolvers<void>()
2020
const order: string[] = []
2121

@@ -44,7 +44,7 @@ describe('memoryLocker', () => {
4444
})
4545

4646
it('tracks locks independently per key', async () => {
47-
const locker = new MemoryLocker()
47+
const locker = new MemoryLocker({ ttl: 60_000 })
4848
const { promise: release, resolve } = promiseWithResolvers<void>()
4949
const holder = locker.lock('alice', () => release)
5050
const fn = vi.fn(() => 'bob')
@@ -57,7 +57,7 @@ describe('memoryLocker', () => {
5757
})
5858

5959
it('releases the lock when the callback throws', async () => {
60-
const locker = new MemoryLocker()
60+
const locker = new MemoryLocker({ ttl: 60_000 })
6161

6262
await expect(
6363
locker.lock('key', () => {
@@ -69,7 +69,7 @@ describe('memoryLocker', () => {
6969
})
7070

7171
it('never runs callbacks for the same key concurrently', async () => {
72-
const locker = new MemoryLocker()
72+
const locker = new MemoryLocker({ ttl: 60_000 })
7373
let active = 0
7474
let maxActive = 0
7575
let count = 0
@@ -101,7 +101,7 @@ describe('memoryLocker', () => {
101101
})
102102

103103
it('rejects with LockTimeoutError when the lock is not released in time', async () => {
104-
const locker = new MemoryLocker({ timeout: 1000 })
104+
const locker = new MemoryLocker({ ttl: 60_000, timeout: 1000 })
105105
const { promise: release, resolve } = promiseWithResolvers<void>()
106106
const holder = locker.lock('key', () => release)
107107
const fn = vi.fn()
@@ -126,7 +126,7 @@ describe('memoryLocker', () => {
126126
})
127127

128128
it('gives up immediately when timeout is 0', async () => {
129-
const locker = new MemoryLocker()
129+
const locker = new MemoryLocker({ ttl: 60_000 })
130130
const { promise: release, resolve } = promiseWithResolvers<void>()
131131
const holder = locker.lock('key', () => release)
132132
const fn = vi.fn()
@@ -139,7 +139,7 @@ describe('memoryLocker', () => {
139139
})
140140

141141
it('per-call timeout overrides the default', async () => {
142-
const locker = new MemoryLocker({ timeout: 10_000 })
142+
const locker = new MemoryLocker({ ttl: 60_000, timeout: 10_000 })
143143
const { promise: release, resolve } = promiseWithResolvers<void>()
144144
const holder = locker.lock('key', () => release)
145145
const waiter = locker.lock('key', vi.fn(), { timeout: 100 })
@@ -153,7 +153,7 @@ describe('memoryLocker', () => {
153153
})
154154

155155
it('still hands the lock over to later waiters after an earlier waiter timed out', async () => {
156-
const locker = new MemoryLocker({ timeout: 1000 })
156+
const locker = new MemoryLocker({ ttl: 60_000, timeout: 1000 })
157157
const { promise: release, resolve } = promiseWithResolvers<void>()
158158
const holder = locker.lock('key', () => release)
159159
const timedOut = locker.lock('key', vi.fn())
@@ -182,22 +182,6 @@ describe('memoryLocker', () => {
182182
vi.useRealTimers()
183183
})
184184

185-
it('does not expire locks by default', async () => {
186-
const locker = new MemoryLocker()
187-
const { promise: release, resolve } = promiseWithResolvers<void>()
188-
const holder = locker.lock('key', () => release)
189-
const fn = vi.fn(() => 'ok')
190-
const waiter = locker.lock('key', fn, { timeout: 100_000 })
191-
192-
await vi.advanceTimersByTimeAsync(60_000)
193-
expect(fn).not.toHaveBeenCalled()
194-
195-
resolve()
196-
await holder
197-
await expect(waiter).resolves.toBe('ok')
198-
expect(fn).toHaveBeenCalledWith({ waited: true })
199-
})
200-
201185
it('hands the lock over when the ttl expires', async () => {
202186
const locker = new MemoryLocker({ ttl: 1000 })
203187
const { promise: release, resolve } = promiseWithResolvers<void>()
@@ -258,7 +242,7 @@ describe('memoryLocker', () => {
258242

259243
describe('signal', () => {
260244
it('stops waiting when the signal is aborted', async () => {
261-
const locker = new MemoryLocker()
245+
const locker = new MemoryLocker({ ttl: 60_000 })
262246
const { promise: release, resolve } = promiseWithResolvers<void>()
263247
const holder = locker.lock('key', () => release)
264248
const controller = new AbortController()
@@ -275,7 +259,7 @@ describe('memoryLocker', () => {
275259
})
276260

277261
it('rejects immediately when the signal is already aborted', async () => {
278-
const locker = new MemoryLocker()
262+
const locker = new MemoryLocker({ ttl: 60_000 })
279263
const controller = new AbortController()
280264
controller.abort(new Error('aborted'))
281265
const fn = vi.fn()
@@ -287,7 +271,7 @@ describe('memoryLocker', () => {
287271
})
288272

289273
it('ignores the signal once the lock is acquired', async () => {
290-
const locker = new MemoryLocker()
274+
const locker = new MemoryLocker({ ttl: 60_000 })
291275
const controller = new AbortController()
292276

293277
await expect(

‎packages/lock/src/adapters/memory.ts‎

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,8 @@ export interface MemoryLockerOptions {
99
* How long a lock is held before it expires automatically, in milliseconds.
1010
* Guards against holders that never release the lock.
1111
* Can be overridden per call.
12-
*
13-
* @default undefined (held until released)
1412
*/
15-
ttl?: number | undefined
13+
ttl: number
1614

1715
/**
1816
* How long to wait for a lock to become available, in milliseconds.
@@ -41,12 +39,12 @@ interface MemoryLockEntry {
4139
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
4240
*/
4341
export class MemoryLocker implements Locker {
44-
private readonly ttl: number | undefined
42+
private readonly ttl: number
4543
private readonly timeout: number
4644

4745
private readonly entries = new Map<string, MemoryLockEntry>()
4846

49-
constructor(options: MemoryLockerOptions = {}) {
47+
constructor(options: MemoryLockerOptions) {
5048
this.ttl = options.ttl
5149
this.timeout = options.timeout ?? 10_000
5250
}
@@ -72,9 +70,7 @@ export class MemoryLocker implements Locker {
7270
this.entries.set(key, entry)
7371
}
7472

75-
if (ttl !== undefined) {
76-
entry.expiry = setTimeout(() => this.release(key, token), ttl)
77-
}
73+
entry.expiry = setTimeout(() => this.release(key, token), ttl)
7874

7975
try {
8076
return await fn({ waited })

‎packages/lock/src/adapters/redis.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,14 @@ describe.concurrent(
221221
},
222222
)
223223

224+
it('does not prefix keys by default', async () => {
225+
const redis = { isOpen: true, set: vi.fn(async () => 'OK'), eval: vi.fn(async () => 1) }
226+
const locker = new RedisLocker(redis as any, { ttl: 1000 })
227+
228+
await expect(locker.lock('key', () => 'ok')).resolves.toBe('ok')
229+
expect(redis.set).toHaveBeenCalledWith('key', expect.any(String), expect.anything())
230+
})
231+
224232
it('preserves the callback outcome when the release fails', async () => {
225233
const redis = {
226234
isOpen: true,

‎packages/lock/src/adapters/redis.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import type { RedisClientType } from 'redis'
33
import type { BaseRedisLockerOptions } from './base-redis'
44
import { BaseRedisLocker } from './base-redis'
55

6+
export interface RedisLockerOptions extends BaseRedisLockerOptions {}
7+
68
/**
79
* Locker adapter for Redis. Acquires locks with `SET NX PX` and releases them
810
* atomically with a Lua script, so every instance using the same server shares
@@ -13,7 +15,7 @@ import { BaseRedisLocker } from './base-redis'
1315
export class RedisLocker extends BaseRedisLocker {
1416
constructor(
1517
private readonly redis: RedisClientType<any, any, any, any, any>,
16-
private readonly options: BaseRedisLockerOptions,
18+
private readonly options: RedisLockerOptions,
1719
) {
1820
super(options)
1921
}

‎packages/lock/src/adapters/upstash.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,18 @@ it('prefix creates a locker that appends the prefix and shares the client', asyn
202202
})
203203
})
204204

205+
it('does not prefix keys by default', async () => {
206+
const redis = { set: vi.fn(async () => 'OK'), eval: vi.fn(async () => 1) }
207+
const locker = new UpstashLocker(redis as any, { ttl: 1000 })
208+
209+
await expect(locker.lock('key', () => 'ok')).resolves.toBe('ok')
210+
expect(redis.set).toHaveBeenCalledWith('key', expect.any(String), {
211+
nx: true,
212+
px: 1000,
213+
})
214+
expect(redis.eval).toHaveBeenCalledWith(expect.any(String), ['key'], [expect.any(String)])
215+
})
216+
205217
it('preserves the callback outcome when the release fails', async () => {
206218
const redis = {
207219
set: vi.fn(async () => 'OK'),

‎packages/lock/src/adapters/upstash.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import type { Redis } from '@upstash/redis'
33
import type { BaseRedisLockerOptions } from './base-redis'
44
import { BaseRedisLocker } from './base-redis'
55

6+
export interface UpstashLockerOptions extends BaseRedisLockerOptions {}
7+
68
/**
79
* Locker adapter for Upstash Redis. Acquires locks with `SET NX PX` and releases
810
* them atomically with a Lua script, so it shares locks with `RedisLocker`.
@@ -13,7 +15,7 @@ import { BaseRedisLocker } from './base-redis'
1315
export class UpstashLocker extends BaseRedisLocker {
1416
constructor(
1517
private readonly redis: Redis,
16-
private readonly options: BaseRedisLockerOptions,
18+
private readonly options: UpstashLockerOptions,
1719
) {
1820
super(options)
1921
}

‎packages/lock/src/middleware.test-d.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
import { os, type } from '@orpc/server'
1+
import { ORPCError, os, type } from '@orpc/server'
22

3+
import type { LockTimeoutError } from './error'
34
import { lock } from './middleware'
45
import type { Locker } from './types'
56

@@ -45,6 +46,14 @@ describe('lock', () => {
4546

4647
return undefined
4748
},
49+
error: (error, { context }, input) => {
50+
expectTypeOf(error).toEqualTypeOf<LockTimeoutError>()
51+
expectTypeOf(input.id).toBeString()
52+
expectTypeOf(context.userId).toBeString()
53+
expectTypeOf(context.db).toBeString()
54+
55+
return new ORPCError('LOCKED')
56+
},
4857
}),
4958
)
5059
.handler(({ context, input }) => {

0 commit comments

Comments
 (0)