@drlock/redis 0.0.0-stage → 0.0.2
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/LICENSE +21 -0
- package/README.md +111 -2
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/reconnecting-subscriber.d.ts +22 -0
- package/dist/reconnecting-subscriber.d.ts.map +1 -0
- package/dist/reconnecting-subscriber.js +55 -0
- package/dist/reconnecting-subscriber.js.map +1 -0
- package/dist/redis.d.ts +47 -0
- package/dist/redis.d.ts.map +1 -0
- package/dist/redis.js +369 -0
- package/dist/redis.js.map +1 -0
- package/dist/types.d.ts +63 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/package.json +54 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dmitrii Golovin
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,112 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @drlock/redis
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Redis backend for `@drlock/core`: distributed, reentrant locks with atomic Lua
|
|
4
|
+
scripts and Pub/Sub wakeup. One batch = one round-trip (pipelined when the client
|
|
5
|
+
supports it).
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
Not published to npm yet. The commands below are the planned release layout.
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm i @drlock/core @drlock/redis ioredis
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
`ioredis` is not a dependency of this package — bring your own client implementing
|
|
16
|
+
the small `RedisCommandClient` / `RedisSubscriber` interfaces from `src/types.ts`.
|
|
17
|
+
ioredis works out of the box; other drivers need a thin adapter (their `eval`
|
|
18
|
+
signatures differ).
|
|
19
|
+
|
|
20
|
+
## Setup
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
import Redis from 'ioredis';
|
|
24
|
+
import { LockManager } from '@drlock/core';
|
|
25
|
+
import { RedisStore, ReconnectingRedisSubscriber } from '@drlock/redis';
|
|
26
|
+
|
|
27
|
+
const client = new Redis(process.env.REDIS_URL!); // commands + pipelining
|
|
28
|
+
const subscriberClient = client.duplicate(); // dedicated SUBSCRIBE connection
|
|
29
|
+
const subscriber = new ReconnectingRedisSubscriber({ client: subscriberClient });
|
|
30
|
+
|
|
31
|
+
const store = new RedisStore({
|
|
32
|
+
client,
|
|
33
|
+
subscriber, // optional: without it, acquisition falls back to polling
|
|
34
|
+
keyPrefix: 'drlock:', // namespace for lock keys
|
|
35
|
+
channelPrefix: 'drlock:events:',
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
const locks = new LockManager(store, { ttlMs: 10_000, acquireTimeoutMs: 5_000 });
|
|
39
|
+
|
|
40
|
+
await locks.runLocked('invoice:42', async () => {
|
|
41
|
+
// critical section; reentrant for the same context id
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
await locks.close(); // detaches handlers; connections stay open (caller owns them)
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### Graceful shutdown
|
|
48
|
+
|
|
49
|
+
On `SIGTERM`, wait for every lock this process holds to be released naturally before
|
|
50
|
+
closing — so no critical section is cut short mid-work:
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
process.on('SIGTERM', async () => {
|
|
54
|
+
await locks.waitAllReleased(); // resolves once all locks acquired by this process are released
|
|
55
|
+
await locks.close();
|
|
56
|
+
subscriberClient.disconnect();
|
|
57
|
+
client.disconnect();
|
|
58
|
+
});
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Notes
|
|
62
|
+
|
|
63
|
+
- Requires Lua scripting and Pub/Sub.
|
|
64
|
+
- A lock is a single JSON string `{ ctx, ttl, workers: [workerId] }`. Expiry is
|
|
65
|
+
the Redis key TTL (`PTTL` → `expiresAt`). Release removes the caller's worker,
|
|
66
|
+
deletes the key when it was the last one, and publishes `released`.
|
|
67
|
+
- `workers: string[]` in results is the sorted worker-id list.
|
|
68
|
+
- `acquire`/`release`/`getState` do one `GET` + `cjson.decode`; `list` scans.
|
|
69
|
+
Fresh locks use `SET ... PX`, and updates re-arm the remaining key TTL with
|
|
70
|
+
`SET ... PX <PTTL>`.
|
|
71
|
+
- Wakeups are hints: `subscribe(key, signal)` requires an `AbortSignal` (also the
|
|
72
|
+
unsubscribe). Awaiting it means `SUBSCRIBE` is active; its `awakePromise`
|
|
73
|
+
resolves on release, reconnect, or abort, then waiters re-check state. Without
|
|
74
|
+
`subscriber`, `subscribe()` throws
|
|
75
|
+
`LockSubscribeUnavailableError` immediately; `LockManager` treats that as
|
|
76
|
+
polling-only mode instead of logging it. Polling (`pollIntervalMs`) remains the
|
|
77
|
+
safety net.
|
|
78
|
+
- `ReconnectingRedisSubscriber` maps ioredis's second `ready` event to
|
|
79
|
+
`onReconnect`; ioredis itself reconnects and (by default) resubscribes.
|
|
80
|
+
Without the adapter, pass an `onReconnect` hook yourself or rely on polling.
|
|
81
|
+
Reconnect is tested at store level; the shared cross-worker suite does not
|
|
82
|
+
inject a reconnect proxy.
|
|
83
|
+
- There is no TTL renewal by design — pass a sufficient `ttlMs` up front.
|
|
84
|
+
- Transient errors (`ECONNRESET`, `ETIMEDOUT`, `LOADING`, `TRYAGAIN`, `READONLY`,
|
|
85
|
+
closed connections, ...) are retried: `maxAttempts` (default 3),
|
|
86
|
+
`retryDelayMs` (default 50, exponential). Retries are at-least-once.
|
|
87
|
+
- Scripts are cached with `EVALSHA` after the first `EVAL`; `NOSCRIPT` recovery
|
|
88
|
+
retries only the failed calls, so commands are not double-applied.
|
|
89
|
+
- Multi-key `acquire`/`release` uses `client.pipeline()` when available; otherwise
|
|
90
|
+
calls run sequentially.
|
|
91
|
+
- Run locks on a dedicated single-node/primary Redis, separate from cache/data.
|
|
92
|
+
Redis Cluster is **not a supported target**: `list()` is node-local and cluster
|
|
93
|
+
behavior is not exercised. Use a hash-tagged prefix (`keyPrefix:
|
|
94
|
+
'drlock:{locks}:'`) only if you accept that limitation.
|
|
95
|
+
- No Redlock/quorum — not a requirement for this project (not designed here). If
|
|
96
|
+
Redis is unavailable, lock calls fail; a failover can lose locks and briefly
|
|
97
|
+
break mutual exclusion. TTL expiry, the watchdog, and resource-side
|
|
98
|
+
version/CAS are the recovery story. Need quorum semantics — the `LockStore`
|
|
99
|
+
interface and cross-worker suite are open; write a custom store.
|
|
100
|
+
- `list()` uses `SCAN` over the namespace and is single-node. The store exhausts
|
|
101
|
+
the cursor inside Lua, so a large namespace can block that Redis for the
|
|
102
|
+
duration. `SCAN` is also required on ElastiCache Serverless, where `KEYS` is
|
|
103
|
+
unavailable.
|
|
104
|
+
- Connections are injected and never closed by the store; sharing instrumented
|
|
105
|
+
clients is fine. Always configure Redis timeouts (`commandTimeout`,
|
|
106
|
+
`connectTimeout`): manager deadlines are client-side races and cannot cancel
|
|
107
|
+
an in-flight command.
|
|
108
|
+
|
|
109
|
+
Details: [`src/redis.ts`](src/redis.ts); exported interfaces (incl. `RedisStoreLogFields`): [`src/types.ts`](src/types.ts). Contract, retries and
|
|
110
|
+
script-cache tests: [`test/store.test.ts`](test/store.test.ts); multi-process
|
|
111
|
+
behavior: [`test/cross-worker.test.ts`](test/cross-worker.test.ts) (9 shared
|
|
112
|
+
scenarios via `packages/core/test/cross-worker-suite.ts`).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { RedisStore } from './redis.ts';
|
|
2
|
+
export { ReconnectingRedisSubscriber } from './reconnecting-subscriber.ts';
|
|
3
|
+
export type { RedisCommandClient, RedisPipeline, RedisSubscriber, RedisSubscriberClient, ReconnectingRedisSubscriberOptions, RedisStoreOptions, RedisStoreLogFields } from './types.ts';
|
|
4
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAC3E,YAAY,EAAE,kBAAkB,EAAE,aAAa,EAAE,eAAe,EAAE,qBAAqB,EAAE,kCAAkC,EAAE,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC","sourcesContent":["export { RedisStore } from './redis.ts';\nexport { ReconnectingRedisSubscriber } from './reconnecting-subscriber.ts';\nexport type { RedisCommandClient, RedisPipeline, RedisSubscriber, RedisSubscriberClient, ReconnectingRedisSubscriberOptions, RedisStoreOptions, RedisStoreLogFields } from './types.ts';\n"]}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { ReconnectingRedisSubscriberOptions, RedisSubscriber } from './types.ts';
|
|
2
|
+
/**
|
|
3
|
+
* ioredis-compatible subscriber adapter: maps a post-initial `ready` to
|
|
4
|
+
* `onReconnect` so waiters re-check state.
|
|
5
|
+
*/
|
|
6
|
+
export declare class ReconnectingRedisSubscriber implements RedisSubscriber {
|
|
7
|
+
private readonly client;
|
|
8
|
+
private readonly logger;
|
|
9
|
+
private readonly messageListeners;
|
|
10
|
+
private readonly reconnectListeners;
|
|
11
|
+
private ready;
|
|
12
|
+
constructor(options: ReconnectingRedisSubscriberOptions);
|
|
13
|
+
subscribe(channel: string): Promise<unknown>;
|
|
14
|
+
unsubscribe(channel: string): Promise<unknown>;
|
|
15
|
+
on(event: 'message', listener: (channel: string, message: string) => void): this;
|
|
16
|
+
off(event: 'message', listener: (channel: string, message: string) => void): this;
|
|
17
|
+
onReconnect(listener: () => void): () => void;
|
|
18
|
+
private onMessage;
|
|
19
|
+
private onReady;
|
|
20
|
+
private onError;
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=reconnecting-subscriber.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reconnecting-subscriber.d.ts","sourceRoot":"","sources":["../src/reconnecting-subscriber.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,kCAAkC,EAAuB,eAAe,EAAyB,MAAM,YAAY,CAAC;AAElI;;;GAGG;AACH,qBAAa,2BAA4B,YAAW,eAAe;IACjE,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAwB;IAC/C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA8B;IACrD,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAyD;IAC1F,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAAyB;IAC5D,OAAO,CAAC,KAAK,CAAS;IAEtB,YAAY,OAAO,EAAE,kCAAkC,EAMtD;IAED,SAAS,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAE3C;IAED,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAE7C;IAED,EAAE,CAAC,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,IAAI,GAAG,IAAI,CAG/E;IAED,GAAG,CAAC,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,KAAK,IAAI,GAAG,IAAI,CAGhF;IAED,WAAW,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAG5C;IAED,OAAO,CAAC,SAAS,CAEf;IAEF,OAAO,CAAC,OAAO,CAMb;IAEF,OAAO,CAAC,OAAO,CAEb;CACH"}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { consoleLogger } from '@drlock/core';
|
|
2
|
+
/**
|
|
3
|
+
* ioredis-compatible subscriber adapter: maps a post-initial `ready` to
|
|
4
|
+
* `onReconnect` so waiters re-check state.
|
|
5
|
+
*/
|
|
6
|
+
export class ReconnectingRedisSubscriber {
|
|
7
|
+
client;
|
|
8
|
+
logger;
|
|
9
|
+
messageListeners = new Set();
|
|
10
|
+
reconnectListeners = new Set();
|
|
11
|
+
ready = false;
|
|
12
|
+
constructor(options) {
|
|
13
|
+
this.client = options.client;
|
|
14
|
+
this.logger = options.logger ?? consoleLogger();
|
|
15
|
+
this.client.on('message', this.onMessage);
|
|
16
|
+
this.client.on('ready', this.onReady);
|
|
17
|
+
this.client.on('error', this.onError);
|
|
18
|
+
}
|
|
19
|
+
subscribe(channel) {
|
|
20
|
+
return this.client.subscribe(channel);
|
|
21
|
+
}
|
|
22
|
+
unsubscribe(channel) {
|
|
23
|
+
return this.client.unsubscribe(channel);
|
|
24
|
+
}
|
|
25
|
+
on(event, listener) {
|
|
26
|
+
if (event === 'message')
|
|
27
|
+
this.messageListeners.add(listener);
|
|
28
|
+
return this;
|
|
29
|
+
}
|
|
30
|
+
off(event, listener) {
|
|
31
|
+
if (event === 'message')
|
|
32
|
+
this.messageListeners.delete(listener);
|
|
33
|
+
return this;
|
|
34
|
+
}
|
|
35
|
+
onReconnect(listener) {
|
|
36
|
+
this.reconnectListeners.add(listener);
|
|
37
|
+
return () => this.reconnectListeners.delete(listener);
|
|
38
|
+
}
|
|
39
|
+
onMessage = (channel, message) => {
|
|
40
|
+
for (const listener of this.messageListeners)
|
|
41
|
+
listener(channel, message);
|
|
42
|
+
};
|
|
43
|
+
onReady = () => {
|
|
44
|
+
if (!this.ready) {
|
|
45
|
+
this.ready = true;
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
for (const listener of this.reconnectListeners)
|
|
49
|
+
listener();
|
|
50
|
+
};
|
|
51
|
+
onError = (err) => {
|
|
52
|
+
this.logger.warn('Redis subscriber connection error', { err });
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
//# sourceMappingURL=reconnecting-subscriber.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reconnecting-subscriber.js","sourceRoot":"","sources":["../src/reconnecting-subscriber.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAI7C;;;GAGG;AACH,MAAM,OAAO,2BAA2B;IACrB,MAAM,CAAwB;IAC9B,MAAM,CAA8B;IACpC,gBAAgB,GAAG,IAAI,GAAG,EAA8C,CAAC;IACzE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C,OAAe,EAAE,OAAe,EAAQ,EAAE;QAC7D,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,gBAAgB;YAAE,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAC3E,CAAC,CAAC;IAEM,OAAO,GAAG,GAAS,EAAE;QAC3B,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;YAChB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;YAClB,OAAO;QACT,CAAC;QACD,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,kBAAkB;YAAE,QAAQ,EAAE,CAAC;IAC7D,CAAC,CAAC;IAEM,OAAO,GAAG,CAAC,GAAU,EAAQ,EAAE;QACrC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,mCAAmC,EAAE,EAAE,GAAG,EAAE,CAAC,CAAC;IACjE,CAAC,CAAC;CACH","sourcesContent":["import { consoleLogger } from '@drlock/core';\nimport type { Logger } from '@drlock/core';\nimport type { ReconnectingRedisSubscriberOptions, RedisStoreLogFields, RedisSubscriber, RedisSubscriberClient } from './types.ts';\n\n/**\n * ioredis-compatible subscriber adapter: maps a post-initial `ready` to\n * `onReconnect` so waiters re-check state.\n */\nexport class ReconnectingRedisSubscriber implements RedisSubscriber {\n private readonly client: RedisSubscriberClient;\n private readonly logger: Logger<RedisStoreLogFields>;\n private readonly messageListeners = new Set<(channel: string, message: string) => void>();\n private readonly reconnectListeners = new Set<() => void>();\n private ready = false;\n\n constructor(options: ReconnectingRedisSubscriberOptions) {\n this.client = options.client;\n this.logger = options.logger ?? consoleLogger<RedisStoreLogFields>();\n this.client.on('message', this.onMessage);\n this.client.on('ready', this.onReady);\n this.client.on('error', this.onError);\n }\n\n subscribe(channel: string): Promise<unknown> {\n return this.client.subscribe(channel);\n }\n\n unsubscribe(channel: string): Promise<unknown> {\n return this.client.unsubscribe(channel);\n }\n\n on(event: 'message', listener: (channel: string, message: string) => void): this {\n if (event === 'message') this.messageListeners.add(listener);\n return this;\n }\n\n off(event: 'message', listener: (channel: string, message: string) => void): this {\n if (event === 'message') this.messageListeners.delete(listener);\n return this;\n }\n\n onReconnect(listener: () => void): () => void {\n this.reconnectListeners.add(listener);\n return () => this.reconnectListeners.delete(listener);\n }\n\n private onMessage = (channel: string, message: string): void => {\n for (const listener of this.messageListeners) listener(channel, message);\n };\n\n private onReady = (): void => {\n if (!this.ready) {\n this.ready = true;\n return;\n }\n for (const listener of this.reconnectListeners) listener();\n };\n\n private onError = (err: Error): void => {\n this.logger.warn('Redis subscriber connection error', { err });\n };\n}\n"]}
|
package/dist/redis.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { AcquireResult, LockState, LockStore, LockSubscription, ReleaseResult, StoreAcquireOptions, StoreReleaseOptions } from '@drlock/core';
|
|
2
|
+
import type { RedisStoreOptions } from './types.ts';
|
|
3
|
+
/**
|
|
4
|
+
* Redis store: atomic Lua acquire/release and Pub/Sub wakeup. Join is a worker
|
|
5
|
+
* set in the JSON; records expire by Redis TTL and are deleted on release.
|
|
6
|
+
* Multi-key calls pipeline when supported, else run sequentially.
|
|
7
|
+
*/
|
|
8
|
+
export declare class RedisStore implements LockStore {
|
|
9
|
+
private readonly client;
|
|
10
|
+
private readonly subscriber?;
|
|
11
|
+
private readonly keyPrefix;
|
|
12
|
+
private readonly channelPrefix;
|
|
13
|
+
private readonly listeners;
|
|
14
|
+
private readonly loadedScripts;
|
|
15
|
+
private readonly maxAttempts;
|
|
16
|
+
private readonly retryDelayMs;
|
|
17
|
+
private readonly logger;
|
|
18
|
+
private handlerAttached;
|
|
19
|
+
private reconnectUnsub;
|
|
20
|
+
constructor(options: RedisStoreOptions);
|
|
21
|
+
acquire(opts: StoreAcquireOptions): Promise<(AcquireResult | null)[]>;
|
|
22
|
+
release(opts: StoreReleaseOptions): Promise<ReleaseResult[]>;
|
|
23
|
+
getState(key: string): Promise<LockState | null>;
|
|
24
|
+
list(): Promise<string[]>;
|
|
25
|
+
subscribe(key: string, signal: AbortSignal): Promise<LockSubscription>;
|
|
26
|
+
close(): Promise<void>;
|
|
27
|
+
private messageHandler;
|
|
28
|
+
private reconnectHandler;
|
|
29
|
+
/** Lock keys use a dedicated segment. */
|
|
30
|
+
private lockPrefix;
|
|
31
|
+
private lockKey;
|
|
32
|
+
private channelFor;
|
|
33
|
+
/**
|
|
34
|
+
* Pipelines when possible, else runs sequentially. First call uses EVAL to
|
|
35
|
+
* populate the script cache; later calls use EVALSHA when the client supports
|
|
36
|
+
* it. NOSCRIPT retries only failed calls with EVAL.
|
|
37
|
+
*/
|
|
38
|
+
private evalBatch;
|
|
39
|
+
/** Fresh pipeline per attempt; retries transient failures (at-least-once). */
|
|
40
|
+
private runPipeline;
|
|
41
|
+
/** Retries only NOSCRIPT calls, preserving applied results. */
|
|
42
|
+
private retryNoScript;
|
|
43
|
+
private evalOne;
|
|
44
|
+
/** Retries only transient errors (not outcomes/NOSCRIPT). */
|
|
45
|
+
private withRetry;
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=redis.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"redis.d.ts","sourceRoot":"","sources":["../src/redis.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,aAAa,EAAE,SAAS,EAAE,SAAS,EAAE,gBAAgB,EAAU,aAAa,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAC3J,OAAO,KAAK,EAA0D,iBAAiB,EAAmB,MAAM,YAAY,CAAC;AAiJ7H;;;;GAIG;AACH,qBAAa,UAAW,YAAW,SAAS;IAE1C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAqB;IAC5C,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAkB;IAC9C,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAS;IACvC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAsC;IAChE,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAyB;IACvD,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAS;IACtC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAA8B;IACrD,OAAO,CAAC,eAAe,CAAS;IAChC,OAAO,CAAC,cAAc,CAA2B;IAEjD,YAAY,OAAO,EAAE,iBAAiB,EAQrC;IAEK,OAAO,CAAC,IAAI,EAAE,mBAAmB,GAAG,OAAO,CAAC,CAAC,aAAa,GAAG,IAAI,CAAC,EAAE,CAAC,CAe1E;IAEK,OAAO,CAAC,IAAI,EAAE,mBAAmB,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC,CAWjE;IAEK,QAAQ,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC,CASrD;IAEK,IAAI,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC,CAI9B;IAEK,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,gBAAgB,CAAC,CA6C3E;IAEK,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAQ3B;IAED,OAAO,CAAC,cAAc,CAIpB;IAEF,OAAO,CAAC,gBAAgB,CAGtB;IAEF,yCAAyC;IACzC,OAAO,CAAC,UAAU;IAIlB,OAAO,CAAC,OAAO;IAIf,OAAO,CAAC,UAAU;IAIlB;;;;OAIG;YACW,SAAS;IA2BvB,8EAA8E;YAChE,WAAW;IAYzB,+DAA+D;YACjD,aAAa;YAYb,OAAO;IAerB,6DAA6D;YAC/C,SAAS;CAexB"}
|
package/dist/redis.js
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { consoleLogger } from '@drlock/core';
|
|
3
|
+
import { LockSubscribeUnavailableError } from '@drlock/core';
|
|
4
|
+
const DEFAULT_MAX_ATTEMPTS = 3;
|
|
5
|
+
const DEFAULT_RETRY_DELAY_MS = 50;
|
|
6
|
+
// Lua scripts are atomic; `-- drlock:*` is a stable script tag.
|
|
7
|
+
// ACQUIRE keys [lockKey], args [contextId, workerId, ttlMs]. Returns 'busy' or
|
|
8
|
+
// ['ok', isNew, workersJson, pttlMs, ttlMs]. Re-adding a listed worker is
|
|
9
|
+
// idempotent; every write uses PX, and joins re-arm from PTTL.
|
|
10
|
+
const ACQUIRE = `-- drlock:acquire
|
|
11
|
+
local ttl = tonumber(ARGV[3])
|
|
12
|
+
local raw = redis.call('GET', KEYS[1])
|
|
13
|
+
local lock = raw and cjson.decode(raw) or nil
|
|
14
|
+
local pttl = lock and redis.call('PTTL', KEYS[1]) or nil
|
|
15
|
+
if not lock or pttl < 1 then
|
|
16
|
+
local workers = {ARGV[2]}
|
|
17
|
+
redis.call('SET', KEYS[1], cjson.encode({ctx = ARGV[1], ttl = ttl, workers = workers}), 'PX', ARGV[3])
|
|
18
|
+
return {'ok', 1, cjson.encode(workers), ttl, ttl}
|
|
19
|
+
end
|
|
20
|
+
if lock.ctx == ARGV[1] then
|
|
21
|
+
local workers = lock.workers or {}
|
|
22
|
+
local found = false
|
|
23
|
+
for _, w in ipairs(workers) do if w == ARGV[2] then found = true break end end
|
|
24
|
+
if not found then table.insert(workers, ARGV[2]) end
|
|
25
|
+
table.sort(workers)
|
|
26
|
+
lock.workers = workers
|
|
27
|
+
redis.call('SET', KEYS[1], cjson.encode(lock), 'PX', pttl)
|
|
28
|
+
return {'ok', 0, cjson.encode(workers), pttl, lock.ttl}
|
|
29
|
+
end
|
|
30
|
+
return {'busy'}`;
|
|
31
|
+
// RELEASE keys [lockKey], args [contextId, workerId, channel]. Deletes and
|
|
32
|
+
// publishes when the last worker leaves; otherwise 'notFound'/'notOwner'.
|
|
33
|
+
const RELEASE = `-- drlock:release
|
|
34
|
+
local pttl = redis.call('PTTL', KEYS[1])
|
|
35
|
+
local raw = redis.call('GET', KEYS[1])
|
|
36
|
+
if pttl < 1 or not raw then return {'notFound'} end
|
|
37
|
+
local lock = cjson.decode(raw)
|
|
38
|
+
if lock.ctx ~= ARGV[1] then return {'notOwner'} end
|
|
39
|
+
local workers = lock.workers or {}
|
|
40
|
+
local index
|
|
41
|
+
for i, w in ipairs(workers) do if w == ARGV[2] then index = i break end end
|
|
42
|
+
if not index then return {'notOwner'} end
|
|
43
|
+
table.remove(workers, index)
|
|
44
|
+
if #workers == 0 then
|
|
45
|
+
redis.call('PUBLISH', ARGV[3], 'released')
|
|
46
|
+
redis.call('DEL', KEYS[1])
|
|
47
|
+
return {'ok'}
|
|
48
|
+
end
|
|
49
|
+
lock.workers = workers
|
|
50
|
+
redis.call('SET', KEYS[1], cjson.encode(lock), 'PX', pttl)
|
|
51
|
+
return {'ok'}`;
|
|
52
|
+
// GET_STATE keys [lockKey]. Returns 'notFound' or
|
|
53
|
+
// ['ok', contextId, workersJson, pttlMs]; expiry is the key TTL.
|
|
54
|
+
const GET_STATE = `-- drlock:getState
|
|
55
|
+
local raw = redis.call('GET', KEYS[1])
|
|
56
|
+
if not raw then return {'notFound'} end
|
|
57
|
+
local lock = cjson.decode(raw)
|
|
58
|
+
local pttl = redis.call('PTTL', KEYS[1])
|
|
59
|
+
if pttl < 1 then return {'notFound'} end
|
|
60
|
+
return {'ok', lock.ctx, cjson.encode(lock.workers or {}), pttl}`;
|
|
61
|
+
// LIST args [lockPrefix]. Returns full keys under the prefix via SCAN (KEYS is
|
|
62
|
+
// unavailable on ElastiCache Serverless); exhausts the cursor inside Lua.
|
|
63
|
+
const LIST = `-- drlock:list
|
|
64
|
+
local cursor = '0'
|
|
65
|
+
local out = {}
|
|
66
|
+
repeat
|
|
67
|
+
local res = redis.call('SCAN', cursor, 'MATCH', ARGV[1] .. '*', 'COUNT', 100)
|
|
68
|
+
cursor = res[1]
|
|
69
|
+
for _, k in ipairs(res[2]) do table.insert(out, k) end
|
|
70
|
+
until cursor == '0'
|
|
71
|
+
return out`;
|
|
72
|
+
const SCRIPTS = {
|
|
73
|
+
acquire: { body: ACQUIRE, sha1: sha1(ACQUIRE) },
|
|
74
|
+
release: { body: RELEASE, sha1: sha1(RELEASE) },
|
|
75
|
+
getState: { body: GET_STATE, sha1: sha1(GET_STATE) },
|
|
76
|
+
list: { body: LIST, sha1: sha1(LIST) },
|
|
77
|
+
};
|
|
78
|
+
function sha1(script) {
|
|
79
|
+
return createHash('sha1').update(script).digest('hex');
|
|
80
|
+
}
|
|
81
|
+
function toEvalArray(result) {
|
|
82
|
+
if (!Array.isArray(result))
|
|
83
|
+
throw new Error('Redis EVAL must return a flat array');
|
|
84
|
+
return result;
|
|
85
|
+
}
|
|
86
|
+
function isNoScript(err) {
|
|
87
|
+
return err instanceof Error && /^NOSCRIPT/.test(err.message);
|
|
88
|
+
}
|
|
89
|
+
const TRANSIENT_CODES = new Set([
|
|
90
|
+
'ECONNRESET',
|
|
91
|
+
'ECONNREFUSED',
|
|
92
|
+
'ECONNABORTED',
|
|
93
|
+
'ETIMEDOUT',
|
|
94
|
+
'EPIPE',
|
|
95
|
+
'ENOTFOUND',
|
|
96
|
+
'EAI_AGAIN',
|
|
97
|
+
'EHOSTUNREACH',
|
|
98
|
+
'ENETUNREACH',
|
|
99
|
+
]);
|
|
100
|
+
/** Retryable: connection drops and Redis "try again" replies. */
|
|
101
|
+
function isTransientRedisError(err) {
|
|
102
|
+
if (!(err instanceof Error))
|
|
103
|
+
return false;
|
|
104
|
+
const code = err.code;
|
|
105
|
+
if (code && TRANSIENT_CODES.has(code))
|
|
106
|
+
return true;
|
|
107
|
+
return (/^\s*(LOADING|BUSY|TRYAGAIN|CLUSTERDOWN|MASTERDOWN|READONLY)\b/.test(err.message) ||
|
|
108
|
+
/Connection is closed|Connection is in closing state|Stream isn't writeable|MaxRetriesPerRequest/i.test(err.message));
|
|
109
|
+
}
|
|
110
|
+
// Retry is not abortable: an ambiguous apply could orphan a lock until TTL.
|
|
111
|
+
// Abort happens in LockManager after the store returns.
|
|
112
|
+
function sleep(ms) {
|
|
113
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
114
|
+
}
|
|
115
|
+
function parseWorkers(value) {
|
|
116
|
+
const parsed = JSON.parse(String(value));
|
|
117
|
+
if (!Array.isArray(parsed))
|
|
118
|
+
throw new Error('Redis EVAL returned malformed workers');
|
|
119
|
+
return parsed.map(String).sort();
|
|
120
|
+
}
|
|
121
|
+
function unwrapReplies(replies) {
|
|
122
|
+
return replies.map(([err, result]) => {
|
|
123
|
+
if (err)
|
|
124
|
+
throw err;
|
|
125
|
+
return toEvalArray(result);
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Redis store: atomic Lua acquire/release and Pub/Sub wakeup. Join is a worker
|
|
130
|
+
* set in the JSON; records expire by Redis TTL and are deleted on release.
|
|
131
|
+
* Multi-key calls pipeline when supported, else run sequentially.
|
|
132
|
+
*/
|
|
133
|
+
export class RedisStore {
|
|
134
|
+
client;
|
|
135
|
+
subscriber;
|
|
136
|
+
keyPrefix;
|
|
137
|
+
channelPrefix;
|
|
138
|
+
listeners = new Map();
|
|
139
|
+
loadedScripts = new Set();
|
|
140
|
+
maxAttempts;
|
|
141
|
+
retryDelayMs;
|
|
142
|
+
logger;
|
|
143
|
+
handlerAttached = false;
|
|
144
|
+
reconnectUnsub;
|
|
145
|
+
constructor(options) {
|
|
146
|
+
this.client = options.client;
|
|
147
|
+
this.subscriber = options.subscriber;
|
|
148
|
+
this.keyPrefix = options.keyPrefix ?? 'drlock:';
|
|
149
|
+
this.channelPrefix = options.channelPrefix ?? 'drlock:events:';
|
|
150
|
+
this.maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
|
|
151
|
+
this.retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;
|
|
152
|
+
this.logger = options.logger ?? consoleLogger();
|
|
153
|
+
}
|
|
154
|
+
async acquire(opts) {
|
|
155
|
+
const { keys, contextId, workerId, ttlMs } = opts;
|
|
156
|
+
if (keys.length === 0)
|
|
157
|
+
return [];
|
|
158
|
+
const now = Date.now();
|
|
159
|
+
const results = await this.evalBatch('acquire', keys.map((key) => ({
|
|
160
|
+
numKeys: 1,
|
|
161
|
+
keysAndArgs: [this.lockKey(key), contextId, workerId, ttlMs],
|
|
162
|
+
})));
|
|
163
|
+
return results.map((raw) => {
|
|
164
|
+
if (raw[0] !== 'ok')
|
|
165
|
+
return null;
|
|
166
|
+
return { isNew: Number(raw[1]) === 1, workers: parseWorkers(raw[2]), expiresAt: now + Number(raw[3]), ttlMs: Number(raw[4]) };
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
async release(opts) {
|
|
170
|
+
const { keys, contextId, workerId } = opts;
|
|
171
|
+
if (keys.length === 0)
|
|
172
|
+
return [];
|
|
173
|
+
const results = await this.evalBatch('release', keys.map((key) => ({
|
|
174
|
+
numKeys: 1,
|
|
175
|
+
keysAndArgs: [this.lockKey(key), contextId, workerId, this.channelFor(key)],
|
|
176
|
+
})));
|
|
177
|
+
return results.map((raw) => (raw[0] === 'ok' ? 'ok' : raw[0] === 'notOwner' ? 'notOwner' : 'notFound'));
|
|
178
|
+
}
|
|
179
|
+
async getState(key) {
|
|
180
|
+
const now = Date.now();
|
|
181
|
+
const raw = await this.evalOne('getState', 1, this.lockKey(key));
|
|
182
|
+
if (raw[0] !== 'ok')
|
|
183
|
+
return null;
|
|
184
|
+
return {
|
|
185
|
+
contextId: String(raw[1]),
|
|
186
|
+
workers: parseWorkers(raw[2]),
|
|
187
|
+
expiresAt: now + Number(raw[3]),
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
async list() {
|
|
191
|
+
const prefix = this.lockPrefix();
|
|
192
|
+
const raw = await this.evalOne('list', 0, prefix);
|
|
193
|
+
return raw.map((k) => String(k).slice(prefix.length));
|
|
194
|
+
}
|
|
195
|
+
async subscribe(key, signal) {
|
|
196
|
+
if (!this.subscriber) {
|
|
197
|
+
throw new LockSubscribeUnavailableError('RedisStore.subscribe() is unavailable: no subscriber is configured');
|
|
198
|
+
}
|
|
199
|
+
const channel = this.channelFor(key);
|
|
200
|
+
const isNew = !this.listeners.has(channel);
|
|
201
|
+
let set = this.listeners.get(channel);
|
|
202
|
+
if (!set) {
|
|
203
|
+
set = new Set();
|
|
204
|
+
this.listeners.set(channel, set);
|
|
205
|
+
if (!this.handlerAttached) {
|
|
206
|
+
this.subscriber.on('message', this.messageHandler);
|
|
207
|
+
this.handlerAttached = true;
|
|
208
|
+
this.reconnectUnsub = this.subscriber.onReconnect?.(this.reconnectHandler);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
const awakePromise = new Promise((resolve) => {
|
|
212
|
+
const onReleased = () => { cleanup(); resolve(); };
|
|
213
|
+
const onAbort = () => { cleanup(); resolve(); };
|
|
214
|
+
const cleanup = () => {
|
|
215
|
+
set.delete(onReleased);
|
|
216
|
+
if (set.size === 0) {
|
|
217
|
+
this.listeners.delete(channel);
|
|
218
|
+
this.subscriber.unsubscribe(channel).catch((err) => this.logger.error(`unsubscribe failed for channel "${channel}"`, { channel, err }));
|
|
219
|
+
if (this.listeners.size === 0 && this.handlerAttached) {
|
|
220
|
+
this.subscriber.off('message', this.messageHandler);
|
|
221
|
+
this.handlerAttached = false;
|
|
222
|
+
this.reconnectUnsub?.();
|
|
223
|
+
this.reconnectUnsub = undefined;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
signal.removeEventListener('abort', onAbort);
|
|
227
|
+
};
|
|
228
|
+
set.add(onReleased);
|
|
229
|
+
if (signal.aborted)
|
|
230
|
+
onAbort();
|
|
231
|
+
else
|
|
232
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
233
|
+
});
|
|
234
|
+
// Register the resolver before SUBSCRIBE so a racing event is not lost.
|
|
235
|
+
if (isNew)
|
|
236
|
+
await this.withRetry(() => this.subscriber.subscribe(channel));
|
|
237
|
+
return { awakePromise };
|
|
238
|
+
}
|
|
239
|
+
async close() {
|
|
240
|
+
this.listeners.clear();
|
|
241
|
+
if (this.subscriber && this.handlerAttached) {
|
|
242
|
+
this.subscriber.off('message', this.messageHandler);
|
|
243
|
+
this.handlerAttached = false;
|
|
244
|
+
this.reconnectUnsub?.();
|
|
245
|
+
this.reconnectUnsub = undefined;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
messageHandler = (channel, message) => {
|
|
249
|
+
if (message !== 'released')
|
|
250
|
+
return;
|
|
251
|
+
const set = this.listeners.get(channel);
|
|
252
|
+
if (set)
|
|
253
|
+
for (const cb of set)
|
|
254
|
+
cb();
|
|
255
|
+
};
|
|
256
|
+
reconnectHandler = () => {
|
|
257
|
+
// SUBSCRIBE was lost: wake waiters to re-check; re-subscribe lazily.
|
|
258
|
+
for (const set of this.listeners.values())
|
|
259
|
+
for (const cb of set)
|
|
260
|
+
cb();
|
|
261
|
+
};
|
|
262
|
+
/** Lock keys use a dedicated segment. */
|
|
263
|
+
lockPrefix() {
|
|
264
|
+
return `${this.keyPrefix}locks:`;
|
|
265
|
+
}
|
|
266
|
+
lockKey(key) {
|
|
267
|
+
return this.lockPrefix() + key;
|
|
268
|
+
}
|
|
269
|
+
channelFor(key) {
|
|
270
|
+
return this.channelPrefix + key;
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Pipelines when possible, else runs sequentially. First call uses EVAL to
|
|
274
|
+
* populate the script cache; later calls use EVALSHA when the client supports
|
|
275
|
+
* it. NOSCRIPT retries only failed calls with EVAL.
|
|
276
|
+
*/
|
|
277
|
+
async evalBatch(kind, calls) {
|
|
278
|
+
if (calls.length === 0)
|
|
279
|
+
return [];
|
|
280
|
+
const def = SCRIPTS[kind];
|
|
281
|
+
if (!this.client.pipeline) {
|
|
282
|
+
const results = [];
|
|
283
|
+
for (const call of calls)
|
|
284
|
+
results.push(await this.evalOne(kind, call.numKeys, ...call.keysAndArgs));
|
|
285
|
+
return results;
|
|
286
|
+
}
|
|
287
|
+
if (this.client.evalsha && this.loadedScripts.has(kind)) {
|
|
288
|
+
const replies = await this.runPipeline((pipeline) => {
|
|
289
|
+
if (!pipeline.evalsha)
|
|
290
|
+
throw new Error('Redis pipeline does not support EVALSHA');
|
|
291
|
+
for (const call of calls)
|
|
292
|
+
pipeline.evalsha(def.sha1, call.numKeys, ...call.keysAndArgs);
|
|
293
|
+
});
|
|
294
|
+
if (!replies.some(([err]) => isNoScript(err)))
|
|
295
|
+
return unwrapReplies(replies);
|
|
296
|
+
this.loadedScripts.delete(kind);
|
|
297
|
+
if (!replies.every(([err]) => isNoScript(err)))
|
|
298
|
+
return this.retryNoScript(kind, calls, replies);
|
|
299
|
+
// Whole batch missed: replay with EVAL below.
|
|
300
|
+
}
|
|
301
|
+
const replies = await this.runPipeline((pipeline) => {
|
|
302
|
+
for (const call of calls)
|
|
303
|
+
pipeline.eval(def.body, call.numKeys, ...call.keysAndArgs);
|
|
304
|
+
});
|
|
305
|
+
this.loadedScripts.add(kind);
|
|
306
|
+
return unwrapReplies(replies);
|
|
307
|
+
}
|
|
308
|
+
/** Fresh pipeline per attempt; retries transient failures (at-least-once). */
|
|
309
|
+
async runPipeline(build) {
|
|
310
|
+
const create = this.client.pipeline;
|
|
311
|
+
if (!create)
|
|
312
|
+
throw new Error('Redis client has no pipeline');
|
|
313
|
+
return this.withRetry(async () => {
|
|
314
|
+
const pipeline = create.call(this.client);
|
|
315
|
+
build(pipeline);
|
|
316
|
+
const replies = await pipeline.exec();
|
|
317
|
+
if (!replies)
|
|
318
|
+
throw new Error('Redis pipeline returned no replies');
|
|
319
|
+
return replies;
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
/** Retries only NOSCRIPT calls, preserving applied results. */
|
|
323
|
+
async retryNoScript(kind, calls, replies) {
|
|
324
|
+
const results = [];
|
|
325
|
+
for (let i = 0; i < calls.length; i++) {
|
|
326
|
+
const [err, result] = replies[i];
|
|
327
|
+
const call = calls[i];
|
|
328
|
+
if (isNoScript(err))
|
|
329
|
+
results.push(await this.evalOne(kind, call.numKeys, ...call.keysAndArgs));
|
|
330
|
+
else if (err)
|
|
331
|
+
throw err;
|
|
332
|
+
else
|
|
333
|
+
results.push(toEvalArray(result));
|
|
334
|
+
}
|
|
335
|
+
return results;
|
|
336
|
+
}
|
|
337
|
+
async evalOne(kind, numKeys, ...keysAndArgs) {
|
|
338
|
+
const def = SCRIPTS[kind];
|
|
339
|
+
if (this.client.evalsha && this.loadedScripts.has(kind)) {
|
|
340
|
+
try {
|
|
341
|
+
return toEvalArray(await this.withRetry(() => this.client.evalsha(def.sha1, numKeys, ...keysAndArgs)));
|
|
342
|
+
}
|
|
343
|
+
catch (err) {
|
|
344
|
+
if (!isNoScript(err))
|
|
345
|
+
throw err;
|
|
346
|
+
this.loadedScripts.delete(kind);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
const result = toEvalArray(await this.withRetry(() => this.client.eval(def.body, numKeys, ...keysAndArgs)));
|
|
350
|
+
this.loadedScripts.add(kind);
|
|
351
|
+
return result;
|
|
352
|
+
}
|
|
353
|
+
/** Retries only transient errors (not outcomes/NOSCRIPT). */
|
|
354
|
+
async withRetry(fn) {
|
|
355
|
+
for (let attempt = 1;; attempt++) {
|
|
356
|
+
try {
|
|
357
|
+
return await fn();
|
|
358
|
+
}
|
|
359
|
+
catch (err) {
|
|
360
|
+
if (attempt >= this.maxAttempts || !isTransientRedisError(err))
|
|
361
|
+
throw err;
|
|
362
|
+
// At-least-once: a partially applied call may run again.
|
|
363
|
+
this.logger.warn(`retrying Redis operation after transient error (attempt ${attempt}/${this.maxAttempts}); at-least-once: a partially executed command/pipeline may be applied again`, { err });
|
|
364
|
+
await sleep(this.retryDelayMs * 2 ** (attempt - 1));
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
//# sourceMappingURL=redis.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"redis.js","sourceRoot":"","sources":["../src/redis.ts"],"names":[],"mappings":"AAA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C7C,KAAK,IAAI,OAAO,GAAG,CAAC,GAAI,OAAO,EAAE,EAAE,CAAC;YAClC,IAAI,CAAC;gBACH,OAAO,MAAM,EAAE,EAAE,CAAC;YACpB,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,IAAI,OAAO,IAAI,IAAI,CAAC,WAAW,IAAI,CAAC,qBAAqB,CAAC,GAAG,CAAC;oBAAE,MAAM,GAAG,CAAC;gBAC1E,yDAAyD;gBACzD,IAAI,CAAC,MAAM,CAAC,IAAI,CACd,2DAA2D,OAAO,IAAI,IAAI,CAAC,WAAW,8EAA8E,EACpK,EAAE,GAAG,EAAE,CACR,CAAC;gBACF,MAAM,KAAK,CAAC,IAAI,CAAC,YAAY,GAAG,CAAC,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC,CAAC;YACtD,CAAC;QACH,CAAC;IACH,CAAC;CACF","sourcesContent":["import { createHash } from 'node:crypto';\nimport { consoleLogger } from '@drlock/core';\nimport { LockSubscribeUnavailableError } from '@drlock/core';\nimport type { AcquireResult, LockState, LockStore, LockSubscription, Logger, ReleaseResult, StoreAcquireOptions, StoreReleaseOptions } from '@drlock/core';\nimport type { RedisCommandClient, RedisPipeline, RedisStoreLogFields, RedisStoreOptions, RedisSubscriber } from './types.ts';\n\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_RETRY_DELAY_MS = 50;\n\n// Lua scripts are atomic; `-- drlock:*` is a stable script tag.\n// ACQUIRE keys [lockKey], args [contextId, workerId, ttlMs]. Returns 'busy' or\n// ['ok', isNew, workersJson, pttlMs, ttlMs]. Re-adding a listed worker is\n// idempotent; every write uses PX, and joins re-arm from PTTL.\nconst ACQUIRE = `-- drlock:acquire\nlocal ttl = tonumber(ARGV[3])\nlocal raw = redis.call('GET', KEYS[1])\nlocal lock = raw and cjson.decode(raw) or nil\nlocal pttl = lock and redis.call('PTTL', KEYS[1]) or nil\nif not lock or pttl < 1 then\n local workers = {ARGV[2]}\n redis.call('SET', KEYS[1], cjson.encode({ctx = ARGV[1], ttl = ttl, workers = workers}), 'PX', ARGV[3])\n return {'ok', 1, cjson.encode(workers), ttl, ttl}\nend\nif lock.ctx == ARGV[1] then\n local workers = lock.workers or {}\n local found = false\n for _, w in ipairs(workers) do if w == ARGV[2] then found = true break end end\n if not found then table.insert(workers, ARGV[2]) end\n table.sort(workers)\n lock.workers = workers\n redis.call('SET', KEYS[1], cjson.encode(lock), 'PX', pttl)\n return {'ok', 0, cjson.encode(workers), pttl, lock.ttl}\nend\nreturn {'busy'}`;\n\n// RELEASE keys [lockKey], args [contextId, workerId, channel]. Deletes and\n// publishes when the last worker leaves; otherwise 'notFound'/'notOwner'.\nconst RELEASE = `-- drlock:release\nlocal pttl = redis.call('PTTL', KEYS[1])\nlocal raw = redis.call('GET', KEYS[1])\nif pttl < 1 or not raw then return {'notFound'} end\nlocal lock = cjson.decode(raw)\nif lock.ctx ~= ARGV[1] then return {'notOwner'} end\nlocal workers = lock.workers or {}\nlocal index\nfor i, w in ipairs(workers) do if w == ARGV[2] then index = i break end end\nif not index then return {'notOwner'} end\ntable.remove(workers, index)\nif #workers == 0 then\n redis.call('PUBLISH', ARGV[3], 'released')\n redis.call('DEL', KEYS[1])\n return {'ok'}\nend\nlock.workers = workers\nredis.call('SET', KEYS[1], cjson.encode(lock), 'PX', pttl)\nreturn {'ok'}`;\n\n// GET_STATE keys [lockKey]. Returns 'notFound' or\n// ['ok', contextId, workersJson, pttlMs]; expiry is the key TTL.\nconst GET_STATE = `-- drlock:getState\nlocal raw = redis.call('GET', KEYS[1])\nif not raw then return {'notFound'} end\nlocal lock = cjson.decode(raw)\nlocal pttl = redis.call('PTTL', KEYS[1])\nif pttl < 1 then return {'notFound'} end\nreturn {'ok', lock.ctx, cjson.encode(lock.workers or {}), pttl}`;\n\n// LIST args [lockPrefix]. Returns full keys under the prefix via SCAN (KEYS is\n// unavailable on ElastiCache Serverless); exhausts the cursor inside Lua.\nconst LIST = `-- drlock:list\nlocal cursor = '0'\nlocal out = {}\nrepeat\n local res = redis.call('SCAN', cursor, 'MATCH', ARGV[1] .. '*', 'COUNT', 100)\n cursor = res[1]\n for _, k in ipairs(res[2]) do table.insert(out, k) end\nuntil cursor == '0'\nreturn out`;\ntype ScriptKind = 'acquire' | 'release' | 'getState' | 'list';\n\nconst SCRIPTS: Record<ScriptKind, { body: string; sha1: string }> = {\n acquire: { body: ACQUIRE, sha1: sha1(ACQUIRE) },\n release: { body: RELEASE, sha1: sha1(RELEASE) },\n getState: { body: GET_STATE, sha1: sha1(GET_STATE) },\n list: { body: LIST, sha1: sha1(LIST) },\n};\n\ntype EvalArray = (string | number)[];\n\ninterface EvalCall {\n numKeys: number;\n keysAndArgs: (string | number)[];\n}\n\nfunction sha1(script: string): string {\n return createHash('sha1').update(script).digest('hex');\n}\n\nfunction toEvalArray(result: unknown): EvalArray {\n if (!Array.isArray(result)) throw new Error('Redis EVAL must return a flat array');\n return result as EvalArray;\n}\n\nfunction isNoScript(err: unknown): boolean {\n return err instanceof Error && /^NOSCRIPT/.test(err.message);\n}\n\nconst TRANSIENT_CODES = new Set([\n 'ECONNRESET',\n 'ECONNREFUSED',\n 'ECONNABORTED',\n 'ETIMEDOUT',\n 'EPIPE',\n 'ENOTFOUND',\n 'EAI_AGAIN',\n 'EHOSTUNREACH',\n 'ENETUNREACH',\n]);\n\n/** Retryable: connection drops and Redis \"try again\" replies. */\nfunction isTransientRedisError(err: unknown): boolean {\n if (!(err instanceof Error)) return false;\n const code = (err as { code?: string }).code;\n if (code && TRANSIENT_CODES.has(code)) return true;\n return (\n /^\\s*(LOADING|BUSY|TRYAGAIN|CLUSTERDOWN|MASTERDOWN|READONLY)\\b/.test(err.message) ||\n /Connection is closed|Connection is in closing state|Stream isn't writeable|MaxRetriesPerRequest/i.test(err.message)\n );\n}\n\n// Retry is not abortable: an ambiguous apply could orphan a lock until TTL.\n// Abort happens in LockManager after the store returns.\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction parseWorkers(value: unknown): string[] {\n const parsed = JSON.parse(String(value)) as unknown;\n if (!Array.isArray(parsed)) throw new Error('Redis EVAL returned malformed workers');\n return parsed.map(String).sort();\n}\n\nfunction unwrapReplies(replies: Array<[Error | null, unknown]>): EvalArray[] {\n return replies.map(([err, result]) => {\n if (err) throw err;\n return toEvalArray(result);\n });\n}\n\n/**\n * Redis store: atomic Lua acquire/release and Pub/Sub wakeup. Join is a worker\n * set in the JSON; records expire by Redis TTL and are deleted on release.\n * Multi-key calls pipeline when supported, else run sequentially.\n */\nexport class RedisStore implements LockStore {\n\n private readonly client: RedisCommandClient;\n private readonly subscriber?: RedisSubscriber;\n private readonly keyPrefix: string;\n private readonly channelPrefix: string;\n private readonly listeners = new Map<string, Set<() => void>>();\n private readonly loadedScripts = new Set<ScriptKind>();\n private readonly maxAttempts: number;\n private readonly retryDelayMs: number;\n private readonly logger: Logger<RedisStoreLogFields>;\n private handlerAttached = false;\n private reconnectUnsub: (() => void) | undefined;\n\n constructor(options: RedisStoreOptions) {\n this.client = options.client;\n this.subscriber = options.subscriber;\n this.keyPrefix = options.keyPrefix ?? 'drlock:';\n this.channelPrefix = options.channelPrefix ?? 'drlock:events:';\n this.maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n this.retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;\n this.logger = options.logger ?? consoleLogger<RedisStoreLogFields>();\n }\n\n async acquire(opts: StoreAcquireOptions): Promise<(AcquireResult | null)[]> {\n const { keys, contextId, workerId, ttlMs } = opts;\n if (keys.length === 0) return [];\n const now = Date.now();\n const results = await this.evalBatch(\n 'acquire',\n keys.map((key) => ({\n numKeys: 1,\n keysAndArgs: [this.lockKey(key), contextId, workerId, ttlMs],\n })),\n );\n return results.map((raw): AcquireResult | null => {\n if (raw[0] !== 'ok') return null;\n return { isNew: Number(raw[1]) === 1, workers: parseWorkers(raw[2]), expiresAt: now + Number(raw[3]), ttlMs: Number(raw[4]) };\n });\n }\n\n async release(opts: StoreReleaseOptions): Promise<ReleaseResult[]> {\n const { keys, contextId, workerId } = opts;\n if (keys.length === 0) return [];\n const results = await this.evalBatch(\n 'release',\n keys.map((key) => ({\n numKeys: 1,\n keysAndArgs: [this.lockKey(key), contextId, workerId, this.channelFor(key)],\n })),\n );\n return results.map((raw): ReleaseResult => (raw[0] === 'ok' ? 'ok' : raw[0] === 'notOwner' ? 'notOwner' : 'notFound'));\n }\n\n async getState(key: string): Promise<LockState | null> {\n const now = Date.now();\n const raw = await this.evalOne('getState', 1, this.lockKey(key));\n if (raw[0] !== 'ok') return null;\n return {\n contextId: String(raw[1]),\n workers: parseWorkers(raw[2]),\n expiresAt: now + Number(raw[3]),\n };\n }\n\n async list(): Promise<string[]> {\n const prefix = this.lockPrefix();\n const raw = await this.evalOne('list', 0, prefix);\n return raw.map((k) => String(k).slice(prefix.length));\n }\n\n async subscribe(key: string, signal: AbortSignal): Promise<LockSubscription> {\n if (!this.subscriber) {\n throw new LockSubscribeUnavailableError('RedisStore.subscribe() is unavailable: no subscriber is configured');\n }\n\n const channel = this.channelFor(key);\n const isNew = !this.listeners.has(channel);\n\n let set = this.listeners.get(channel);\n if (!set) {\n set = new Set();\n this.listeners.set(channel, set);\n if (!this.handlerAttached) {\n this.subscriber.on('message', this.messageHandler);\n this.handlerAttached = true;\n this.reconnectUnsub = this.subscriber.onReconnect?.(this.reconnectHandler);\n }\n }\n\n const awakePromise = new Promise<void>((resolve) => {\n const onReleased = () => { cleanup(); resolve(); };\n const onAbort = () => { cleanup(); resolve(); };\n const cleanup = () => {\n set.delete(onReleased);\n if (set.size === 0) {\n this.listeners.delete(channel);\n this.subscriber!.unsubscribe(channel).catch((err) => this.logger.error(`unsubscribe failed for channel \"${channel}\"`, { channel, err }));\n if (this.listeners.size === 0 && this.handlerAttached) {\n this.subscriber!.off('message', this.messageHandler);\n this.handlerAttached = false;\n this.reconnectUnsub?.();\n this.reconnectUnsub = undefined;\n }\n }\n signal.removeEventListener('abort', onAbort);\n };\n set.add(onReleased);\n if (signal.aborted) onAbort();\n else signal.addEventListener('abort', onAbort, { once: true });\n });\n\n // Register the resolver before SUBSCRIBE so a racing event is not lost.\n if (isNew) await this.withRetry(() => this.subscriber!.subscribe(channel));\n\n return { awakePromise };\n }\n\n async close(): Promise<void> {\n this.listeners.clear();\n if (this.subscriber && this.handlerAttached) {\n this.subscriber.off('message', this.messageHandler);\n this.handlerAttached = false;\n this.reconnectUnsub?.();\n this.reconnectUnsub = undefined;\n }\n }\n\n private messageHandler = (channel: string, message: string): void => {\n if (message !== 'released') return;\n const set = this.listeners.get(channel);\n if (set) for (const cb of set) cb();\n };\n\n private reconnectHandler = (): void => {\n // SUBSCRIBE was lost: wake waiters to re-check; re-subscribe lazily.\n for (const set of this.listeners.values()) for (const cb of set) cb();\n };\n\n /** Lock keys use a dedicated segment. */\n private lockPrefix(): string {\n return `${this.keyPrefix}locks:`;\n }\n\n private lockKey(key: string): string {\n return this.lockPrefix() + key;\n }\n\n private channelFor(key: string): string {\n return this.channelPrefix + key;\n }\n\n /**\n * Pipelines when possible, else runs sequentially. First call uses EVAL to\n * populate the script cache; later calls use EVALSHA when the client supports\n * it. NOSCRIPT retries only failed calls with EVAL.\n */\n private async evalBatch(kind: ScriptKind, calls: EvalCall[]): Promise<EvalArray[]> {\n if (calls.length === 0) return [];\n const def = SCRIPTS[kind];\n if (!this.client.pipeline) {\n const results: EvalArray[] = [];\n for (const call of calls) results.push(await this.evalOne(kind, call.numKeys, ...call.keysAndArgs));\n return results;\n }\n\n if (this.client.evalsha && this.loadedScripts.has(kind)) {\n const replies = await this.runPipeline((pipeline) => {\n if (!pipeline.evalsha) throw new Error('Redis pipeline does not support EVALSHA');\n for (const call of calls) pipeline.evalsha(def.sha1, call.numKeys, ...call.keysAndArgs);\n });\n if (!replies.some(([err]) => isNoScript(err))) return unwrapReplies(replies);\n this.loadedScripts.delete(kind);\n if (!replies.every(([err]) => isNoScript(err))) return this.retryNoScript(kind, calls, replies);\n // Whole batch missed: replay with EVAL below.\n }\n\n const replies = await this.runPipeline((pipeline) => {\n for (const call of calls) pipeline.eval(def.body, call.numKeys, ...call.keysAndArgs);\n });\n this.loadedScripts.add(kind);\n return unwrapReplies(replies);\n }\n\n /** Fresh pipeline per attempt; retries transient failures (at-least-once). */\n private async runPipeline(build: (pipeline: RedisPipeline) => void): Promise<Array<[Error | null, unknown]>> {\n const create = this.client.pipeline;\n if (!create) throw new Error('Redis client has no pipeline');\n return this.withRetry(async () => {\n const pipeline = create.call(this.client);\n build(pipeline);\n const replies = await pipeline.exec();\n if (!replies) throw new Error('Redis pipeline returned no replies');\n return replies;\n });\n }\n\n /** Retries only NOSCRIPT calls, preserving applied results. */\n private async retryNoScript(kind: ScriptKind, calls: EvalCall[], replies: Array<[Error | null, unknown]>): Promise<EvalArray[]> {\n const results: EvalArray[] = [];\n for (let i = 0; i < calls.length; i++) {\n const [err, result] = replies[i]!;\n const call = calls[i]!;\n if (isNoScript(err)) results.push(await this.evalOne(kind, call.numKeys, ...call.keysAndArgs));\n else if (err) throw err;\n else results.push(toEvalArray(result));\n }\n return results;\n }\n\n private async evalOne(kind: ScriptKind, numKeys: number, ...keysAndArgs: (string | number)[]): Promise<EvalArray> {\n const def = SCRIPTS[kind];\n if (this.client.evalsha && this.loadedScripts.has(kind)) {\n try {\n return toEvalArray(await this.withRetry(() => this.client.evalsha!(def.sha1, numKeys, ...keysAndArgs)));\n } catch (err) {\n if (!isNoScript(err)) throw err;\n this.loadedScripts.delete(kind);\n }\n }\n const result = toEvalArray(await this.withRetry(() => this.client.eval(def.body, numKeys, ...keysAndArgs)));\n this.loadedScripts.add(kind);\n return result;\n }\n\n /** Retries only transient errors (not outcomes/NOSCRIPT). */\n private async withRetry<T>(fn: () => Promise<T>): Promise<T> {\n for (let attempt = 1; ; attempt++) {\n try {\n return await fn();\n } catch (err) {\n if (attempt >= this.maxAttempts || !isTransientRedisError(err)) throw err;\n // At-least-once: a partially applied call may run again.\n this.logger.warn(\n `retrying Redis operation after transient error (attempt ${attempt}/${this.maxAttempts}); at-least-once: a partially executed command/pipeline may be applied again`,\n { err },\n );\n await sleep(this.retryDelayMs * 2 ** (attempt - 1));\n }\n }\n }\n}\n\n\n\n"]}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { Logger } from '@drlock/core';
|
|
2
|
+
/** `RedisStore` log fields. */
|
|
3
|
+
export interface RedisStoreLogFields {
|
|
4
|
+
channel?: string;
|
|
5
|
+
err?: unknown;
|
|
6
|
+
}
|
|
7
|
+
/** ioredis-compatible pipeline: queue evals, then `exec()` in one round-trip. */
|
|
8
|
+
export interface RedisPipeline {
|
|
9
|
+
eval(script: string, numKeys: number, ...keysAndArgs: (string | number)[]): RedisPipeline;
|
|
10
|
+
/** Optional cached-script call by SHA1. */
|
|
11
|
+
evalsha?(sha1: string, numKeys: number, ...keysAndArgs: (string | number)[]): RedisPipeline;
|
|
12
|
+
exec(): Promise<Array<[Error | null, unknown]> | null>;
|
|
13
|
+
}
|
|
14
|
+
/** Minimal Redis command surface, matching ioredis `eval(script, numKeys, ...)`; adapt other drivers. */
|
|
15
|
+
export interface RedisCommandClient {
|
|
16
|
+
eval(script: string, numKeys: number, ...keysAndArgs: (string | number)[]): Promise<unknown>;
|
|
17
|
+
/** Optional cached-script call by SHA1. */
|
|
18
|
+
evalsha?(sha1: string, numKeys: number, ...keysAndArgs: (string | number)[]): Promise<unknown>;
|
|
19
|
+
/** Optional batching; without it, multi-key calls run sequentially. */
|
|
20
|
+
pipeline?(): RedisPipeline;
|
|
21
|
+
}
|
|
22
|
+
/** Raw ioredis-style SUBSCRIBE surface used by the reconnect adapter. */
|
|
23
|
+
export interface RedisSubscriberClient {
|
|
24
|
+
subscribe(channel: string): Promise<unknown>;
|
|
25
|
+
unsubscribe(channel: string): Promise<unknown>;
|
|
26
|
+
on(event: 'message', listener: (channel: string, message: string) => void): unknown;
|
|
27
|
+
off(event: 'message', listener: (channel: string, message: string) => void): unknown;
|
|
28
|
+
on(event: 'ready', listener: () => void): unknown;
|
|
29
|
+
off(event: 'ready', listener: () => void): unknown;
|
|
30
|
+
on(event: 'error', listener: (err: Error) => void): unknown;
|
|
31
|
+
off(event: 'error', listener: (err: Error) => void): unknown;
|
|
32
|
+
}
|
|
33
|
+
/** Minimal SUBSCRIBE connection (ioredis-compatible). */
|
|
34
|
+
export interface RedisSubscriber {
|
|
35
|
+
subscribe(channel: string): Promise<unknown>;
|
|
36
|
+
unsubscribe(channel: string): Promise<unknown>;
|
|
37
|
+
on(event: 'message', listener: (channel: string, message: string) => void): unknown;
|
|
38
|
+
off(event: 'message', listener: (channel: string, message: string) => void): unknown;
|
|
39
|
+
/** On reconnect, resolve active subscriptions; returns unsubscribe. */
|
|
40
|
+
onReconnect?(listener: () => void): () => void;
|
|
41
|
+
}
|
|
42
|
+
export interface ReconnectingRedisSubscriberOptions {
|
|
43
|
+
/** Raw ioredis-compatible client; ioredis owns reconnect/resubscribe. */
|
|
44
|
+
client: RedisSubscriberClient;
|
|
45
|
+
/** Subscriber error logger. */
|
|
46
|
+
logger?: Logger<RedisStoreLogFields>;
|
|
47
|
+
}
|
|
48
|
+
export interface RedisStoreOptions {
|
|
49
|
+
client: RedisCommandClient;
|
|
50
|
+
/** Dedicated SUBSCRIBE connection; omit for polling-only. */
|
|
51
|
+
subscriber?: RedisSubscriber;
|
|
52
|
+
/** Lock namespace: `<keyPrefix>locks:<key>`; default `drlock:`. */
|
|
53
|
+
keyPrefix?: string;
|
|
54
|
+
/** Pub/Sub channel prefix; default `drlock:events:`. */
|
|
55
|
+
channelPrefix?: string;
|
|
56
|
+
/** Background-error logger. */
|
|
57
|
+
logger?: Logger<RedisStoreLogFields>;
|
|
58
|
+
/** Attempts on transient errors; default 3. Retries are at-least-once. */
|
|
59
|
+
maxAttempts?: number;
|
|
60
|
+
/** Base retry delay in ms (doubles); default 50. */
|
|
61
|
+
retryDelayMs?: number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AAM,EAAE,OAAO,EAAE,MAAM,KAAK,IAAI,GAAG,OAAO,CAAC;IACrF,uEAAuE;IACvE,WAAW,CAAC,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC;CAChD;AAED,MAAM,WAAW,kCAAkC;IACjD,yEAAyE;IACzE,MAAM,EAAE,qBAAqB,CAAC;IAC9B,+BAA+B;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC,mBAAmB,CAAC,CAAC;CACtC;AAED,MAAM,WAAW,iBAAiB;IAChC,MAAM,EAAE,kBAAkB,CAAC;IAC3B,6DAA6D;IAC7D,UAAU,CAAC,EAAE,eAAe,CAAC;IAC7B,mEAAmE;IACnE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,wDAAwD;IACxD,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,+BAA+B;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC,mBAAmB,CAAC,CAAC;IACrC,0EAA0E;IAC1E,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,oDAAoD;IACpD,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB"}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Logger } from '@drlock/core';\n\n/** `RedisStore` log fields. */\nexport interface RedisStoreLogFields {\n channel?: string;\n err?: unknown;\n}\n\n/** ioredis-compatible pipeline: queue evals, then `exec()` in one round-trip. */\nexport interface RedisPipeline {\n eval(script: string, numKeys: number, ...keysAndArgs: (string | number)[]): RedisPipeline;\n /** Optional cached-script call by SHA1. */\n evalsha?(sha1: string, numKeys: number, ...keysAndArgs: (string | number)[]): RedisPipeline;\n exec(): Promise<Array<[Error | null, unknown]> | null>;\n}\n\n/** Minimal Redis command surface, matching ioredis `eval(script, numKeys, ...)`; adapt other drivers. */\nexport interface RedisCommandClient {\n eval(script: string, numKeys: number, ...keysAndArgs: (string | number)[]): Promise<unknown>;\n /** Optional cached-script call by SHA1. */\n evalsha?(sha1: string, numKeys: number, ...keysAndArgs: (string | number)[]): Promise<unknown>;\n /** Optional batching; without it, multi-key calls run sequentially. */\n pipeline?(): RedisPipeline;\n}\n\n/** Raw ioredis-style SUBSCRIBE surface used by the reconnect adapter. */\nexport interface RedisSubscriberClient {\n subscribe(channel: string): Promise<unknown>;\n unsubscribe(channel: string): Promise<unknown>;\n on(event: 'message', listener: (channel: string, message: string) => void): unknown;\n off(event: 'message', listener: (channel: string, message: string) => void): unknown;\n on(event: 'ready', listener: () => void): unknown;\n off(event: 'ready', listener: () => void): unknown;\n on(event: 'error', listener: (err: Error) => void): unknown;\n off(event: 'error', listener: (err: Error) => void): unknown;\n}\n\n/** Minimal SUBSCRIBE connection (ioredis-compatible). */\nexport interface RedisSubscriber {\n subscribe(channel: string): Promise<unknown>;\n unsubscribe(channel: string): Promise<unknown>;\n on(event: 'message', listener: (channel: string, message: string) => void): unknown;\n off(event: 'message', listener: (channel: string, message: string) => void): unknown;\n /** On reconnect, resolve active subscriptions; returns unsubscribe. */\n onReconnect?(listener: () => void): () => void;\n}\n\nexport interface ReconnectingRedisSubscriberOptions {\n /** Raw ioredis-compatible client; ioredis owns reconnect/resubscribe. */\n client: RedisSubscriberClient;\n /** Subscriber error logger. */\n logger?: Logger<RedisStoreLogFields>;\n}\n\nexport interface RedisStoreOptions {\n client: RedisCommandClient;\n /** Dedicated SUBSCRIBE connection; omit for polling-only. */\n subscriber?: RedisSubscriber;\n /** Lock namespace: `<keyPrefix>locks:<key>`; default `drlock:`. */\n keyPrefix?: string;\n /** Pub/Sub channel prefix; default `drlock:events:`. */\n channelPrefix?: string;\n /** Background-error logger. */\n logger?: Logger<RedisStoreLogFields>;\n /** Attempts on transient errors; default 3. Retries are at-least-once. */\n maxAttempts?: number;\n /** Base retry delay in ms (doubles); default 50. */\n retryDelayMs?: number;\n}\n\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,56 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@drlock/redis",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.2",
|
|
4
|
+
"description": "Redis store for @drlock/core",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js",
|
|
12
|
+
"default": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist"
|
|
17
|
+
],
|
|
18
|
+
"scripts": {
|
|
19
|
+
"build": "tsc -p tsconfig.build.json",
|
|
20
|
+
"prepublishOnly": "npm run build",
|
|
21
|
+
"test": "node --experimental-strip-types --test test/*.test.ts",
|
|
22
|
+
"typecheck": "tsc -p tsconfig.json"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"@drlock/core": "0.0.2"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"ioredis": "^5.5.0",
|
|
29
|
+
"redis-memory-server": "^0.17.2"
|
|
30
|
+
},
|
|
31
|
+
"engines": {
|
|
32
|
+
"node": ">=22.6.0"
|
|
33
|
+
},
|
|
34
|
+
"license": "MIT",
|
|
35
|
+
"repository": {
|
|
36
|
+
"type": "git",
|
|
37
|
+
"url": "git+https://github.com/dgolovin-dev/drlock.git",
|
|
38
|
+
"directory": "packages/redis"
|
|
39
|
+
},
|
|
40
|
+
"bugs": {
|
|
41
|
+
"url": "https://github.com/dgolovin-dev/drlock/issues"
|
|
42
|
+
},
|
|
43
|
+
"keywords": [
|
|
44
|
+
"distributed-lock",
|
|
45
|
+
"reentrant",
|
|
46
|
+
"lock",
|
|
47
|
+
"mutex",
|
|
48
|
+
"redis",
|
|
49
|
+
"nodejs",
|
|
50
|
+
"typescript"
|
|
51
|
+
],
|
|
52
|
+
"author": "Dmitry Golovin",
|
|
53
|
+
"publishConfig": {
|
|
54
|
+
"access": "public"
|
|
55
|
+
}
|
|
56
|
+
}
|