@orpc/experimental-lock 2.0.0-beta.47 → 2.0.0-beta.49
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -7
- package/dist/adapters/base-redis.d.ts +4 -8
- package/dist/adapters/base-redis.js +57 -0
- package/dist/adapters/memory.d.ts +4 -8
- package/dist/adapters/memory.js +75 -0
- package/dist/adapters/redis.d.ts +4 -8
- package/dist/adapters/redis.js +42 -0
- package/dist/adapters/upstash.d.ts +4 -8
- package/dist/adapters/upstash.js +32 -0
- package/dist/error.d.ts +12 -0
- package/dist/error.js +16 -0
- package/dist/index.d.ts +3 -81
- package/dist/index.js +3 -0
- package/dist/middleware.d.ts +75 -0
- package/dist/middleware.js +51 -0
- package/dist/{shared/experimental-lock.D9u4cJfq.d.mts → types.d.ts} +4 -7
- package/dist/types.js +1 -0
- package/package.json +43 -45
- package/dist/adapters/base-redis.d.mts +0 -66
- package/dist/adapters/base-redis.mjs +0 -45
- package/dist/adapters/memory.d.mts +0 -38
- package/dist/adapters/memory.mjs +0 -70
- package/dist/adapters/redis.d.mts +0 -28
- package/dist/adapters/redis.mjs +0 -38
- package/dist/adapters/upstash.d.mts +0 -27
- package/dist/adapters/upstash.mjs +0 -28
- package/dist/index.d.mts +0 -81
- package/dist/index.mjs +0 -49
- package/dist/shared/experimental-lock.CoYbYjCJ.mjs +0 -13
- package/dist/shared/experimental-lock.D9u4cJfq.d.ts +0 -46
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
<img alt="codecov" src="https://codecov.io/gh/middleapi/orpc/branch/main/graph/badge.svg">
|
|
6
6
|
</a>
|
|
7
7
|
<a href="https://www.npmjs.com/package/@orpc/experimental-lock">
|
|
8
|
-
<img alt="
|
|
8
|
+
<img alt="monthly downloads" src="https://img.shields.io/npm/dm/%40orpc%2Fexperimental-lock?logo=npm" />
|
|
9
9
|
</a>
|
|
10
10
|
<a href="https://app.codspeed.io/middleapi/orpc?utm_source=badge">
|
|
11
11
|
<img alt="CodSpeed" src="https://img.shields.io/endpoint?url=https://codspeed.io/badge.json" />
|
|
@@ -41,10 +41,11 @@ export const router = {
|
|
|
41
41
|
Then call them from a client that knows every input and output, without generating anything:
|
|
42
42
|
|
|
43
43
|
```ts
|
|
44
|
-
import type { RouterClient } from '@orpc/server'
|
|
45
|
-
import type { router } from './router'
|
|
46
44
|
import { createORPCClient } from '@orpc/client'
|
|
47
45
|
import { RPCLink } from '@orpc/client/fetch'
|
|
46
|
+
import type { RouterClient } from '@orpc/server'
|
|
47
|
+
|
|
48
|
+
import type { router } from './router'
|
|
48
49
|
|
|
49
50
|
const link = new RPCLink({ origin: 'http://localhost:3000', url: '/rpc' })
|
|
50
51
|
const client: RouterClient<typeof router> = createORPCClient(link)
|
|
@@ -191,15 +192,14 @@ Like what we build over at [middleapi](https://github.com/middleapi)? You can he
|
|
|
191
192
|
<td align="center"><a href="https://kellychan.im/?ref=middleapi&utm_source=middleapi&utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Kelly Peilin Chan"><img src="https://avatars.githubusercontent.com/u/520852?u=6b0f7105f694e7b5cacf410a3f04c7044b469dc8&v=4" width="139" alt="Kelly Peilin Chan"/><br />Kelly Peilin Chan</a></td>
|
|
192
193
|
<td align="center"><a href="https://guyariely.com/?ref=middleapi&utm_source=middleapi&utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Guy Ariely"><img src="https://avatars.githubusercontent.com/u/42813496?u=edb6b7f563bf28e160a290832e7da57c0506f8ca&v=4" width="139" alt="Guy Ariely"/><br />Guy Ariely</a></td>
|
|
193
194
|
<td align="center"><a href="https://paulsenon.com/?ref=middleapi&utm_source=middleapi&utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="PaulSenon"><img src="https://avatars.githubusercontent.com/u/19531087?u=6385741eb91d200b8c513ec6045482e301767ca6&v=4" width="139" alt="PaulSenon"/><br />PaulSenon</a></td>
|
|
194
|
-
<td align="center"><a href="https://
|
|
195
|
+
<td align="center"><a href="https://piscis.dev/?ref=middleapi&utm_source=middleapi&utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Alex"><img src="https://avatars.githubusercontent.com/u/326163?u=b245f368bd940cf51d08c0b6bf55f8257f359437&v=4" width="139" alt="Alex"/><br />Alex</a></td>
|
|
195
196
|
</tr>
|
|
196
197
|
<tr>
|
|
197
|
-
<td align="center"><a href="https://piscis.dev/?ref=middleapi&utm_source=middleapi&utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Alex"><img src="https://avatars.githubusercontent.com/u/326163?u=b245f368bd940cf51d08c0b6bf55f8257f359437&v=4" width="139" alt="Alex"/><br />Alex</a></td>
|
|
198
198
|
<td align="center"><a href="https://opensource.gubanov.eu/?ref=middleapi&utm_source=middleapi&utm_medium=sponsor" target="_blank" rel="noopener sponsored" title="Andrey Gubanov"><img src="https://avatars.githubusercontent.com/u/1082083?u=c5f2daf7ebece498e85c83367bb37b4e10e2649d&v=4" width="139" alt="Andrey Gubanov"/><br />Andrey Gubanov</a></td>
|
|
199
199
|
</tr>
|
|
200
200
|
</table>
|
|
201
201
|
|
|
202
|
-
With thanks to [
|
|
202
|
+
With thanks to [40 past sponsors](https://orpc.dev/sponsors#past-sponsors) who helped get oRPC here.
|
|
203
203
|
|
|
204
204
|
## Open Source Programs
|
|
205
205
|
|
|
@@ -209,7 +209,6 @@ With thanks to [39 past sponsors](https://orpc.dev/sponsors#past-sponsors) who h
|
|
|
209
209
|
<tr>
|
|
210
210
|
<td align="center"><a href="https://claude.com/contact-sales/claude-for-oss" target="_blank" rel="noopener" title="Claude for Open Source"><img src="https://cdn.simpleicons.org/claude" width="64" alt="Claude"/><br />Claude</a></td>
|
|
211
211
|
<td align="center"><a href="https://pullfrog.com/for-oss" target="_blank" rel="noopener" title="Pullfrog for OSS"><img src="https://avatars.githubusercontent.com/in/1768019?s=128&v=4" width="64" alt="Pullfrog"/><br />Pullfrog</a></td>
|
|
212
|
-
<td align="center"><a href="https://macroscope.com/open-source" target="_blank" rel="noopener" title="Macroscope for Open Source"><img src="https://avatars.githubusercontent.com/in/900172?s=128&v=4" width="64" alt="Macroscope"/><br />Macroscope</a></td>
|
|
213
212
|
</tr>
|
|
214
213
|
</table>
|
|
215
214
|
|
|
@@ -1,12 +1,11 @@
|
|
|
1
|
-
import { Promisable } from '@orpc/shared';
|
|
2
|
-
import {
|
|
3
|
-
|
|
1
|
+
import type { Promisable } from '@orpc/shared';
|
|
2
|
+
import type { LockCallbackOptions, Locker, LockOptions } from '../types.ts';
|
|
4
3
|
/**
|
|
5
4
|
* Options shared by every Redis-backed locker adapter.
|
|
6
5
|
*
|
|
7
6
|
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
8
7
|
*/
|
|
9
|
-
interface BaseRedisLockerOptions {
|
|
8
|
+
export interface BaseRedisLockerOptions {
|
|
10
9
|
/**
|
|
11
10
|
* The prefix to use for Redis keys.
|
|
12
11
|
*
|
|
@@ -43,7 +42,7 @@ interface BaseRedisLockerOptions {
|
|
|
43
42
|
*
|
|
44
43
|
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
45
44
|
*/
|
|
46
|
-
declare abstract class BaseRedisLocker implements Locker {
|
|
45
|
+
export declare abstract class BaseRedisLocker implements Locker {
|
|
47
46
|
protected readonly keyPrefix: string;
|
|
48
47
|
protected readonly ttl: number;
|
|
49
48
|
protected readonly timeout: number;
|
|
@@ -61,6 +60,3 @@ declare abstract class BaseRedisLocker implements Locker {
|
|
|
61
60
|
protected abstract evalScript(script: string, keys: string[], args: string[]): Promise<unknown>;
|
|
62
61
|
lock<T>(key: string, fn: (options: LockCallbackOptions) => Promisable<T>, options?: LockOptions): Promise<T>;
|
|
63
62
|
}
|
|
64
|
-
|
|
65
|
-
export { BaseRedisLocker };
|
|
66
|
-
export type { BaseRedisLockerOptions };
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { sleep, throwIfAborted } from '@orpc/shared';
|
|
2
|
+
import { LockTimeoutError } from '../error.js';
|
|
3
|
+
const RELEASE_LOCK_SCRIPT = `
|
|
4
|
+
if redis.call('GET', KEYS[1]) == ARGV[1] then
|
|
5
|
+
return redis.call('DEL', KEYS[1])
|
|
6
|
+
end
|
|
7
|
+
|
|
8
|
+
return 0
|
|
9
|
+
`;
|
|
10
|
+
/**
|
|
11
|
+
* Base class for Redis-backed locker adapters. It owns the key naming, the lock
|
|
12
|
+
* token, the acquisition loop, and the atomic Lua release, so every adapter built
|
|
13
|
+
* on it can share locks with the others regardless of the Redis client in use.
|
|
14
|
+
*
|
|
15
|
+
* Extend it and implement the abstract methods to support another Redis client.
|
|
16
|
+
*
|
|
17
|
+
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
18
|
+
*/
|
|
19
|
+
export class BaseRedisLocker {
|
|
20
|
+
keyPrefix;
|
|
21
|
+
ttl;
|
|
22
|
+
timeout;
|
|
23
|
+
retryInterval;
|
|
24
|
+
constructor(options) {
|
|
25
|
+
this.keyPrefix = options.prefix ?? '';
|
|
26
|
+
this.ttl = options.ttl;
|
|
27
|
+
this.timeout = options.timeout ?? 10_000;
|
|
28
|
+
this.retryInterval = options.retryInterval ?? 100;
|
|
29
|
+
}
|
|
30
|
+
async lock(key, fn, options = {}) {
|
|
31
|
+
const prefixedKey = `${this.keyPrefix}${key}`;
|
|
32
|
+
const ttl = options.ttl ?? this.ttl;
|
|
33
|
+
const deadline = Date.now() + (options.timeout ?? this.timeout);
|
|
34
|
+
const token = crypto.randomUUID();
|
|
35
|
+
let waited = false;
|
|
36
|
+
throwIfAborted(options.signal);
|
|
37
|
+
while (!(await this.acquire(prefixedKey, token, ttl))) {
|
|
38
|
+
const remaining = deadline - Date.now();
|
|
39
|
+
if (remaining <= 0) {
|
|
40
|
+
throw new LockTimeoutError(key);
|
|
41
|
+
}
|
|
42
|
+
waited = true;
|
|
43
|
+
await sleep(Math.min(this.retryInterval, remaining), { signal: options.signal });
|
|
44
|
+
}
|
|
45
|
+
try {
|
|
46
|
+
return await fn({ waited });
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
try {
|
|
50
|
+
await this.evalScript(RELEASE_LOCK_SCRIPT, [prefixedKey], [token]);
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
// the lock still expires through its TTL
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { Promisable } from '@orpc/shared';
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
interface MemoryLockerOptions {
|
|
1
|
+
import type { Promisable } from '@orpc/shared';
|
|
2
|
+
import type { LockCallbackOptions, Locker, LockOptions } from '../types.ts';
|
|
3
|
+
export interface MemoryLockerOptions {
|
|
5
4
|
/**
|
|
6
5
|
* How long a lock is held before it expires automatically, in milliseconds.
|
|
7
6
|
* Guards against holders that never release the lock.
|
|
@@ -24,7 +23,7 @@ interface MemoryLockerOptions {
|
|
|
24
23
|
*
|
|
25
24
|
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
26
25
|
*/
|
|
27
|
-
declare class MemoryLocker implements Locker {
|
|
26
|
+
export declare class MemoryLocker implements Locker {
|
|
28
27
|
private readonly ttl;
|
|
29
28
|
private readonly timeout;
|
|
30
29
|
private readonly entries;
|
|
@@ -33,6 +32,3 @@ declare class MemoryLocker implements Locker {
|
|
|
33
32
|
private wait;
|
|
34
33
|
private release;
|
|
35
34
|
}
|
|
36
|
-
|
|
37
|
-
export { MemoryLocker };
|
|
38
|
-
export type { MemoryLockerOptions };
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { promiseWithResolvers, throwIfAborted } from '@orpc/shared';
|
|
2
|
+
import { LockTimeoutError } from '../error.js';
|
|
3
|
+
/**
|
|
4
|
+
* Locker adapter backed by in-memory storage, so locks are only shared within
|
|
5
|
+
* the current process. Waiters acquire the lock in order, without polling.
|
|
6
|
+
*
|
|
7
|
+
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
8
|
+
*/
|
|
9
|
+
export class MemoryLocker {
|
|
10
|
+
ttl;
|
|
11
|
+
timeout;
|
|
12
|
+
entries = new Map();
|
|
13
|
+
constructor(options = {}) {
|
|
14
|
+
this.ttl = options.ttl;
|
|
15
|
+
this.timeout = options.timeout ?? 10_000;
|
|
16
|
+
}
|
|
17
|
+
async lock(key, fn, options = {}) {
|
|
18
|
+
const ttl = options.ttl ?? this.ttl;
|
|
19
|
+
const timeout = options.timeout ?? this.timeout;
|
|
20
|
+
const token = {};
|
|
21
|
+
throwIfAborted(options.signal);
|
|
22
|
+
let entry = this.entries.get(key);
|
|
23
|
+
const waited = entry !== undefined;
|
|
24
|
+
if (entry) {
|
|
25
|
+
await this.wait(key, entry, token, timeout, options.signal);
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
entry = { holder: token, waiters: new Set() };
|
|
29
|
+
this.entries.set(key, entry);
|
|
30
|
+
}
|
|
31
|
+
if (ttl !== undefined) {
|
|
32
|
+
entry.expiry = setTimeout(() => this.release(key, token), ttl);
|
|
33
|
+
}
|
|
34
|
+
try {
|
|
35
|
+
return await fn({ waited });
|
|
36
|
+
}
|
|
37
|
+
finally {
|
|
38
|
+
this.release(key, token);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
wait(key, entry, token, timeout, signal) {
|
|
42
|
+
if (timeout <= 0) {
|
|
43
|
+
return Promise.reject(new LockTimeoutError(key));
|
|
44
|
+
}
|
|
45
|
+
const { promise, resolve, reject } = promiseWithResolvers();
|
|
46
|
+
const waiter = { token, resolve };
|
|
47
|
+
entry.waiters.add(waiter);
|
|
48
|
+
const fail = (reason) => {
|
|
49
|
+
entry.waiters.delete(waiter);
|
|
50
|
+
reject(reason);
|
|
51
|
+
};
|
|
52
|
+
const timer = setTimeout(() => fail(new LockTimeoutError(key)), timeout);
|
|
53
|
+
const abortListener = () => fail(signal?.reason);
|
|
54
|
+
signal?.addEventListener('abort', abortListener, { once: true });
|
|
55
|
+
return promise.finally(() => {
|
|
56
|
+
clearTimeout(timer);
|
|
57
|
+
signal?.removeEventListener('abort', abortListener);
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
release(key, token) {
|
|
61
|
+
const entry = this.entries.get(key);
|
|
62
|
+
if (entry?.holder !== token) {
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
clearTimeout(entry.expiry);
|
|
66
|
+
const [next] = entry.waiters;
|
|
67
|
+
if (!next) {
|
|
68
|
+
this.entries.delete(key);
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
entry.waiters.delete(next);
|
|
72
|
+
entry.holder = next.token;
|
|
73
|
+
next.resolve();
|
|
74
|
+
}
|
|
75
|
+
}
|
package/dist/adapters/redis.d.ts
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
|
-
import { RedisClientType } from 'redis';
|
|
2
|
-
import {
|
|
3
|
-
import '
|
|
4
|
-
import '../shared/experimental-lock.D9u4cJfq.js';
|
|
5
|
-
|
|
1
|
+
import type { RedisClientType } from 'redis';
|
|
2
|
+
import type { BaseRedisLockerOptions } from './base-redis.ts';
|
|
3
|
+
import { BaseRedisLocker } from './base-redis.ts';
|
|
6
4
|
/**
|
|
7
5
|
* Locker adapter for Redis. Acquires locks with `SET NX PX` and releases them
|
|
8
6
|
* atomically with a Lua script, so every instance using the same server shares
|
|
@@ -10,7 +8,7 @@ import '../shared/experimental-lock.D9u4cJfq.js';
|
|
|
10
8
|
*
|
|
11
9
|
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
12
10
|
*/
|
|
13
|
-
declare class RedisLocker extends BaseRedisLocker {
|
|
11
|
+
export declare class RedisLocker extends BaseRedisLocker {
|
|
14
12
|
private readonly redis;
|
|
15
13
|
private readonly options;
|
|
16
14
|
constructor(redis: RedisClientType<any, any, any, any, any>, options: BaseRedisLockerOptions);
|
|
@@ -24,5 +22,3 @@ declare class RedisLocker extends BaseRedisLocker {
|
|
|
24
22
|
protected evalScript(script: string, keys: string[], args: string[]): Promise<unknown>;
|
|
25
23
|
private connectIfNeeded;
|
|
26
24
|
}
|
|
27
|
-
|
|
28
|
-
export { RedisLocker };
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { BaseRedisLocker } from './base-redis.js';
|
|
2
|
+
/**
|
|
3
|
+
* Locker adapter for Redis. Acquires locks with `SET NX PX` and releases them
|
|
4
|
+
* atomically with a Lua script, so every instance using the same server shares
|
|
5
|
+
* the same locks.
|
|
6
|
+
*
|
|
7
|
+
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
8
|
+
*/
|
|
9
|
+
export class RedisLocker extends BaseRedisLocker {
|
|
10
|
+
redis;
|
|
11
|
+
options;
|
|
12
|
+
constructor(redis, options) {
|
|
13
|
+
super(options);
|
|
14
|
+
this.redis = redis;
|
|
15
|
+
this.options = options;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Creates a locker with `prefix` appended to this locker's prefix, sharing its Redis client.
|
|
19
|
+
*
|
|
20
|
+
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
21
|
+
*/
|
|
22
|
+
prefix(prefix) {
|
|
23
|
+
return new RedisLocker(this.redis, { ...this.options, prefix: `${this.keyPrefix}${prefix}` });
|
|
24
|
+
}
|
|
25
|
+
async acquire(key, token, ttl) {
|
|
26
|
+
await this.connectIfNeeded();
|
|
27
|
+
const result = await this.redis.set(key, token, {
|
|
28
|
+
condition: 'NX',
|
|
29
|
+
expiration: { type: 'PX', value: ttl },
|
|
30
|
+
});
|
|
31
|
+
return result === 'OK';
|
|
32
|
+
}
|
|
33
|
+
async evalScript(script, keys, args) {
|
|
34
|
+
await this.connectIfNeeded();
|
|
35
|
+
return await this.redis.eval(script, { keys, arguments: args });
|
|
36
|
+
}
|
|
37
|
+
async connectIfNeeded() {
|
|
38
|
+
if (!this.redis.isOpen) {
|
|
39
|
+
await this.redis.connect();
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -1,8 +1,6 @@
|
|
|
1
|
-
import { Redis } from '@upstash/redis';
|
|
2
|
-
import {
|
|
3
|
-
import '
|
|
4
|
-
import '../shared/experimental-lock.D9u4cJfq.js';
|
|
5
|
-
|
|
1
|
+
import type { Redis } from '@upstash/redis';
|
|
2
|
+
import type { BaseRedisLockerOptions } from './base-redis.ts';
|
|
3
|
+
import { BaseRedisLocker } from './base-redis.ts';
|
|
6
4
|
/**
|
|
7
5
|
* Locker adapter for Upstash Redis. Acquires locks with `SET NX PX` and releases
|
|
8
6
|
* them atomically with a Lua script, so it shares locks with `RedisLocker`.
|
|
@@ -10,7 +8,7 @@ import '../shared/experimental-lock.D9u4cJfq.js';
|
|
|
10
8
|
*
|
|
11
9
|
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
12
10
|
*/
|
|
13
|
-
declare class UpstashLocker extends BaseRedisLocker {
|
|
11
|
+
export declare class UpstashLocker extends BaseRedisLocker {
|
|
14
12
|
private readonly redis;
|
|
15
13
|
private readonly options;
|
|
16
14
|
constructor(redis: Redis, options: BaseRedisLockerOptions);
|
|
@@ -23,5 +21,3 @@ declare class UpstashLocker extends BaseRedisLocker {
|
|
|
23
21
|
protected acquire(key: string, token: string, ttl: number): Promise<boolean>;
|
|
24
22
|
protected evalScript(script: string, keys: string[], args: string[]): Promise<unknown>;
|
|
25
23
|
}
|
|
26
|
-
|
|
27
|
-
export { UpstashLocker };
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { BaseRedisLocker } from './base-redis.js';
|
|
2
|
+
/**
|
|
3
|
+
* Locker adapter for Upstash Redis. Acquires locks with `SET NX PX` and releases
|
|
4
|
+
* them atomically with a Lua script, so it shares locks with `RedisLocker`.
|
|
5
|
+
* A good fit for serverless and edge runtimes.
|
|
6
|
+
*
|
|
7
|
+
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
8
|
+
*/
|
|
9
|
+
export class UpstashLocker extends BaseRedisLocker {
|
|
10
|
+
redis;
|
|
11
|
+
options;
|
|
12
|
+
constructor(redis, options) {
|
|
13
|
+
super(options);
|
|
14
|
+
this.redis = redis;
|
|
15
|
+
this.options = options;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Creates a locker with `prefix` appended to this locker's prefix, sharing its Redis client.
|
|
19
|
+
*
|
|
20
|
+
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
21
|
+
*/
|
|
22
|
+
prefix(prefix) {
|
|
23
|
+
return new UpstashLocker(this.redis, { ...this.options, prefix: `${this.keyPrefix}${prefix}` });
|
|
24
|
+
}
|
|
25
|
+
async acquire(key, token, ttl) {
|
|
26
|
+
const result = await this.redis.set(key, token, { nx: true, px: ttl });
|
|
27
|
+
return result === 'OK';
|
|
28
|
+
}
|
|
29
|
+
async evalScript(script, keys, args) {
|
|
30
|
+
return await this.redis.eval(script, keys, args);
|
|
31
|
+
}
|
|
32
|
+
}
|
package/dist/error.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thrown when a lock cannot be acquired before the timeout elapses.
|
|
3
|
+
*
|
|
4
|
+
* @see {@link https://orpc.dev/docs/helpers/lock#options | Lock Helpers - Options}
|
|
5
|
+
*/
|
|
6
|
+
export declare class LockTimeoutError extends Error {
|
|
7
|
+
/**
|
|
8
|
+
* The key of the lock that could not be acquired.
|
|
9
|
+
*/
|
|
10
|
+
readonly key: string;
|
|
11
|
+
constructor(key: string);
|
|
12
|
+
}
|
package/dist/error.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Thrown when a lock cannot be acquired before the timeout elapses.
|
|
3
|
+
*
|
|
4
|
+
* @see {@link https://orpc.dev/docs/helpers/lock#options | Lock Helpers - Options}
|
|
5
|
+
*/
|
|
6
|
+
export class LockTimeoutError extends Error {
|
|
7
|
+
/**
|
|
8
|
+
* The key of the lock that could not be acquired.
|
|
9
|
+
*/
|
|
10
|
+
key;
|
|
11
|
+
constructor(key) {
|
|
12
|
+
super(`Timed out waiting for the lock of key "${key}"`);
|
|
13
|
+
this.name = 'LockTimeoutError';
|
|
14
|
+
this.key = key;
|
|
15
|
+
}
|
|
16
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,81 +1,3 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
export { a as LockCallbackOptions, b as LockOptions } from './shared/experimental-lock.D9u4cJfq.js';
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Thrown when a lock cannot be acquired before the timeout elapses.
|
|
8
|
-
*
|
|
9
|
-
* @see {@link https://orpc.dev/docs/helpers/lock#options | Lock Helpers - Options}
|
|
10
|
-
*/
|
|
11
|
-
declare class LockTimeoutError extends Error {
|
|
12
|
-
/**
|
|
13
|
-
* The key of the lock that could not be acquired.
|
|
14
|
-
*/
|
|
15
|
-
readonly key: string;
|
|
16
|
-
constructor(key: string);
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
declare const LOCK_MIDDLEWARE_CONTEXT_SYMBOL: unique symbol;
|
|
20
|
-
interface LockMiddlewareContext {
|
|
21
|
-
[LOCK_MIDDLEWARE_CONTEXT_SYMBOL]?: {
|
|
22
|
-
/**
|
|
23
|
-
* The locks held in this request, mainly for deduplication purposes
|
|
24
|
-
*/
|
|
25
|
-
held: {
|
|
26
|
-
locker: Locker;
|
|
27
|
-
key: string;
|
|
28
|
-
waited: boolean;
|
|
29
|
-
}[];
|
|
30
|
-
};
|
|
31
|
-
}
|
|
32
|
-
interface LockMiddlewareOutContext {
|
|
33
|
-
/**
|
|
34
|
-
* Whether the lock was acquired only after waiting for another holder to release it.
|
|
35
|
-
* `false` means the lock was acquired immediately.
|
|
36
|
-
*/
|
|
37
|
-
['lock/waited']: boolean;
|
|
38
|
-
}
|
|
39
|
-
interface LockMiddlewareOptions<TInContext extends Context, TInput> {
|
|
40
|
-
/**
|
|
41
|
-
* The locker to acquire the lock from
|
|
42
|
-
*/
|
|
43
|
-
locker: Value<Promisable<Locker>, [options: MiddlewareOptions<TInContext, unknown, Record<never, never>>, input: TInput]>;
|
|
44
|
-
/**
|
|
45
|
-
* The key to identify the work that must not run concurrently
|
|
46
|
-
*/
|
|
47
|
-
key: Value<Promisable<string>, [options: MiddlewareOptions<TInContext, unknown, Record<never, never>>, input: TInput]>;
|
|
48
|
-
/**
|
|
49
|
-
* How long the lock is held before it expires automatically, in milliseconds.
|
|
50
|
-
*
|
|
51
|
-
* @default the adapter default
|
|
52
|
-
*/
|
|
53
|
-
ttl?: Value<Promisable<number | undefined>, [options: MiddlewareOptions<TInContext, unknown, Record<never, never>>, input: TInput]> | undefined;
|
|
54
|
-
/**
|
|
55
|
-
* How long to wait for the lock to become available, in milliseconds.
|
|
56
|
-
*
|
|
57
|
-
* @default the adapter default
|
|
58
|
-
*/
|
|
59
|
-
timeout?: Value<Promisable<number | undefined>, [options: MiddlewareOptions<TInContext, unknown, Record<never, never>>, input: TInput]> | undefined;
|
|
60
|
-
/**
|
|
61
|
-
* If your lock middleware is used multiple times
|
|
62
|
-
* or you invoke a procedure inside another procedure (shared the same context) that also has
|
|
63
|
-
* lock middleware **with the same locker and key**, this option
|
|
64
|
-
* will ensure that the lock is only acquired once per request,
|
|
65
|
-
* instead of waiting for itself until the timeout elapses.
|
|
66
|
-
*
|
|
67
|
-
* @default true
|
|
68
|
-
*/
|
|
69
|
-
dedupe?: boolean | undefined;
|
|
70
|
-
}
|
|
71
|
-
/**
|
|
72
|
-
* Creates a middleware that runs oRPC procedures under a lock, so that calls
|
|
73
|
-
* sharing the same key never run concurrently. Rejects with a `CONFLICT` error
|
|
74
|
-
* when the lock cannot be acquired before the timeout elapses.
|
|
75
|
-
*
|
|
76
|
-
* @see {@link https://orpc.dev/docs/helpers/lock#lock-middleware | Lock Helpers - Lock Middleware}
|
|
77
|
-
*/
|
|
78
|
-
declare function lock<TInContext extends Context, TInput>({ dedupe, ...options }: LockMiddlewareOptions<TInContext, TInput>): Middleware<TInContext, LockMiddlewareOutContext, TInput, any, object>;
|
|
79
|
-
|
|
80
|
-
export { LOCK_MIDDLEWARE_CONTEXT_SYMBOL, LockTimeoutError, Locker, lock };
|
|
81
|
-
export type { LockMiddlewareContext, LockMiddlewareOptions, LockMiddlewareOutContext };
|
|
1
|
+
export * from './error.ts';
|
|
2
|
+
export * from './middleware.ts';
|
|
3
|
+
export * from './types.ts';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { Context, Middleware, MiddlewareOptions } from '@orpc/server';
|
|
2
|
+
import type { Promisable, Value } from '@orpc/shared';
|
|
3
|
+
import type { Locker } from './types.ts';
|
|
4
|
+
export declare const LOCK_MIDDLEWARE_CONTEXT_SYMBOL: unique symbol;
|
|
5
|
+
export interface LockMiddlewareContext {
|
|
6
|
+
[LOCK_MIDDLEWARE_CONTEXT_SYMBOL]?: {
|
|
7
|
+
/**
|
|
8
|
+
* The locks held in this request, mainly for deduplication purposes
|
|
9
|
+
*/
|
|
10
|
+
held: {
|
|
11
|
+
locker: Locker;
|
|
12
|
+
key: string;
|
|
13
|
+
waited: boolean;
|
|
14
|
+
}[];
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
export interface LockMiddlewareOutContext {
|
|
18
|
+
/**
|
|
19
|
+
* Whether the lock was acquired only after waiting for another holder to release it.
|
|
20
|
+
* `false` means the lock was acquired immediately.
|
|
21
|
+
*/
|
|
22
|
+
['lock/waited']: boolean;
|
|
23
|
+
}
|
|
24
|
+
export interface LockMiddlewareOptions<TInContext extends Context, TInput> {
|
|
25
|
+
/**
|
|
26
|
+
* The locker to acquire the lock from
|
|
27
|
+
*/
|
|
28
|
+
locker: Value<Promisable<Locker>, [
|
|
29
|
+
options: MiddlewareOptions<TInContext, unknown, Record<never, never>>,
|
|
30
|
+
input: TInput
|
|
31
|
+
]>;
|
|
32
|
+
/**
|
|
33
|
+
* The key to identify the work that must not run concurrently
|
|
34
|
+
*/
|
|
35
|
+
key: Value<Promisable<string>, [
|
|
36
|
+
options: MiddlewareOptions<TInContext, unknown, Record<never, never>>,
|
|
37
|
+
input: TInput
|
|
38
|
+
]>;
|
|
39
|
+
/**
|
|
40
|
+
* How long the lock is held before it expires automatically, in milliseconds.
|
|
41
|
+
*
|
|
42
|
+
* @default the adapter default
|
|
43
|
+
*/
|
|
44
|
+
ttl?: Value<Promisable<number | undefined>, [
|
|
45
|
+
options: MiddlewareOptions<TInContext, unknown, Record<never, never>>,
|
|
46
|
+
input: TInput
|
|
47
|
+
]> | undefined;
|
|
48
|
+
/**
|
|
49
|
+
* How long to wait for the lock to become available, in milliseconds.
|
|
50
|
+
*
|
|
51
|
+
* @default the adapter default
|
|
52
|
+
*/
|
|
53
|
+
timeout?: Value<Promisable<number | undefined>, [
|
|
54
|
+
options: MiddlewareOptions<TInContext, unknown, Record<never, never>>,
|
|
55
|
+
input: TInput
|
|
56
|
+
]> | undefined;
|
|
57
|
+
/**
|
|
58
|
+
* If your lock middleware is used multiple times
|
|
59
|
+
* or you invoke a procedure inside another procedure (shared the same context) that also has
|
|
60
|
+
* lock middleware **with the same locker and key**, this option
|
|
61
|
+
* will ensure that the lock is only acquired once per request,
|
|
62
|
+
* instead of waiting for itself until the timeout elapses.
|
|
63
|
+
*
|
|
64
|
+
* @default true
|
|
65
|
+
*/
|
|
66
|
+
dedupe?: boolean | undefined;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Creates a middleware that runs oRPC procedures under a lock, so that calls
|
|
70
|
+
* sharing the same key never run concurrently. Rejects with a `CONFLICT` error
|
|
71
|
+
* when the lock cannot be acquired before the timeout elapses.
|
|
72
|
+
*
|
|
73
|
+
* @see {@link https://orpc.dev/docs/helpers/lock#lock-middleware | Lock Helpers - Lock Middleware}
|
|
74
|
+
*/
|
|
75
|
+
export declare function lock<TInContext extends Context, TInput>({ dedupe, ...options }: LockMiddlewareOptions<TInContext, TInput>): Middleware<TInContext, LockMiddlewareOutContext, TInput, any, object>;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { ORPCError } from '@orpc/server';
|
|
2
|
+
import { toArray, value } from '@orpc/shared';
|
|
3
|
+
import { LockTimeoutError } from './error.js';
|
|
4
|
+
export const LOCK_MIDDLEWARE_CONTEXT_SYMBOL = /* @__PURE__ */ Symbol.for('ORPC_LOCK_MIDDLEWARE_CONTEXT');
|
|
5
|
+
/**
|
|
6
|
+
* Creates a middleware that runs oRPC procedures under a lock, so that calls
|
|
7
|
+
* sharing the same key never run concurrently. Rejects with a `CONFLICT` error
|
|
8
|
+
* when the lock cannot be acquired before the timeout elapses.
|
|
9
|
+
*
|
|
10
|
+
* @see {@link https://orpc.dev/docs/helpers/lock#lock-middleware | Lock Helpers - Lock Middleware}
|
|
11
|
+
*/
|
|
12
|
+
export function lock({ dedupe = true, ...options }) {
|
|
13
|
+
return async function lock(middlewareOptions, input) {
|
|
14
|
+
const [locker, key, ttl, timeout] = await Promise.all([
|
|
15
|
+
value(options.locker, middlewareOptions, input),
|
|
16
|
+
value(options.key, middlewareOptions, input),
|
|
17
|
+
value(options.ttl, middlewareOptions, input),
|
|
18
|
+
value(options.timeout, middlewareOptions, input),
|
|
19
|
+
]);
|
|
20
|
+
const middlewareContext = middlewareOptions.context[LOCK_MIDDLEWARE_CONTEXT_SYMBOL];
|
|
21
|
+
const held = middlewareContext?.held.find((l) => l.key === key && l.locker === locker);
|
|
22
|
+
if (dedupe && held) {
|
|
23
|
+
return middlewareOptions.next({
|
|
24
|
+
context: {
|
|
25
|
+
'lock/waited': held.waited,
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
let acquired = false;
|
|
30
|
+
try {
|
|
31
|
+
return await locker.lock(key, ({ waited }) => {
|
|
32
|
+
acquired = true;
|
|
33
|
+
return middlewareOptions.next({
|
|
34
|
+
context: {
|
|
35
|
+
'lock/waited': waited,
|
|
36
|
+
[LOCK_MIDDLEWARE_CONTEXT_SYMBOL]: {
|
|
37
|
+
...middlewareContext,
|
|
38
|
+
held: [...toArray(middlewareContext?.held), { locker, key, waited }],
|
|
39
|
+
},
|
|
40
|
+
},
|
|
41
|
+
});
|
|
42
|
+
}, { ttl, timeout, signal: middlewareOptions.signal });
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
if (!acquired && error instanceof LockTimeoutError) {
|
|
46
|
+
throw new ORPCError('CONFLICT', { cause: error });
|
|
47
|
+
}
|
|
48
|
+
throw error;
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { Promisable } from '@orpc/shared';
|
|
2
|
-
|
|
3
|
-
interface LockOptions {
|
|
1
|
+
import type { Promisable } from '@orpc/shared';
|
|
2
|
+
export interface LockOptions {
|
|
4
3
|
/**
|
|
5
4
|
* How long the lock is held before it expires automatically, in milliseconds.
|
|
6
5
|
* Guards against holders that never release the lock, such as a crashed process.
|
|
@@ -19,7 +18,7 @@ interface LockOptions {
|
|
|
19
18
|
*/
|
|
20
19
|
signal?: AbortSignal | undefined;
|
|
21
20
|
}
|
|
22
|
-
interface LockCallbackOptions {
|
|
21
|
+
export interface LockCallbackOptions {
|
|
23
22
|
/**
|
|
24
23
|
* Whether the lock was acquired only after waiting for another holder to release it.
|
|
25
24
|
* `false` means the lock was acquired immediately.
|
|
@@ -33,7 +32,7 @@ interface LockCallbackOptions {
|
|
|
33
32
|
*
|
|
34
33
|
* @see {@link https://orpc.dev/docs/helpers/lock | Lock Helpers}
|
|
35
34
|
*/
|
|
36
|
-
interface Locker {
|
|
35
|
+
export interface Locker {
|
|
37
36
|
/**
|
|
38
37
|
* Runs `fn` while holding the lock for `key`, and releases the lock afterwards,
|
|
39
38
|
* even when `fn` throws.
|
|
@@ -42,5 +41,3 @@ interface Locker {
|
|
|
42
41
|
*/
|
|
43
42
|
lock<T>(key: string, fn: (options: LockCallbackOptions) => Promisable<T>, options?: LockOptions): Promise<T>;
|
|
44
43
|
}
|
|
45
|
-
|
|
46
|
-
export type { Locker as L, LockCallbackOptions as a, LockOptions as b };
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|