@orpc/experimental-lock 2.0.0-beta.48 → 2.0.0-beta.50

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 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="weekly downloads" src="https://img.shields.io/npm/dw/%40orpc%2Fexperimental-lock?logo=npm" />
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&amp;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&amp;v=4" width="64" alt="Macroscope"/><br />Macroscope</a></td>
212
212
  </tr>
213
213
  </table>
214
214
 
@@ -0,0 +1,62 @@
1
+ import { LockCallbackOptions, LockOptions, Locker } from "../types.js";
2
+ import { Promisable } from "@orpc/shared";
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,5 +1,6 @@
1
+ import { LockTimeoutError } from "../error.js";
1
2
  import { sleep, throwIfAborted } from "@orpc/shared";
2
- import { LockTimeoutError } from "../error.mjs";
3
+ // src/adapters/base-redis.ts
3
4
  const RELEASE_LOCK_SCRIPT = `
4
5
  if redis.call('GET', KEYS[1]) == ARGV[1] then
5
6
  return redis.call('DEL', KEYS[1])
@@ -7,8 +8,16 @@ end
7
8
 
8
9
  return 0
9
10
  `;
10
-
11
- export class BaseRedisLocker {
11
+ /**
12
+ * Base class for Redis-backed locker adapters. It owns the key naming, the lock
13
+ * token, the acquisition loop, and the atomic Lua release, so every adapter built
14
+ * on it can share locks with the others regardless of the Redis client in use.
15
+ *
16
+ * Extend it and implement the abstract methods to support another Redis client.
17
+ *
18
+ * @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
19
+ */
20
+ var BaseRedisLocker = class {
12
21
  keyPrefix;
13
22
  ttl;
14
23
  timeout;
@@ -28,16 +37,17 @@ export class BaseRedisLocker {
28
37
  throwIfAborted(options.signal);
29
38
  while (!await this.acquire(prefixedKey, token, ttl)) {
30
39
  const remaining = deadline - Date.now();
31
- if (remaining <= 0) {
32
- throw new LockTimeoutError(key);
33
- }
40
+ if (remaining <= 0) throw new LockTimeoutError(key);
34
41
  waited = true;
35
42
  await sleep(Math.min(this.retryInterval, remaining), { signal: options.signal });
36
43
  }
37
44
  try {
38
45
  return await fn({ waited });
39
46
  } finally {
40
- await this.evalScript(RELEASE_LOCK_SCRIPT, [prefixedKey], [token]);
47
+ try {
48
+ await this.evalScript(RELEASE_LOCK_SCRIPT, [prefixedKey], [token]);
49
+ } catch {}
41
50
  }
42
51
  }
43
- }
52
+ };
53
+ export { BaseRedisLocker };
@@ -0,0 +1,34 @@
1
+ import { LockCallbackOptions, LockOptions, Locker } from "../types.js";
2
+ import { Promisable } from "@orpc/shared";
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
+ }
@@ -1,10 +1,16 @@
1
+ import { LockTimeoutError } from "../error.js";
1
2
  import { promiseWithResolvers, throwIfAborted } from "@orpc/shared";
2
- import { LockTimeoutError } from "../error.mjs";
3
-
4
- export class MemoryLocker {
3
+ // src/adapters/memory.ts
4
+ /**
5
+ * Locker adapter backed by in-memory storage, so locks are only shared within
6
+ * the current process. Waiters acquire the lock in order, without polling.
7
+ *
8
+ * @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
9
+ */
10
+ var MemoryLocker = class {
5
11
  ttl;
6
12
  timeout;
7
- entries = new Map();
13
+ entries = /* @__PURE__ */ new Map();
8
14
  constructor(options = {}) {
9
15
  this.ttl = options.ttl;
10
16
  this.timeout = options.timeout ?? 1e4;
@@ -15,19 +21,16 @@ export class MemoryLocker {
15
21
  const token = {};
16
22
  throwIfAborted(options.signal);
17
23
  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 {
24
+ const waited = entry !== void 0;
25
+ if (entry) await this.wait(key, entry, token, timeout, options.signal);
26
+ else {
22
27
  entry = {
23
28
  holder: token,
24
- waiters: new Set()
29
+ waiters: /* @__PURE__ */ new Set()
25
30
  };
26
31
  this.entries.set(key, entry);
27
32
  }
28
- if (ttl !== undefined) {
29
- entry.expiry = setTimeout(() => this.release(key, token), ttl);
30
- }
33
+ if (ttl !== void 0) entry.expiry = setTimeout(() => this.release(key, token), ttl);
31
34
  try {
32
35
  return await fn({ waited });
33
36
  } finally {
@@ -35,9 +38,7 @@ export class MemoryLocker {
35
38
  }
36
39
  }
37
40
  wait(key, entry, token, timeout, signal) {
38
- if (timeout <= 0) {
39
- return Promise.reject(new LockTimeoutError(key));
40
- }
41
+ if (timeout <= 0) return Promise.reject(new LockTimeoutError(key));
41
42
  const { promise, resolve, reject } = promiseWithResolvers();
42
43
  const waiter = {
43
44
  token,
@@ -58,9 +59,7 @@ export class MemoryLocker {
58
59
  }
59
60
  release(key, token) {
60
61
  const entry = this.entries.get(key);
61
- if (entry?.holder !== token) {
62
- return;
63
- }
62
+ if (entry?.holder !== token) return;
64
63
  clearTimeout(entry.expiry);
65
64
  const [next] = entry.waiters;
66
65
  if (!next) {
@@ -71,4 +70,5 @@ export class MemoryLocker {
71
70
  entry.holder = next.token;
72
71
  next.resolve();
73
72
  }
74
- }
73
+ };
74
+ export { MemoryLocker };
@@ -0,0 +1,23 @@
1
+ import { BaseRedisLocker, BaseRedisLockerOptions } from "./base-redis.js";
2
+ import { RedisClientType } from "redis";
3
+ /**
4
+ * Locker adapter for Redis. Acquires locks with `SET NX PX` and releases them
5
+ * atomically with a Lua script, so every instance using the same server shares
6
+ * the same locks.
7
+ *
8
+ * @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
9
+ */
10
+ export declare class RedisLocker extends BaseRedisLocker {
11
+ private readonly redis;
12
+ private readonly options;
13
+ constructor(redis: RedisClientType<any, any, any, any, any>, options: BaseRedisLockerOptions);
14
+ /**
15
+ * Creates a locker with `prefix` appended to this locker's prefix, sharing its Redis client.
16
+ *
17
+ * @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
18
+ */
19
+ prefix(prefix: string): RedisLocker;
20
+ protected acquire(key: string, token: string, ttl: number): Promise<boolean>;
21
+ protected evalScript(script: string, keys: string[], args: string[]): Promise<unknown>;
22
+ private connectIfNeeded;
23
+ }
@@ -0,0 +1,50 @@
1
+ import { BaseRedisLocker } from "./base-redis.js";
2
+ // src/adapters/redis.ts
3
+ /**
4
+ * Locker adapter for Redis. Acquires locks with `SET NX PX` and releases them
5
+ * atomically with a Lua script, so every instance using the same server shares
6
+ * the same locks.
7
+ *
8
+ * @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
9
+ */
10
+ var RedisLocker = class RedisLocker extends BaseRedisLocker {
11
+ redis;
12
+ options;
13
+ constructor(redis, options) {
14
+ super(options);
15
+ this.redis = redis;
16
+ this.options = options;
17
+ }
18
+ /**
19
+ * Creates a locker with `prefix` appended to this locker's prefix, sharing its Redis client.
20
+ *
21
+ * @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
22
+ */
23
+ prefix(prefix) {
24
+ return new RedisLocker(this.redis, {
25
+ ...this.options,
26
+ prefix: `${this.keyPrefix}${prefix}`
27
+ });
28
+ }
29
+ async acquire(key, token, ttl) {
30
+ await this.connectIfNeeded();
31
+ return await this.redis.set(key, token, {
32
+ condition: "NX",
33
+ expiration: {
34
+ type: "PX",
35
+ value: ttl
36
+ }
37
+ }) === "OK";
38
+ }
39
+ async evalScript(script, keys, args) {
40
+ await this.connectIfNeeded();
41
+ return await this.redis.eval(script, {
42
+ keys,
43
+ arguments: args
44
+ });
45
+ }
46
+ async connectIfNeeded() {
47
+ if (!this.redis.isOpen) await this.redis.connect();
48
+ }
49
+ };
50
+ export { RedisLocker };
@@ -0,0 +1,22 @@
1
+ import { BaseRedisLocker, BaseRedisLockerOptions } from "./base-redis.js";
2
+ import { Redis } from "@upstash/redis";
3
+ /**
4
+ * Locker adapter for Upstash Redis. Acquires locks with `SET NX PX` and releases
5
+ * them atomically with a Lua script, so it shares locks with `RedisLocker`.
6
+ * A good fit for serverless and edge runtimes.
7
+ *
8
+ * @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
9
+ */
10
+ export declare class UpstashLocker extends BaseRedisLocker {
11
+ private readonly redis;
12
+ private readonly options;
13
+ constructor(redis: Redis, options: BaseRedisLockerOptions);
14
+ /**
15
+ * Creates a locker with `prefix` appended to this locker's prefix, sharing its Redis client.
16
+ *
17
+ * @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
18
+ */
19
+ prefix(prefix: string): UpstashLocker;
20
+ protected acquire(key: string, token: string, ttl: number): Promise<boolean>;
21
+ protected evalScript(script: string, keys: string[], args: string[]): Promise<unknown>;
22
+ }
@@ -0,0 +1,39 @@
1
+ import { BaseRedisLocker } from "./base-redis.js";
2
+ // src/adapters/upstash.ts
3
+ /**
4
+ * Locker adapter for Upstash Redis. Acquires locks with `SET NX PX` and releases
5
+ * them atomically with a Lua script, so it shares locks with `RedisLocker`.
6
+ * A good fit for serverless and edge runtimes.
7
+ *
8
+ * @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
9
+ */
10
+ var UpstashLocker = class UpstashLocker extends BaseRedisLocker {
11
+ redis;
12
+ options;
13
+ constructor(redis, options) {
14
+ super(options);
15
+ this.redis = redis;
16
+ this.options = options;
17
+ }
18
+ /**
19
+ * Creates a locker with `prefix` appended to this locker's prefix, sharing its Redis client.
20
+ *
21
+ * @see {@link https://orpc.dev/docs/helpers/lock#adapters | Lock Helpers - Adapters}
22
+ */
23
+ prefix(prefix) {
24
+ return new UpstashLocker(this.redis, {
25
+ ...this.options,
26
+ prefix: `${this.keyPrefix}${prefix}`
27
+ });
28
+ }
29
+ async acquire(key, token, ttl) {
30
+ return await this.redis.set(key, token, {
31
+ nx: true,
32
+ px: ttl
33
+ }) === "OK";
34
+ }
35
+ async evalScript(script, keys, args) {
36
+ return await this.redis.eval(script, keys, args);
37
+ }
38
+ };
39
+ export { UpstashLocker };
@@ -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,18 @@
1
+ // src/error.ts
2
+ /**
3
+ * Thrown when a lock cannot be acquired before the timeout elapses.
4
+ *
5
+ * @see {@link https://orpc.dev/docs/helpers/lock#options | Lock Helpers - Options}
6
+ */
7
+ var LockTimeoutError = class extends Error {
8
+ /**
9
+ * The key of the lock that could not be acquired.
10
+ */
11
+ key;
12
+ constructor(key) {
13
+ super(`Timed out waiting for the lock of key "${key}"`);
14
+ this.name = "LockTimeoutError";
15
+ this.key = key;
16
+ }
17
+ };
18
+ export { LockTimeoutError };
@@ -0,0 +1,4 @@
1
+ import { LockTimeoutError } from "./error.js";
2
+ import { LOCK_MIDDLEWARE_CONTEXT_SYMBOL, LockMiddlewareContext, LockMiddlewareOptions, LockMiddlewareOutContext, lock } from "./middleware.js";
3
+ import { LockCallbackOptions, LockOptions, Locker } from "./types.js";
4
+ export { LOCK_MIDDLEWARE_CONTEXT_SYMBOL, LockCallbackOptions, LockMiddlewareContext, LockMiddlewareOptions, LockMiddlewareOutContext, LockOptions, LockTimeoutError, Locker, lock };
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { LockTimeoutError } from "./error.js";
2
+ export { LOCK_MIDDLEWARE_CONTEXT_SYMBOL, lock } from "./middleware.js";
@@ -0,0 +1,63 @@
1
+ import { Locker } from "./types.js";
2
+ import { Context, Middleware, MiddlewareOptions } from "@orpc/server";
3
+ import { Promisable, Value } from "@orpc/shared";
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>, [options: MiddlewareOptions<TInContext, unknown, Record<never, never>>, input: TInput]>;
29
+ /**
30
+ * The key to identify the work that must not run concurrently
31
+ */
32
+ key: Value<Promisable<string>, [options: MiddlewareOptions<TInContext, unknown, Record<never, never>>, input: TInput]>;
33
+ /**
34
+ * How long the lock is held before it expires automatically, in milliseconds.
35
+ *
36
+ * @default the adapter default
37
+ */
38
+ ttl?: Value<Promisable<number | undefined>, [options: MiddlewareOptions<TInContext, unknown, Record<never, never>>, input: TInput]> | undefined;
39
+ /**
40
+ * How long to wait for the lock to become available, in milliseconds.
41
+ *
42
+ * @default the adapter default
43
+ */
44
+ timeout?: Value<Promisable<number | undefined>, [options: MiddlewareOptions<TInContext, unknown, Record<never, never>>, input: TInput]> | undefined;
45
+ /**
46
+ * If your lock middleware is used multiple times
47
+ * or you invoke a procedure inside another procedure (shared the same context) that also has
48
+ * lock middleware **with the same locker and key**, this option
49
+ * will ensure that the lock is only acquired once per request,
50
+ * instead of waiting for itself until the timeout elapses.
51
+ *
52
+ * @default true
53
+ */
54
+ dedupe?: boolean | undefined;
55
+ }
56
+ /**
57
+ * Creates a middleware that runs oRPC procedures under a lock, so that calls
58
+ * sharing the same key never run concurrently. Rejects with a `CONFLICT` error
59
+ * when the lock cannot be acquired before the timeout elapses.
60
+ *
61
+ * @see {@link https://orpc.dev/docs/helpers/lock#lock-middleware | Lock Helpers - Lock Middleware}
62
+ */
63
+ export declare function lock<TInContext extends Context, TInput>({ dedupe, ...options }: LockMiddlewareOptions<TInContext, TInput>): Middleware<TInContext, LockMiddlewareOutContext, TInput, any, object>;
@@ -1,9 +1,16 @@
1
+ import { LockTimeoutError } from "./error.js";
1
2
  import { ORPCError } from "@orpc/server";
2
3
  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 }) {
4
+ // src/middleware.ts
5
+ const LOCK_MIDDLEWARE_CONTEXT_SYMBOL = /* @__PURE__ */ Symbol.for("ORPC_LOCK_MIDDLEWARE_CONTEXT");
6
+ /**
7
+ * Creates a middleware that runs oRPC procedures under a lock, so that calls
8
+ * sharing the same key never run concurrently. Rejects with a `CONFLICT` error
9
+ * when the lock cannot be acquired before the timeout elapses.
10
+ *
11
+ * @see {@link https://orpc.dev/docs/helpers/lock#lock-middleware | Lock Helpers - Lock Middleware}
12
+ */
13
+ function lock({ dedupe = true, ...options }) {
7
14
  return async function lock(middlewareOptions, input) {
8
15
  const [locker, key, ttl, timeout] = await Promise.all([
9
16
  value(options.locker, middlewareOptions, input),
@@ -13,9 +20,7 @@ export function lock({ dedupe = true, ...options }) {
13
20
  ]);
14
21
  const middlewareContext = middlewareOptions.context[LOCK_MIDDLEWARE_CONTEXT_SYMBOL];
15
22
  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
- }
23
+ if (dedupe && held) return middlewareOptions.next({ context: { "lock/waited": held.waited } });
19
24
  let acquired = false;
20
25
  try {
21
26
  return await locker.lock(key, ({ waited }) => {
@@ -37,10 +42,9 @@ export function lock({ dedupe = true, ...options }) {
37
42
  signal: middlewareOptions.signal
38
43
  });
39
44
  } catch (error) {
40
- if (!acquired && error instanceof LockTimeoutError) {
41
- throw new ORPCError("CONFLICT", { cause: error });
42
- }
45
+ if (!acquired && error instanceof LockTimeoutError) throw new ORPCError("CONFLICT", { cause: error });
43
46
  throw error;
44
47
  }
45
48
  };
46
49
  }
50
+ export { LOCK_MIDDLEWARE_CONTEXT_SYMBOL, lock };
@@ -0,0 +1,43 @@
1
+ import { 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
- "type": "module",
4
- "version": "2.0.0-beta.48",
3
+ "version": "2.0.0-beta.50",
5
4
  "description": "Locking for oRPC procedures, with memory, Redis, and Upstash adapters",
6
- "license": "MIT",
7
- "funding": [
8
- "https://github.com/sponsors/dinwwwh",
9
- "https://opencollective.com/middleapi"
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
- "keywords": [
18
- "orpc",
19
- "lock",
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.mts",
33
- "import": "./dist/index.mjs",
34
- "default": "./dist/index.mjs"
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.mts",
38
- "import": "./dist/adapters/base-redis.mjs",
39
- "default": "./dist/adapters/base-redis.mjs"
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.mts",
43
- "import": "./dist/adapters/memory.mjs",
44
- "default": "./dist/adapters/memory.mjs"
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.mts",
48
- "import": "./dist/adapters/redis.mjs",
49
- "default": "./dist/adapters/redis.mjs"
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.mts",
53
- "import": "./dist/adapters/upstash.mjs",
54
- "default": "./dist/adapters/upstash.mjs"
55
+ "types": "./dist/adapters/upstash.d.ts",
56
+ "import": "./dist/adapters/upstash.js",
57
+ "default": "./dist/adapters/upstash.js"
55
58
  }
56
59
  },
57
- "files": [
58
- "dist"
59
- ],
60
+ "dependencies": {
61
+ "@orpc/server": "2.0.0-beta.50",
62
+ "@orpc/shared": "2.0.0-beta.50"
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
- "dependencies": {
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,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
- }
@@ -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
- }
@@ -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
@@ -1,10 +0,0 @@
1
-
2
- export class LockTimeoutError extends Error {
3
-
4
- key;
5
- constructor(key) {
6
- super(`Timed out waiting for the lock of key "${key}"`);
7
- this.name = "LockTimeoutError";
8
- this.key = key;
9
- }
10
- }
package/dist/index.d.mts DELETED
@@ -1,3 +0,0 @@
1
- export * from "./error.mjs";
2
- export * from "./middleware.mjs";
3
- export * from "./types.mjs";
package/dist/index.mjs DELETED
@@ -1,3 +0,0 @@
1
- export * from "./error.mjs";
2
- export * from "./middleware.mjs";
3
- export * from "./types.mjs";
@@ -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/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
- }
package/dist/types.mjs DELETED
@@ -1 +0,0 @@
1
- export {};