@orpc/experimental-lock 2.0.0-beta.48 → 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 +4 -4
- package/dist/adapters/base-redis.d.ts +62 -0
- package/dist/adapters/base-redis.js +57 -0
- package/dist/adapters/memory.d.ts +34 -0
- package/dist/adapters/memory.js +75 -0
- package/dist/adapters/redis.d.ts +24 -0
- package/dist/adapters/redis.js +42 -0
- package/dist/adapters/upstash.d.ts +23 -0
- 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 -0
- package/dist/index.js +3 -0
- package/dist/middleware.d.ts +75 -0
- package/dist/middleware.js +51 -0
- package/dist/types.d.ts +43 -0
- package/package.json +43 -45
- package/dist/adapters/base-redis.d.mts +0 -62
- package/dist/adapters/base-redis.mjs +0 -43
- package/dist/adapters/memory.d.mts +0 -34
- package/dist/adapters/memory.mjs +0 -74
- package/dist/adapters/redis.d.mts +0 -24
- package/dist/adapters/redis.mjs +0 -41
- package/dist/adapters/upstash.d.mts +0 -23
- package/dist/adapters/upstash.mjs +0 -28
- package/dist/error.d.mts +0 -12
- package/dist/error.mjs +0 -10
- package/dist/index.d.mts +0 -3
- package/dist/index.mjs +0 -3
- package/dist/middleware.d.mts +0 -69
- package/dist/middleware.mjs +0 -46
- package/dist/types.d.mts +0 -43
- /package/dist/{types.mjs → types.js} +0 -0
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)
|
|
@@ -208,7 +209,6 @@ With thanks to [40 past sponsors](https://orpc.dev/sponsors#past-sponsors) who h
|
|
|
208
209
|
<tr>
|
|
209
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>
|
|
210
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>
|
|
211
|
-
<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>
|
|
212
212
|
</tr>
|
|
213
213
|
</table>
|
|
214
214
|
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { Promisable } from '@orpc/shared';
|
|
2
|
+
import type { LockCallbackOptions, Locker, LockOptions } from '../types.ts';
|
|
3
|
+
/**
|
|
4
|
+
* Options shared by every Redis-backed locker adapter.
|
|
5
|
+
*
|
|
6
|
+
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
7
|
+
*/
|
|
8
|
+
export interface BaseRedisLockerOptions {
|
|
9
|
+
/**
|
|
10
|
+
* The prefix to use for Redis keys.
|
|
11
|
+
*
|
|
12
|
+
* @default ''
|
|
13
|
+
*/
|
|
14
|
+
prefix?: string | undefined;
|
|
15
|
+
/**
|
|
16
|
+
* How long a lock is held before it expires automatically, in milliseconds.
|
|
17
|
+
* Guards against holders that never release the lock, such as a crashed process.
|
|
18
|
+
* Can be overridden per call.
|
|
19
|
+
*/
|
|
20
|
+
ttl: number;
|
|
21
|
+
/**
|
|
22
|
+
* How long to wait for a lock to become available, in milliseconds.
|
|
23
|
+
* Can be overridden per call.
|
|
24
|
+
*
|
|
25
|
+
* @default 10000
|
|
26
|
+
*/
|
|
27
|
+
timeout?: number | undefined;
|
|
28
|
+
/**
|
|
29
|
+
* How long to wait between acquisition attempts while the lock
|
|
30
|
+
* is held by someone else, in milliseconds.
|
|
31
|
+
*
|
|
32
|
+
* @default 100
|
|
33
|
+
*/
|
|
34
|
+
retryInterval?: number | undefined;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Base class for Redis-backed locker adapters. It owns the key naming, the lock
|
|
38
|
+
* token, the acquisition loop, and the atomic Lua release, so every adapter built
|
|
39
|
+
* on it can share locks with the others regardless of the Redis client in use.
|
|
40
|
+
*
|
|
41
|
+
* Extend it and implement the abstract methods to support another Redis client.
|
|
42
|
+
*
|
|
43
|
+
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
44
|
+
*/
|
|
45
|
+
export declare abstract class BaseRedisLocker implements Locker {
|
|
46
|
+
protected readonly keyPrefix: string;
|
|
47
|
+
protected readonly ttl: number;
|
|
48
|
+
protected readonly timeout: number;
|
|
49
|
+
protected readonly retryInterval: number;
|
|
50
|
+
constructor(options: BaseRedisLockerOptions);
|
|
51
|
+
/**
|
|
52
|
+
* Sets `key` to `token` only when it does not exist yet, with an expiry
|
|
53
|
+
* of `ttl` milliseconds (`SET key token NX PX ttl`), and resolves with
|
|
54
|
+
* whether the key was set.
|
|
55
|
+
*/
|
|
56
|
+
protected abstract acquire(key: string, token: string, ttl: number): Promise<boolean>;
|
|
57
|
+
/**
|
|
58
|
+
* Runs a Lua script (`EVAL script numkeys key [key ...] arg [arg ...]`).
|
|
59
|
+
*/
|
|
60
|
+
protected abstract evalScript(script: string, keys: string[], args: string[]): Promise<unknown>;
|
|
61
|
+
lock<T>(key: string, fn: (options: LockCallbackOptions) => Promisable<T>, options?: LockOptions): Promise<T>;
|
|
62
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Promisable } from '@orpc/shared';
|
|
2
|
+
import type { LockCallbackOptions, Locker, LockOptions } from '../types.ts';
|
|
3
|
+
export interface MemoryLockerOptions {
|
|
4
|
+
/**
|
|
5
|
+
* How long a lock is held before it expires automatically, in milliseconds.
|
|
6
|
+
* Guards against holders that never release the lock.
|
|
7
|
+
* Can be overridden per call.
|
|
8
|
+
*
|
|
9
|
+
* @default undefined (held until released)
|
|
10
|
+
*/
|
|
11
|
+
ttl?: number | undefined;
|
|
12
|
+
/**
|
|
13
|
+
* How long to wait for a lock to become available, in milliseconds.
|
|
14
|
+
* Can be overridden per call.
|
|
15
|
+
*
|
|
16
|
+
* @default 10000
|
|
17
|
+
*/
|
|
18
|
+
timeout?: number | undefined;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Locker adapter backed by in-memory storage, so locks are only shared within
|
|
22
|
+
* the current process. Waiters acquire the lock in order, without polling.
|
|
23
|
+
*
|
|
24
|
+
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
25
|
+
*/
|
|
26
|
+
export declare class MemoryLocker implements Locker {
|
|
27
|
+
private readonly ttl;
|
|
28
|
+
private readonly timeout;
|
|
29
|
+
private readonly entries;
|
|
30
|
+
constructor(options?: MemoryLockerOptions);
|
|
31
|
+
lock<T>(key: string, fn: (options: LockCallbackOptions) => Promisable<T>, options?: LockOptions): Promise<T>;
|
|
32
|
+
private wait;
|
|
33
|
+
private release;
|
|
34
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { RedisClientType } from 'redis';
|
|
2
|
+
import type { BaseRedisLockerOptions } from './base-redis.ts';
|
|
3
|
+
import { BaseRedisLocker } from './base-redis.ts';
|
|
4
|
+
/**
|
|
5
|
+
* Locker adapter for Redis. Acquires locks with `SET NX PX` and releases them
|
|
6
|
+
* atomically with a Lua script, so every instance using the same server shares
|
|
7
|
+
* the same locks.
|
|
8
|
+
*
|
|
9
|
+
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
10
|
+
*/
|
|
11
|
+
export declare class RedisLocker extends BaseRedisLocker {
|
|
12
|
+
private readonly redis;
|
|
13
|
+
private readonly options;
|
|
14
|
+
constructor(redis: RedisClientType<any, any, any, any, any>, options: BaseRedisLockerOptions);
|
|
15
|
+
/**
|
|
16
|
+
* Creates a locker with `prefix` appended to this locker's prefix, sharing its Redis client.
|
|
17
|
+
*
|
|
18
|
+
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
19
|
+
*/
|
|
20
|
+
prefix(prefix: string): RedisLocker;
|
|
21
|
+
protected acquire(key: string, token: string, ttl: number): Promise<boolean>;
|
|
22
|
+
protected evalScript(script: string, keys: string[], args: string[]): Promise<unknown>;
|
|
23
|
+
private connectIfNeeded;
|
|
24
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Redis } from '@upstash/redis';
|
|
2
|
+
import type { BaseRedisLockerOptions } from './base-redis.ts';
|
|
3
|
+
import { BaseRedisLocker } from './base-redis.ts';
|
|
4
|
+
/**
|
|
5
|
+
* Locker adapter for Upstash Redis. Acquires locks with `SET NX PX` and releases
|
|
6
|
+
* them atomically with a Lua script, so it shares locks with `RedisLocker`.
|
|
7
|
+
* A good fit for serverless and edge runtimes.
|
|
8
|
+
*
|
|
9
|
+
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
10
|
+
*/
|
|
11
|
+
export declare class UpstashLocker extends BaseRedisLocker {
|
|
12
|
+
private readonly redis;
|
|
13
|
+
private readonly options;
|
|
14
|
+
constructor(redis: Redis, options: BaseRedisLockerOptions);
|
|
15
|
+
/**
|
|
16
|
+
* Creates a locker with `prefix` appended to this locker's prefix, sharing its Redis client.
|
|
17
|
+
*
|
|
18
|
+
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
19
|
+
*/
|
|
20
|
+
prefix(prefix: string): UpstashLocker;
|
|
21
|
+
protected acquire(key: string, token: string, ttl: number): Promise<boolean>;
|
|
22
|
+
protected evalScript(script: string, keys: string[], args: string[]): Promise<unknown>;
|
|
23
|
+
}
|
|
@@ -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
ADDED
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
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { Promisable } from '@orpc/shared';
|
|
2
|
+
export interface LockOptions {
|
|
3
|
+
/**
|
|
4
|
+
* How long the lock is held before it expires automatically, in milliseconds.
|
|
5
|
+
* Guards against holders that never release the lock, such as a crashed process.
|
|
6
|
+
*
|
|
7
|
+
* @default the adapter default
|
|
8
|
+
*/
|
|
9
|
+
ttl?: number | undefined;
|
|
10
|
+
/**
|
|
11
|
+
* How long to wait for the lock to become available, in milliseconds.
|
|
12
|
+
*
|
|
13
|
+
* @default the adapter default
|
|
14
|
+
*/
|
|
15
|
+
timeout?: number | undefined;
|
|
16
|
+
/**
|
|
17
|
+
* Aborts waiting for the lock. Has no effect once the lock is acquired.
|
|
18
|
+
*/
|
|
19
|
+
signal?: AbortSignal | undefined;
|
|
20
|
+
}
|
|
21
|
+
export interface LockCallbackOptions {
|
|
22
|
+
/**
|
|
23
|
+
* Whether the lock was acquired only after waiting for another holder to release it.
|
|
24
|
+
* `false` means the lock was acquired immediately.
|
|
25
|
+
*/
|
|
26
|
+
waited: boolean;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Standard interface for running work under a lock, so that work sharing
|
|
30
|
+
* the same key never runs concurrently.
|
|
31
|
+
* Implement it for custom strategies, or use one of the provided adapters.
|
|
32
|
+
*
|
|
33
|
+
* @see {@link https://orpc.dev/docs/helpers/lock | Lock Helpers}
|
|
34
|
+
*/
|
|
35
|
+
export interface Locker {
|
|
36
|
+
/**
|
|
37
|
+
* Runs `fn` while holding the lock for `key`, and releases the lock afterwards,
|
|
38
|
+
* even when `fn` throws.
|
|
39
|
+
*
|
|
40
|
+
* @throws {LockTimeoutError} when the lock cannot be acquired before the timeout elapses
|
|
41
|
+
*/
|
|
42
|
+
lock<T>(key: string, fn: (options: LockCallbackOptions) => Promisable<T>, options?: LockOptions): Promise<T>;
|
|
43
|
+
}
|
package/package.json
CHANGED
|
@@ -1,62 +1,70 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@orpc/experimental-lock",
|
|
3
|
-
"
|
|
4
|
-
"version": "2.0.0-beta.48",
|
|
3
|
+
"version": "2.0.0-beta.49",
|
|
5
4
|
"description": "Locking for oRPC procedures, with memory, Redis, and Upstash adapters",
|
|
6
|
-
"
|
|
7
|
-
|
|
8
|
-
"
|
|
9
|
-
"
|
|
5
|
+
"keywords": [
|
|
6
|
+
"api",
|
|
7
|
+
"lock",
|
|
8
|
+
"locking",
|
|
9
|
+
"middleware",
|
|
10
|
+
"mutex",
|
|
11
|
+
"orpc",
|
|
12
|
+
"redis",
|
|
13
|
+
"typescript",
|
|
14
|
+
"upstash"
|
|
10
15
|
],
|
|
11
16
|
"homepage": "https://orpc.dev",
|
|
17
|
+
"license": "MIT",
|
|
12
18
|
"repository": {
|
|
13
19
|
"type": "git",
|
|
14
20
|
"url": "git+https://github.com/middleapi/orpc.git",
|
|
15
21
|
"directory": "packages/lock"
|
|
16
22
|
},
|
|
17
|
-
"
|
|
18
|
-
"
|
|
19
|
-
"
|
|
20
|
-
"locking",
|
|
21
|
-
"mutex",
|
|
22
|
-
"redis",
|
|
23
|
-
"upstash",
|
|
24
|
-
"middleware",
|
|
25
|
-
"api",
|
|
26
|
-
"typescript"
|
|
23
|
+
"funding": [
|
|
24
|
+
"https://github.com/sponsors/dinwwwh",
|
|
25
|
+
"https://opencollective.com/middleapi"
|
|
27
26
|
],
|
|
27
|
+
"files": [
|
|
28
|
+
"dist"
|
|
29
|
+
],
|
|
30
|
+
"type": "module",
|
|
28
31
|
"sideEffects": false,
|
|
29
32
|
"exports": {
|
|
30
33
|
"./package.json": "./package.json",
|
|
31
34
|
".": {
|
|
32
|
-
"types": "./dist/index.d.
|
|
33
|
-
"import": "./dist/index.
|
|
34
|
-
"default": "./dist/index.
|
|
35
|
+
"types": "./dist/index.d.ts",
|
|
36
|
+
"import": "./dist/index.js",
|
|
37
|
+
"default": "./dist/index.js"
|
|
35
38
|
},
|
|
36
39
|
"./base-redis": {
|
|
37
|
-
"types": "./dist/adapters/base-redis.d.
|
|
38
|
-
"import": "./dist/adapters/base-redis.
|
|
39
|
-
"default": "./dist/adapters/base-redis.
|
|
40
|
+
"types": "./dist/adapters/base-redis.d.ts",
|
|
41
|
+
"import": "./dist/adapters/base-redis.js",
|
|
42
|
+
"default": "./dist/adapters/base-redis.js"
|
|
40
43
|
},
|
|
41
44
|
"./memory": {
|
|
42
|
-
"types": "./dist/adapters/memory.d.
|
|
43
|
-
"import": "./dist/adapters/memory.
|
|
44
|
-
"default": "./dist/adapters/memory.
|
|
45
|
+
"types": "./dist/adapters/memory.d.ts",
|
|
46
|
+
"import": "./dist/adapters/memory.js",
|
|
47
|
+
"default": "./dist/adapters/memory.js"
|
|
45
48
|
},
|
|
46
49
|
"./redis": {
|
|
47
|
-
"types": "./dist/adapters/redis.d.
|
|
48
|
-
"import": "./dist/adapters/redis.
|
|
49
|
-
"default": "./dist/adapters/redis.
|
|
50
|
+
"types": "./dist/adapters/redis.d.ts",
|
|
51
|
+
"import": "./dist/adapters/redis.js",
|
|
52
|
+
"default": "./dist/adapters/redis.js"
|
|
50
53
|
},
|
|
51
54
|
"./upstash": {
|
|
52
|
-
"types": "./dist/adapters/upstash.d.
|
|
53
|
-
"import": "./dist/adapters/upstash.
|
|
54
|
-
"default": "./dist/adapters/upstash.
|
|
55
|
+
"types": "./dist/adapters/upstash.d.ts",
|
|
56
|
+
"import": "./dist/adapters/upstash.js",
|
|
57
|
+
"default": "./dist/adapters/upstash.js"
|
|
55
58
|
}
|
|
56
59
|
},
|
|
57
|
-
"
|
|
58
|
-
"
|
|
59
|
-
|
|
60
|
+
"dependencies": {
|
|
61
|
+
"@orpc/server": "2.0.0-beta.49",
|
|
62
|
+
"@orpc/shared": "2.0.0-beta.49"
|
|
63
|
+
},
|
|
64
|
+
"devDependencies": {
|
|
65
|
+
"@upstash/redis": "^1.41.0",
|
|
66
|
+
"redis": "^6.3.1"
|
|
67
|
+
},
|
|
60
68
|
"peerDependencies": {
|
|
61
69
|
"@upstash/redis": ">=1.35.6",
|
|
62
70
|
"redis": ">=6.0.0"
|
|
@@ -69,15 +77,5 @@
|
|
|
69
77
|
"optional": true
|
|
70
78
|
}
|
|
71
79
|
},
|
|
72
|
-
"
|
|
73
|
-
"@orpc/server": "2.0.0-beta.48",
|
|
74
|
-
"@orpc/shared": "2.0.0-beta.48"
|
|
75
|
-
},
|
|
76
|
-
"devDependencies": {
|
|
77
|
-
"@upstash/redis": "^1.40.0",
|
|
78
|
-
"redis": "^6.3.1"
|
|
79
|
-
},
|
|
80
|
-
"scripts": {
|
|
81
|
-
"type:check": "tsc -b"
|
|
82
|
-
}
|
|
80
|
+
"scripts": {}
|
|
83
81
|
}
|
|
@@ -1,62 +0,0 @@
|
|
|
1
|
-
import type { Promisable } from "@orpc/shared";
|
|
2
|
-
import type { LockCallbackOptions, Locker, LockOptions } from "../types.mjs";
|
|
3
|
-
/**
|
|
4
|
-
* Options shared by every Redis-backed locker adapter.
|
|
5
|
-
*
|
|
6
|
-
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
7
|
-
*/
|
|
8
|
-
export interface BaseRedisLockerOptions {
|
|
9
|
-
/**
|
|
10
|
-
* The prefix to use for Redis keys.
|
|
11
|
-
*
|
|
12
|
-
* @default ''
|
|
13
|
-
*/
|
|
14
|
-
prefix?: string | undefined;
|
|
15
|
-
/**
|
|
16
|
-
* How long a lock is held before it expires automatically, in milliseconds.
|
|
17
|
-
* Guards against holders that never release the lock, such as a crashed process.
|
|
18
|
-
* Can be overridden per call.
|
|
19
|
-
*/
|
|
20
|
-
ttl: number;
|
|
21
|
-
/**
|
|
22
|
-
* How long to wait for a lock to become available, in milliseconds.
|
|
23
|
-
* Can be overridden per call.
|
|
24
|
-
*
|
|
25
|
-
* @default 10000
|
|
26
|
-
*/
|
|
27
|
-
timeout?: number | undefined;
|
|
28
|
-
/**
|
|
29
|
-
* How long to wait between acquisition attempts while the lock
|
|
30
|
-
* is held by someone else, in milliseconds.
|
|
31
|
-
*
|
|
32
|
-
* @default 100
|
|
33
|
-
*/
|
|
34
|
-
retryInterval?: number | undefined;
|
|
35
|
-
}
|
|
36
|
-
/**
|
|
37
|
-
* Base class for Redis-backed locker adapters. It owns the key naming, the lock
|
|
38
|
-
* token, the acquisition loop, and the atomic Lua release, so every adapter built
|
|
39
|
-
* on it can share locks with the others regardless of the Redis client in use.
|
|
40
|
-
*
|
|
41
|
-
* Extend it and implement the abstract methods to support another Redis client.
|
|
42
|
-
*
|
|
43
|
-
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
44
|
-
*/
|
|
45
|
-
export declare abstract class BaseRedisLocker implements Locker {
|
|
46
|
-
protected readonly keyPrefix: string;
|
|
47
|
-
protected readonly ttl: number;
|
|
48
|
-
protected readonly timeout: number;
|
|
49
|
-
protected readonly retryInterval: number;
|
|
50
|
-
constructor(options: BaseRedisLockerOptions);
|
|
51
|
-
/**
|
|
52
|
-
* Sets `key` to `token` only when it does not exist yet, with an expiry
|
|
53
|
-
* of `ttl` milliseconds (`SET key token NX PX ttl`), and resolves with
|
|
54
|
-
* whether the key was set.
|
|
55
|
-
*/
|
|
56
|
-
protected abstract acquire(key: string, token: string, ttl: number): Promise<boolean>;
|
|
57
|
-
/**
|
|
58
|
-
* Runs a Lua script (`EVAL script numkeys key [key ...] arg [arg ...]`).
|
|
59
|
-
*/
|
|
60
|
-
protected abstract evalScript(script: string, keys: string[], args: string[]): Promise<unknown>;
|
|
61
|
-
lock<T>(key: string, fn: (options: LockCallbackOptions) => Promisable<T>, options?: LockOptions): Promise<T>;
|
|
62
|
-
}
|
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
import { sleep, throwIfAborted } from "@orpc/shared";
|
|
2
|
-
import { LockTimeoutError } from "../error.mjs";
|
|
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
|
-
export class BaseRedisLocker {
|
|
12
|
-
keyPrefix;
|
|
13
|
-
ttl;
|
|
14
|
-
timeout;
|
|
15
|
-
retryInterval;
|
|
16
|
-
constructor(options) {
|
|
17
|
-
this.keyPrefix = options.prefix ?? "";
|
|
18
|
-
this.ttl = options.ttl;
|
|
19
|
-
this.timeout = options.timeout ?? 1e4;
|
|
20
|
-
this.retryInterval = options.retryInterval ?? 100;
|
|
21
|
-
}
|
|
22
|
-
async lock(key, fn, options = {}) {
|
|
23
|
-
const prefixedKey = `${this.keyPrefix}${key}`;
|
|
24
|
-
const ttl = options.ttl ?? this.ttl;
|
|
25
|
-
const deadline = Date.now() + (options.timeout ?? this.timeout);
|
|
26
|
-
const token = crypto.randomUUID();
|
|
27
|
-
let waited = false;
|
|
28
|
-
throwIfAborted(options.signal);
|
|
29
|
-
while (!await this.acquire(prefixedKey, token, ttl)) {
|
|
30
|
-
const remaining = deadline - Date.now();
|
|
31
|
-
if (remaining <= 0) {
|
|
32
|
-
throw new LockTimeoutError(key);
|
|
33
|
-
}
|
|
34
|
-
waited = true;
|
|
35
|
-
await sleep(Math.min(this.retryInterval, remaining), { signal: options.signal });
|
|
36
|
-
}
|
|
37
|
-
try {
|
|
38
|
-
return await fn({ waited });
|
|
39
|
-
} finally {
|
|
40
|
-
await this.evalScript(RELEASE_LOCK_SCRIPT, [prefixedKey], [token]);
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
}
|
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import type { Promisable } from "@orpc/shared";
|
|
2
|
-
import type { LockCallbackOptions, Locker, LockOptions } from "../types.mjs";
|
|
3
|
-
export interface MemoryLockerOptions {
|
|
4
|
-
/**
|
|
5
|
-
* How long a lock is held before it expires automatically, in milliseconds.
|
|
6
|
-
* Guards against holders that never release the lock.
|
|
7
|
-
* Can be overridden per call.
|
|
8
|
-
*
|
|
9
|
-
* @default undefined (held until released)
|
|
10
|
-
*/
|
|
11
|
-
ttl?: number | undefined;
|
|
12
|
-
/**
|
|
13
|
-
* How long to wait for a lock to become available, in milliseconds.
|
|
14
|
-
* Can be overridden per call.
|
|
15
|
-
*
|
|
16
|
-
* @default 10000
|
|
17
|
-
*/
|
|
18
|
-
timeout?: number | undefined;
|
|
19
|
-
}
|
|
20
|
-
/**
|
|
21
|
-
* Locker adapter backed by in-memory storage, so locks are only shared within
|
|
22
|
-
* the current process. Waiters acquire the lock in order, without polling.
|
|
23
|
-
*
|
|
24
|
-
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
25
|
-
*/
|
|
26
|
-
export declare class MemoryLocker implements Locker {
|
|
27
|
-
private readonly ttl;
|
|
28
|
-
private readonly timeout;
|
|
29
|
-
private readonly entries;
|
|
30
|
-
constructor(options?: MemoryLockerOptions);
|
|
31
|
-
lock<T>(key: string, fn: (options: LockCallbackOptions) => Promisable<T>, options?: LockOptions): Promise<T>;
|
|
32
|
-
private wait;
|
|
33
|
-
private release;
|
|
34
|
-
}
|
package/dist/adapters/memory.mjs
DELETED
|
@@ -1,74 +0,0 @@
|
|
|
1
|
-
import { promiseWithResolvers, throwIfAborted } from "@orpc/shared";
|
|
2
|
-
import { LockTimeoutError } from "../error.mjs";
|
|
3
|
-
|
|
4
|
-
export class MemoryLocker {
|
|
5
|
-
ttl;
|
|
6
|
-
timeout;
|
|
7
|
-
entries = new Map();
|
|
8
|
-
constructor(options = {}) {
|
|
9
|
-
this.ttl = options.ttl;
|
|
10
|
-
this.timeout = options.timeout ?? 1e4;
|
|
11
|
-
}
|
|
12
|
-
async lock(key, fn, options = {}) {
|
|
13
|
-
const ttl = options.ttl ?? this.ttl;
|
|
14
|
-
const timeout = options.timeout ?? this.timeout;
|
|
15
|
-
const token = {};
|
|
16
|
-
throwIfAborted(options.signal);
|
|
17
|
-
let entry = this.entries.get(key);
|
|
18
|
-
const waited = entry !== undefined;
|
|
19
|
-
if (entry) {
|
|
20
|
-
await this.wait(key, entry, token, timeout, options.signal);
|
|
21
|
-
} else {
|
|
22
|
-
entry = {
|
|
23
|
-
holder: token,
|
|
24
|
-
waiters: new Set()
|
|
25
|
-
};
|
|
26
|
-
this.entries.set(key, entry);
|
|
27
|
-
}
|
|
28
|
-
if (ttl !== undefined) {
|
|
29
|
-
entry.expiry = setTimeout(() => this.release(key, token), ttl);
|
|
30
|
-
}
|
|
31
|
-
try {
|
|
32
|
-
return await fn({ waited });
|
|
33
|
-
} finally {
|
|
34
|
-
this.release(key, token);
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
wait(key, entry, token, timeout, signal) {
|
|
38
|
-
if (timeout <= 0) {
|
|
39
|
-
return Promise.reject(new LockTimeoutError(key));
|
|
40
|
-
}
|
|
41
|
-
const { promise, resolve, reject } = promiseWithResolvers();
|
|
42
|
-
const waiter = {
|
|
43
|
-
token,
|
|
44
|
-
resolve
|
|
45
|
-
};
|
|
46
|
-
entry.waiters.add(waiter);
|
|
47
|
-
const fail = (reason) => {
|
|
48
|
-
entry.waiters.delete(waiter);
|
|
49
|
-
reject(reason);
|
|
50
|
-
};
|
|
51
|
-
const timer = setTimeout(() => fail(new LockTimeoutError(key)), timeout);
|
|
52
|
-
const abortListener = () => fail(signal?.reason);
|
|
53
|
-
signal?.addEventListener("abort", abortListener, { once: true });
|
|
54
|
-
return promise.finally(() => {
|
|
55
|
-
clearTimeout(timer);
|
|
56
|
-
signal?.removeEventListener("abort", abortListener);
|
|
57
|
-
});
|
|
58
|
-
}
|
|
59
|
-
release(key, token) {
|
|
60
|
-
const entry = this.entries.get(key);
|
|
61
|
-
if (entry?.holder !== token) {
|
|
62
|
-
return;
|
|
63
|
-
}
|
|
64
|
-
clearTimeout(entry.expiry);
|
|
65
|
-
const [next] = entry.waiters;
|
|
66
|
-
if (!next) {
|
|
67
|
-
this.entries.delete(key);
|
|
68
|
-
return;
|
|
69
|
-
}
|
|
70
|
-
entry.waiters.delete(next);
|
|
71
|
-
entry.holder = next.token;
|
|
72
|
-
next.resolve();
|
|
73
|
-
}
|
|
74
|
-
}
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import type { RedisClientType } from "redis";
|
|
2
|
-
import type { BaseRedisLockerOptions } from "./base-redis.mjs";
|
|
3
|
-
import { BaseRedisLocker } from "./base-redis.mjs";
|
|
4
|
-
/**
|
|
5
|
-
* Locker adapter for Redis. Acquires locks with `SET NX PX` and releases them
|
|
6
|
-
* atomically with a Lua script, so every instance using the same server shares
|
|
7
|
-
* the same locks.
|
|
8
|
-
*
|
|
9
|
-
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
10
|
-
*/
|
|
11
|
-
export declare class RedisLocker extends BaseRedisLocker {
|
|
12
|
-
private readonly redis;
|
|
13
|
-
private readonly options;
|
|
14
|
-
constructor(redis: RedisClientType<any, any, any, any, any>, options: BaseRedisLockerOptions);
|
|
15
|
-
/**
|
|
16
|
-
* Creates a locker with `prefix` appended to this locker's prefix, sharing its Redis client.
|
|
17
|
-
*
|
|
18
|
-
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
19
|
-
*/
|
|
20
|
-
prefix(prefix: string): RedisLocker;
|
|
21
|
-
protected acquire(key: string, token: string, ttl: number): Promise<boolean>;
|
|
22
|
-
protected evalScript(script: string, keys: string[], args: string[]): Promise<unknown>;
|
|
23
|
-
private connectIfNeeded;
|
|
24
|
-
}
|
package/dist/adapters/redis.mjs
DELETED
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
import { BaseRedisLocker } from "./base-redis.mjs";
|
|
2
|
-
|
|
3
|
-
export class RedisLocker extends BaseRedisLocker {
|
|
4
|
-
redis;
|
|
5
|
-
options;
|
|
6
|
-
constructor(redis, options) {
|
|
7
|
-
super(options);
|
|
8
|
-
this.redis = redis;
|
|
9
|
-
this.options = options;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
prefix(prefix) {
|
|
13
|
-
return new RedisLocker(this.redis, {
|
|
14
|
-
...this.options,
|
|
15
|
-
prefix: `${this.keyPrefix}${prefix}`
|
|
16
|
-
});
|
|
17
|
-
}
|
|
18
|
-
async acquire(key, token, ttl) {
|
|
19
|
-
await this.connectIfNeeded();
|
|
20
|
-
const result = await this.redis.set(key, token, {
|
|
21
|
-
condition: "NX",
|
|
22
|
-
expiration: {
|
|
23
|
-
type: "PX",
|
|
24
|
-
value: ttl
|
|
25
|
-
}
|
|
26
|
-
});
|
|
27
|
-
return result === "OK";
|
|
28
|
-
}
|
|
29
|
-
async evalScript(script, keys, args) {
|
|
30
|
-
await this.connectIfNeeded();
|
|
31
|
-
return await this.redis.eval(script, {
|
|
32
|
-
keys,
|
|
33
|
-
arguments: args
|
|
34
|
-
});
|
|
35
|
-
}
|
|
36
|
-
async connectIfNeeded() {
|
|
37
|
-
if (!this.redis.isOpen) {
|
|
38
|
-
await this.redis.connect();
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
|
-
}
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import type { Redis } from "@upstash/redis";
|
|
2
|
-
import type { BaseRedisLockerOptions } from "./base-redis.mjs";
|
|
3
|
-
import { BaseRedisLocker } from "./base-redis.mjs";
|
|
4
|
-
/**
|
|
5
|
-
* Locker adapter for Upstash Redis. Acquires locks with `SET NX PX` and releases
|
|
6
|
-
* them atomically with a Lua script, so it shares locks with `RedisLocker`.
|
|
7
|
-
* A good fit for serverless and edge runtimes.
|
|
8
|
-
*
|
|
9
|
-
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
10
|
-
*/
|
|
11
|
-
export declare class UpstashLocker extends BaseRedisLocker {
|
|
12
|
-
private readonly redis;
|
|
13
|
-
private readonly options;
|
|
14
|
-
constructor(redis: Redis, options: BaseRedisLockerOptions);
|
|
15
|
-
/**
|
|
16
|
-
* Creates a locker with `prefix` appended to this locker's prefix, sharing its Redis client.
|
|
17
|
-
*
|
|
18
|
-
* @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
|
|
19
|
-
*/
|
|
20
|
-
prefix(prefix: string): UpstashLocker;
|
|
21
|
-
protected acquire(key: string, token: string, ttl: number): Promise<boolean>;
|
|
22
|
-
protected evalScript(script: string, keys: string[], args: string[]): Promise<unknown>;
|
|
23
|
-
}
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import { BaseRedisLocker } from "./base-redis.mjs";
|
|
2
|
-
|
|
3
|
-
export class UpstashLocker extends BaseRedisLocker {
|
|
4
|
-
redis;
|
|
5
|
-
options;
|
|
6
|
-
constructor(redis, options) {
|
|
7
|
-
super(options);
|
|
8
|
-
this.redis = redis;
|
|
9
|
-
this.options = options;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
prefix(prefix) {
|
|
13
|
-
return new UpstashLocker(this.redis, {
|
|
14
|
-
...this.options,
|
|
15
|
-
prefix: `${this.keyPrefix}${prefix}`
|
|
16
|
-
});
|
|
17
|
-
}
|
|
18
|
-
async acquire(key, token, ttl) {
|
|
19
|
-
const result = await this.redis.set(key, token, {
|
|
20
|
-
nx: true,
|
|
21
|
-
px: ttl
|
|
22
|
-
});
|
|
23
|
-
return result === "OK";
|
|
24
|
-
}
|
|
25
|
-
async evalScript(script, keys, args) {
|
|
26
|
-
return await this.redis.eval(script, keys, args);
|
|
27
|
-
}
|
|
28
|
-
}
|
package/dist/error.d.mts
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
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.mjs
DELETED
package/dist/index.d.mts
DELETED
package/dist/index.mjs
DELETED
package/dist/middleware.d.mts
DELETED
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
import type { Context, Middleware, MiddlewareOptions } from "@orpc/server";
|
|
2
|
-
import type { Promisable, Value } from "@orpc/shared";
|
|
3
|
-
import type { Locker } from "./types.mjs";
|
|
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<
|
|
25
|
-
TInContext extends Context,
|
|
26
|
-
TInput
|
|
27
|
-
> {
|
|
28
|
-
/**
|
|
29
|
-
* The locker to acquire the lock from
|
|
30
|
-
*/
|
|
31
|
-
locker: Value<Promisable<Locker>, [options: MiddlewareOptions<TInContext, unknown, Record<never, never>>, input: TInput]>;
|
|
32
|
-
/**
|
|
33
|
-
* The key to identify the work that must not run concurrently
|
|
34
|
-
*/
|
|
35
|
-
key: Value<Promisable<string>, [options: MiddlewareOptions<TInContext, unknown, Record<never, never>>, input: TInput]>;
|
|
36
|
-
/**
|
|
37
|
-
* How long the lock is held before it expires automatically, in milliseconds.
|
|
38
|
-
*
|
|
39
|
-
* @default the adapter default
|
|
40
|
-
*/
|
|
41
|
-
ttl?: Value<Promisable<number | undefined>, [options: MiddlewareOptions<TInContext, unknown, Record<never, never>>, input: TInput]> | undefined;
|
|
42
|
-
/**
|
|
43
|
-
* How long to wait for the lock to become available, in milliseconds.
|
|
44
|
-
*
|
|
45
|
-
* @default the adapter default
|
|
46
|
-
*/
|
|
47
|
-
timeout?: Value<Promisable<number | undefined>, [options: MiddlewareOptions<TInContext, unknown, Record<never, never>>, input: TInput]> | undefined;
|
|
48
|
-
/**
|
|
49
|
-
* If your lock middleware is used multiple times
|
|
50
|
-
* or you invoke a procedure inside another procedure (shared the same context) that also has
|
|
51
|
-
* lock middleware **with the same locker and key**, this option
|
|
52
|
-
* will ensure that the lock is only acquired once per request,
|
|
53
|
-
* instead of waiting for itself until the timeout elapses.
|
|
54
|
-
*
|
|
55
|
-
* @default true
|
|
56
|
-
*/
|
|
57
|
-
dedupe?: boolean | undefined;
|
|
58
|
-
}
|
|
59
|
-
/**
|
|
60
|
-
* Creates a middleware that runs oRPC procedures under a lock, so that calls
|
|
61
|
-
* sharing the same key never run concurrently. Rejects with a `CONFLICT` error
|
|
62
|
-
* when the lock cannot be acquired before the timeout elapses.
|
|
63
|
-
*
|
|
64
|
-
* @see {@link https://orpc.dev/docs/helpers/lock#lock-middleware | Lock Helpers - Lock Middleware}
|
|
65
|
-
*/
|
|
66
|
-
export declare function lock<
|
|
67
|
-
TInContext extends Context,
|
|
68
|
-
TInput
|
|
69
|
-
>({ dedupe, ...options }: LockMiddlewareOptions<TInContext, TInput>): Middleware<TInContext, LockMiddlewareOutContext, TInput, any, object>;
|
package/dist/middleware.mjs
DELETED
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
import { ORPCError } from "@orpc/server";
|
|
2
|
-
import { toArray, value } from "@orpc/shared";
|
|
3
|
-
import { LockTimeoutError } from "./error.mjs";
|
|
4
|
-
export const LOCK_MIDDLEWARE_CONTEXT_SYMBOL = /* @__PURE__ */ Symbol.for("ORPC_LOCK_MIDDLEWARE_CONTEXT");
|
|
5
|
-
|
|
6
|
-
export function lock({ dedupe = true, ...options }) {
|
|
7
|
-
return async function lock(middlewareOptions, input) {
|
|
8
|
-
const [locker, key, ttl, timeout] = await Promise.all([
|
|
9
|
-
value(options.locker, middlewareOptions, input),
|
|
10
|
-
value(options.key, middlewareOptions, input),
|
|
11
|
-
value(options.ttl, middlewareOptions, input),
|
|
12
|
-
value(options.timeout, middlewareOptions, input)
|
|
13
|
-
]);
|
|
14
|
-
const middlewareContext = middlewareOptions.context[LOCK_MIDDLEWARE_CONTEXT_SYMBOL];
|
|
15
|
-
const held = middlewareContext?.held.find((l) => l.key === key && l.locker === locker);
|
|
16
|
-
if (dedupe && held) {
|
|
17
|
-
return middlewareOptions.next({ context: { "lock/waited": held.waited } });
|
|
18
|
-
}
|
|
19
|
-
let acquired = false;
|
|
20
|
-
try {
|
|
21
|
-
return await locker.lock(key, ({ waited }) => {
|
|
22
|
-
acquired = true;
|
|
23
|
-
return middlewareOptions.next({ context: {
|
|
24
|
-
"lock/waited": waited,
|
|
25
|
-
[LOCK_MIDDLEWARE_CONTEXT_SYMBOL]: {
|
|
26
|
-
...middlewareContext,
|
|
27
|
-
held: [...toArray(middlewareContext?.held), {
|
|
28
|
-
locker,
|
|
29
|
-
key,
|
|
30
|
-
waited
|
|
31
|
-
}]
|
|
32
|
-
}
|
|
33
|
-
} });
|
|
34
|
-
}, {
|
|
35
|
-
ttl,
|
|
36
|
-
timeout,
|
|
37
|
-
signal: middlewareOptions.signal
|
|
38
|
-
});
|
|
39
|
-
} catch (error) {
|
|
40
|
-
if (!acquired && error instanceof LockTimeoutError) {
|
|
41
|
-
throw new ORPCError("CONFLICT", { cause: error });
|
|
42
|
-
}
|
|
43
|
-
throw error;
|
|
44
|
-
}
|
|
45
|
-
};
|
|
46
|
-
}
|
package/dist/types.d.mts
DELETED
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
import type { Promisable } from "@orpc/shared";
|
|
2
|
-
export interface LockOptions {
|
|
3
|
-
/**
|
|
4
|
-
* How long the lock is held before it expires automatically, in milliseconds.
|
|
5
|
-
* Guards against holders that never release the lock, such as a crashed process.
|
|
6
|
-
*
|
|
7
|
-
* @default the adapter default
|
|
8
|
-
*/
|
|
9
|
-
ttl?: number | undefined;
|
|
10
|
-
/**
|
|
11
|
-
* How long to wait for the lock to become available, in milliseconds.
|
|
12
|
-
*
|
|
13
|
-
* @default the adapter default
|
|
14
|
-
*/
|
|
15
|
-
timeout?: number | undefined;
|
|
16
|
-
/**
|
|
17
|
-
* Aborts waiting for the lock. Has no effect once the lock is acquired.
|
|
18
|
-
*/
|
|
19
|
-
signal?: AbortSignal | undefined;
|
|
20
|
-
}
|
|
21
|
-
export interface LockCallbackOptions {
|
|
22
|
-
/**
|
|
23
|
-
* Whether the lock was acquired only after waiting for another holder to release it.
|
|
24
|
-
* `false` means the lock was acquired immediately.
|
|
25
|
-
*/
|
|
26
|
-
waited: boolean;
|
|
27
|
-
}
|
|
28
|
-
/**
|
|
29
|
-
* Standard interface for running work under a lock, so that work sharing
|
|
30
|
-
* the same key never runs concurrently.
|
|
31
|
-
* Implement it for custom strategies, or use one of the provided adapters.
|
|
32
|
-
*
|
|
33
|
-
* @see {@link https://orpc.dev/docs/helpers/lock | Lock Helpers}
|
|
34
|
-
*/
|
|
35
|
-
export interface Locker {
|
|
36
|
-
/**
|
|
37
|
-
* Runs `fn` while holding the lock for `key`, and releases the lock afterwards,
|
|
38
|
-
* even when `fn` throws.
|
|
39
|
-
*
|
|
40
|
-
* @throws {LockTimeoutError} when the lock cannot be acquired before the timeout elapses
|
|
41
|
-
*/
|
|
42
|
-
lock<T>(key: string, fn: (options: LockCallbackOptions) => Promisable<T>, options?: LockOptions): Promise<T>;
|
|
43
|
-
}
|
|
File without changes
|