@imqueue/rpc 3.5.3 → 3.6.0
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/package.json +1 -1
- package/src/IMQLock.d.ts +55 -3
- package/src/IMQLock.js +104 -22
- package/src/IMQRPCOptions.js +26 -4
- package/src/decorators/lock.js +7 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@imqueue/rpc",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.6.0",
|
|
4
4
|
"description": "Type-safe RPC framework for Node.js & TypeScript microservices over a Redis message queue — self-describing services generate their own strongly-typed clients (@imqueue framework)",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"redis",
|
package/src/IMQLock.d.ts
CHANGED
|
@@ -92,6 +92,15 @@ export interface IMQLockMetadata {
|
|
|
92
92
|
* Keys are used verbatim, with no prefixing or namespacing, so they are global to
|
|
93
93
|
* the process and unrelated call sites sharing a string share a lock.
|
|
94
94
|
*
|
|
95
|
+
* Exclusion is not absolute, and {@link IMQLock.deadlockTimeout} is why. A waiter
|
|
96
|
+
* that times out frees the key so that a holder which never releases cannot poison
|
|
97
|
+
* it for the life of the process — but the holder is still running, so the next
|
|
98
|
+
* call acquires and runs alongside it. Pass the {@link IMQLock.token} to
|
|
99
|
+
* {@link IMQLock.release}, as the example does and as {@link lock} does for you,
|
|
100
|
+
* and the damage stops there: the overtaken holder can no longer resolve the new
|
|
101
|
+
* holder's waiters or free a lock still in use. Set `deadlockTimeout` to `0` if
|
|
102
|
+
* you would rather have strict exclusion and let waiters wait forever.
|
|
103
|
+
*
|
|
95
104
|
* @example
|
|
96
105
|
* ```typescript
|
|
97
106
|
* import { IMQLock, type AcquiredLock } from '@imqueue/rpc';
|
|
@@ -102,6 +111,10 @@ export interface IMQLockMetadata {
|
|
|
102
111
|
*
|
|
103
112
|
* // locked() is the only reliable way to tell holder from waiter
|
|
104
113
|
* if (IMQLock.locked('doSomething')) {
|
|
114
|
+
* // read the token straight after acquiring and pass it to every
|
|
115
|
+
* // release, so a release cannot land on a later holder's lock
|
|
116
|
+
* const token = IMQLock.token('doSomething');
|
|
117
|
+
*
|
|
105
118
|
* // always wrap locked work in try/catch and release on both paths,
|
|
106
119
|
* // otherwise waiters hang until the deadlock timeout fires
|
|
107
120
|
* try {
|
|
@@ -109,12 +122,12 @@ export interface IMQLockMetadata {
|
|
|
109
122
|
* // resolves with this same value
|
|
110
123
|
* const res = Math.random();
|
|
111
124
|
*
|
|
112
|
-
* IMQLock.release('doSomething', res);
|
|
125
|
+
* IMQLock.release('doSomething', res, undefined, token);
|
|
113
126
|
*
|
|
114
127
|
* return res;
|
|
115
128
|
* } catch (err) {
|
|
116
129
|
* // reject every waiter with the same error
|
|
117
|
-
* IMQLock.release('doSomething', null, err);
|
|
130
|
+
* IMQLock.release('doSomething', null, err, token);
|
|
118
131
|
* throw err;
|
|
119
132
|
* }
|
|
120
133
|
* }
|
|
@@ -128,9 +141,18 @@ export interface IMQLockMetadata {
|
|
|
128
141
|
* ```
|
|
129
142
|
*/
|
|
130
143
|
export declare class IMQLock {
|
|
144
|
+
/**
|
|
145
|
+
* Maps a locked key to the token identifying its current holder. Absent
|
|
146
|
+
* means unlocked; tokens start at 1, so the map stays truthy-testable.
|
|
147
|
+
*/
|
|
131
148
|
private static acquiredLocks;
|
|
132
149
|
private static queues;
|
|
133
150
|
private static metadata;
|
|
151
|
+
/**
|
|
152
|
+
* Source of lock tokens, incremented once per successful acquire so that no
|
|
153
|
+
* two holders of the same key can ever share one.
|
|
154
|
+
*/
|
|
155
|
+
private static lastToken;
|
|
134
156
|
/**
|
|
135
157
|
* Deadlock timeout in milliseconds
|
|
136
158
|
*/
|
|
@@ -148,14 +170,44 @@ export declare class IMQLock {
|
|
|
148
170
|
* @param metadata - metadata for the locked call
|
|
149
171
|
*/
|
|
150
172
|
static acquire<T>(key: string, callback?: (...args: any[]) => any, metadata?: IMQLockMetadataItem): Promise<AcquiredLock<T>>;
|
|
173
|
+
/**
|
|
174
|
+
* Returns the token identifying the current holder of a given key, or
|
|
175
|
+
* `undefined` when the key is not locked.
|
|
176
|
+
*
|
|
177
|
+
* @remarks
|
|
178
|
+
* Read it immediately after {@link IMQLock.acquire} resolves and
|
|
179
|
+
* {@link IMQLock.locked} confirms you are the holder, then hand it back to
|
|
180
|
+
* {@link IMQLock.release} — that is what proves the release is yours. There
|
|
181
|
+
* is no way to recover it later: once the deadlock timeout has freed the
|
|
182
|
+
* key, this returns the NEXT holder's token, which is exactly the confusion
|
|
183
|
+
* the token exists to prevent.
|
|
184
|
+
*
|
|
185
|
+
* @param key - key to read the current holder's token for
|
|
186
|
+
*/
|
|
187
|
+
static token(key: string): number | undefined;
|
|
151
188
|
/**
|
|
152
189
|
* Releases a previously acquired lock for a given key.
|
|
153
190
|
*
|
|
191
|
+
* @remarks
|
|
192
|
+
* Pass the `token` {@link IMQLock.token} gave you when you acquired the
|
|
193
|
+
* lock, and the release is ignored unless the key is still yours. Without
|
|
194
|
+
* it the release is applied unconditionally, which is what this did for
|
|
195
|
+
* every caller: the deadlock timeout frees a key while its holder is still
|
|
196
|
+
* running, so the holder's eventual release landed on whichever call had
|
|
197
|
+
* acquired the key in the meantime — resolving that call's waiters with a
|
|
198
|
+
* result computed for nobody and freeing a lock still in use, which let a
|
|
199
|
+
* third call in behind it.
|
|
200
|
+
*
|
|
201
|
+
* The token is optional only to keep the signature compatible. A release
|
|
202
|
+
* without one cannot be checked, and stays as unsafe as it was.
|
|
203
|
+
*
|
|
154
204
|
* @param key - key to release the lock for
|
|
155
205
|
* @param value - value to resolve pending calls with
|
|
156
206
|
* @param err - error to reject pending calls with
|
|
207
|
+
* @param token - token from {@link IMQLock.token} proving this release is
|
|
208
|
+
* the holder's own
|
|
157
209
|
*/
|
|
158
|
-
static release<T, E>(key: string, value?: T, err?: E): void;
|
|
210
|
+
static release<T, E>(key: string, value?: T, err?: E, token?: number): void;
|
|
159
211
|
/**
|
|
160
212
|
* Returns true if the given key is locked, false otherwise.
|
|
161
213
|
*
|
package/src/IMQLock.js
CHANGED
|
@@ -38,6 +38,15 @@ import {} from '@imqueue/core';
|
|
|
38
38
|
* Keys are used verbatim, with no prefixing or namespacing, so they are global to
|
|
39
39
|
* the process and unrelated call sites sharing a string share a lock.
|
|
40
40
|
*
|
|
41
|
+
* Exclusion is not absolute, and {@link IMQLock.deadlockTimeout} is why. A waiter
|
|
42
|
+
* that times out frees the key so that a holder which never releases cannot poison
|
|
43
|
+
* it for the life of the process — but the holder is still running, so the next
|
|
44
|
+
* call acquires and runs alongside it. Pass the {@link IMQLock.token} to
|
|
45
|
+
* {@link IMQLock.release}, as the example does and as {@link lock} does for you,
|
|
46
|
+
* and the damage stops there: the overtaken holder can no longer resolve the new
|
|
47
|
+
* holder's waiters or free a lock still in use. Set `deadlockTimeout` to `0` if
|
|
48
|
+
* you would rather have strict exclusion and let waiters wait forever.
|
|
49
|
+
*
|
|
41
50
|
* @example
|
|
42
51
|
* ```typescript
|
|
43
52
|
* import { IMQLock, type AcquiredLock } from '@imqueue/rpc';
|
|
@@ -48,6 +57,10 @@ import {} from '@imqueue/core';
|
|
|
48
57
|
*
|
|
49
58
|
* // locked() is the only reliable way to tell holder from waiter
|
|
50
59
|
* if (IMQLock.locked('doSomething')) {
|
|
60
|
+
* // read the token straight after acquiring and pass it to every
|
|
61
|
+
* // release, so a release cannot land on a later holder's lock
|
|
62
|
+
* const token = IMQLock.token('doSomething');
|
|
63
|
+
*
|
|
51
64
|
* // always wrap locked work in try/catch and release on both paths,
|
|
52
65
|
* // otherwise waiters hang until the deadlock timeout fires
|
|
53
66
|
* try {
|
|
@@ -55,12 +68,12 @@ import {} from '@imqueue/core';
|
|
|
55
68
|
* // resolves with this same value
|
|
56
69
|
* const res = Math.random();
|
|
57
70
|
*
|
|
58
|
-
* IMQLock.release('doSomething', res);
|
|
71
|
+
* IMQLock.release('doSomething', res, undefined, token);
|
|
59
72
|
*
|
|
60
73
|
* return res;
|
|
61
74
|
* } catch (err) {
|
|
62
75
|
* // reject every waiter with the same error
|
|
63
|
-
* IMQLock.release('doSomething', null, err);
|
|
76
|
+
* IMQLock.release('doSomething', null, err, token);
|
|
64
77
|
* throw err;
|
|
65
78
|
* }
|
|
66
79
|
* }
|
|
@@ -74,9 +87,18 @@ import {} from '@imqueue/core';
|
|
|
74
87
|
* ```
|
|
75
88
|
*/
|
|
76
89
|
export class IMQLock {
|
|
90
|
+
/**
|
|
91
|
+
* Maps a locked key to the token identifying its current holder. Absent
|
|
92
|
+
* means unlocked; tokens start at 1, so the map stays truthy-testable.
|
|
93
|
+
*/
|
|
77
94
|
static acquiredLocks = {};
|
|
78
95
|
static queues = {};
|
|
79
96
|
static metadata = {};
|
|
97
|
+
/**
|
|
98
|
+
* Source of lock tokens, incremented once per successful acquire so that no
|
|
99
|
+
* two holders of the same key can ever share one.
|
|
100
|
+
*/
|
|
101
|
+
static lastToken = 0;
|
|
80
102
|
/**
|
|
81
103
|
* Deadlock timeout in milliseconds
|
|
82
104
|
*/
|
|
@@ -101,23 +123,7 @@ export class IMQLock {
|
|
|
101
123
|
if (IMQLock.locked(key)) {
|
|
102
124
|
return new Promise((resolve, reject) => {
|
|
103
125
|
let timer = null;
|
|
104
|
-
|
|
105
|
-
// avoid dead-locks using timeouts
|
|
106
|
-
timer = setTimeout(() => {
|
|
107
|
-
let dumpStr = '';
|
|
108
|
-
try {
|
|
109
|
-
dumpStr = JSON.stringify(IMQLock.metadata[key]);
|
|
110
|
-
}
|
|
111
|
-
catch {
|
|
112
|
-
dumpStr = 'Unable to stringify metadata';
|
|
113
|
-
}
|
|
114
|
-
const err = new Error(`Lock timeout, "${key}" call rejected, metadata: ${dumpStr}`);
|
|
115
|
-
timer && clearTimeout(timer);
|
|
116
|
-
timer = null;
|
|
117
|
-
IMQLock.release(key, null, err);
|
|
118
|
-
}, IMQLock.deadlockTimeout);
|
|
119
|
-
}
|
|
120
|
-
IMQLock.queues[key].push([
|
|
126
|
+
const task = [
|
|
121
127
|
(result) => {
|
|
122
128
|
// lock resolve
|
|
123
129
|
try {
|
|
@@ -142,20 +148,96 @@ export class IMQLock {
|
|
|
142
148
|
}
|
|
143
149
|
reject(err);
|
|
144
150
|
},
|
|
145
|
-
]
|
|
151
|
+
];
|
|
152
|
+
if (IMQLock.deadlockTimeout) {
|
|
153
|
+
// avoid dead-locks using timeouts
|
|
154
|
+
timer = setTimeout(() => {
|
|
155
|
+
let dumpStr = '';
|
|
156
|
+
try {
|
|
157
|
+
dumpStr = JSON.stringify(IMQLock.metadata[key]);
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
dumpStr = 'Unable to stringify metadata';
|
|
161
|
+
}
|
|
162
|
+
const err = new Error(`Lock timeout, "${key}" call rejected, metadata: ${dumpStr}`);
|
|
163
|
+
timer && clearTimeout(timer);
|
|
164
|
+
timer = null;
|
|
165
|
+
// Rejecting through release() used to reject EVERY
|
|
166
|
+
// waiter on the key and hand the holder's lock to
|
|
167
|
+
// whoever asked next, so a waiter that arrived a
|
|
168
|
+
// moment ago died for an older waiter's patience. Only
|
|
169
|
+
// this waiter is rejected now, and only this waiter is
|
|
170
|
+
// taken out of the queue.
|
|
171
|
+
const queue = IMQLock.queues[key] || [];
|
|
172
|
+
const index = queue.indexOf(task);
|
|
173
|
+
if (~index) {
|
|
174
|
+
queue.splice(index, 1);
|
|
175
|
+
}
|
|
176
|
+
// The key is still freed: the holder may be one that
|
|
177
|
+
// never releases, and leaving the lock in place would
|
|
178
|
+
// poison the key for the life of the process. The
|
|
179
|
+
// queue is deliberately left alone, so the next holder
|
|
180
|
+
// adopts the waiters instead of them being dropped.
|
|
181
|
+
delete IMQLock.acquiredLocks[key];
|
|
182
|
+
delete IMQLock.metadata[key];
|
|
183
|
+
task[1](err);
|
|
184
|
+
}, IMQLock.deadlockTimeout);
|
|
185
|
+
}
|
|
186
|
+
IMQLock.queues[key].push(task);
|
|
146
187
|
});
|
|
147
188
|
}
|
|
148
|
-
IMQLock.acquiredLocks[key] =
|
|
189
|
+
IMQLock.acquiredLocks[key] = ++IMQLock.lastToken;
|
|
149
190
|
return true;
|
|
150
191
|
}
|
|
192
|
+
/**
|
|
193
|
+
* Returns the token identifying the current holder of a given key, or
|
|
194
|
+
* `undefined` when the key is not locked.
|
|
195
|
+
*
|
|
196
|
+
* @remarks
|
|
197
|
+
* Read it immediately after {@link IMQLock.acquire} resolves and
|
|
198
|
+
* {@link IMQLock.locked} confirms you are the holder, then hand it back to
|
|
199
|
+
* {@link IMQLock.release} — that is what proves the release is yours. There
|
|
200
|
+
* is no way to recover it later: once the deadlock timeout has freed the
|
|
201
|
+
* key, this returns the NEXT holder's token, which is exactly the confusion
|
|
202
|
+
* the token exists to prevent.
|
|
203
|
+
*
|
|
204
|
+
* @param key - key to read the current holder's token for
|
|
205
|
+
*/
|
|
206
|
+
static token(key) {
|
|
207
|
+
return IMQLock.acquiredLocks[key];
|
|
208
|
+
}
|
|
151
209
|
/**
|
|
152
210
|
* Releases a previously acquired lock for a given key.
|
|
153
211
|
*
|
|
212
|
+
* @remarks
|
|
213
|
+
* Pass the `token` {@link IMQLock.token} gave you when you acquired the
|
|
214
|
+
* lock, and the release is ignored unless the key is still yours. Without
|
|
215
|
+
* it the release is applied unconditionally, which is what this did for
|
|
216
|
+
* every caller: the deadlock timeout frees a key while its holder is still
|
|
217
|
+
* running, so the holder's eventual release landed on whichever call had
|
|
218
|
+
* acquired the key in the meantime — resolving that call's waiters with a
|
|
219
|
+
* result computed for nobody and freeing a lock still in use, which let a
|
|
220
|
+
* third call in behind it.
|
|
221
|
+
*
|
|
222
|
+
* The token is optional only to keep the signature compatible. A release
|
|
223
|
+
* without one cannot be checked, and stays as unsafe as it was.
|
|
224
|
+
*
|
|
154
225
|
* @param key - key to release the lock for
|
|
155
226
|
* @param value - value to resolve pending calls with
|
|
156
227
|
* @param err - error to reject pending calls with
|
|
228
|
+
* @param token - token from {@link IMQLock.token} proving this release is
|
|
229
|
+
* the holder's own
|
|
157
230
|
*/
|
|
158
|
-
static release(key, value, err) {
|
|
231
|
+
static release(key, value, err, token) {
|
|
232
|
+
const owner = IMQLock.acquiredLocks[key];
|
|
233
|
+
// A different call owns the key now, so this release is a straggler
|
|
234
|
+
// from a holder the deadlock timeout already gave up on: it must not
|
|
235
|
+
// touch the current holder's lock, metadata or waiters. An unowned key
|
|
236
|
+
// is not a conflict — the timeout freed it and nobody took it, so the
|
|
237
|
+
// straggler is still the best answer its waiters are going to get.
|
|
238
|
+
if (token !== undefined && owner !== undefined && owner !== token) {
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
159
241
|
const queue = IMQLock.queues[key];
|
|
160
242
|
IMQLock.queues[key] = [];
|
|
161
243
|
delete IMQLock.acquiredLocks[key];
|
package/src/IMQRPCOptions.js
CHANGED
|
@@ -26,6 +26,28 @@ import {} from './IMQRPCRequest.js';
|
|
|
26
26
|
import {} from './IMQRPCResponse.js';
|
|
27
27
|
import { IMQService } from './IMQService.js';
|
|
28
28
|
import { IMQClient } from './IMQClient.js';
|
|
29
|
+
/**
|
|
30
|
+
* Process-wide anchor for the mutable default-option singletons below.
|
|
31
|
+
*
|
|
32
|
+
* @remarks
|
|
33
|
+
* A module can be evaluated more than once inside one process: a loader that
|
|
34
|
+
* handles ESM and CJS through separate pipelines — `tsx`, for one — produces a
|
|
35
|
+
* distinct instance for `require('@imqueue/rpc')` and `import('@imqueue/rpc')`.
|
|
36
|
+
* Ordinary module-scope objects would then exist twice, and anything that
|
|
37
|
+
* *mutates* them to install behaviour would silently patch a copy the
|
|
38
|
+
* application never calls. `@imqueue/opentelemetry` does exactly that to attach
|
|
39
|
+
* its `beforeCall`/`afterCall`/`wrapCall` tracing hooks, and produced no spans
|
|
40
|
+
* at all under such a loader, with no error to explain it.
|
|
41
|
+
*
|
|
42
|
+
* Keying on `Symbol.for` makes these singletons per *process* rather than per
|
|
43
|
+
* module evaluation, so every instance hands out the same object and a mutation
|
|
44
|
+
* through any of them is visible to all.
|
|
45
|
+
*/
|
|
46
|
+
const shared = (key, create) => {
|
|
47
|
+
const anchor = globalThis;
|
|
48
|
+
const symbol = Symbol.for(`@imqueue/rpc:${key}`);
|
|
49
|
+
return (anchor[symbol] ??= create());
|
|
50
|
+
};
|
|
29
51
|
/**
|
|
30
52
|
* Default options applied to every IMQ service: the core queue defaults, plus
|
|
31
53
|
* cleanup enabled with a `'*:client'` filter, single-process mode, and one worker
|
|
@@ -41,13 +63,13 @@ import { IMQClient } from './IMQClient.js';
|
|
|
41
63
|
* {@link DEFAULT_IMQ_METRICS_SERVER_OPTIONS} and are merged in separately by the
|
|
42
64
|
* service constructor.
|
|
43
65
|
*/
|
|
44
|
-
export const DEFAULT_IMQ_SERVICE_OPTIONS = {
|
|
66
|
+
export const DEFAULT_IMQ_SERVICE_OPTIONS = shared('DEFAULT_IMQ_SERVICE_OPTIONS', () => ({
|
|
45
67
|
...DEFAULT_IMQ_OPTIONS,
|
|
46
68
|
cleanup: true,
|
|
47
69
|
cleanupFilter: '*:client',
|
|
48
70
|
multiProcess: false,
|
|
49
71
|
childrenPerCore: 1,
|
|
50
|
-
};
|
|
72
|
+
}));
|
|
51
73
|
/**
|
|
52
74
|
* Default metrics server options
|
|
53
75
|
*/
|
|
@@ -69,7 +91,7 @@ export const DEFAULT_IMQ_METRICS_SERVER_OPTIONS = {
|
|
|
69
91
|
* As with the service defaults, `cleanup: true` and `cleanupFilter: '*:client'`
|
|
70
92
|
* override the core defaults, and `timeout` applies to the generator only.
|
|
71
93
|
*/
|
|
72
|
-
export const DEFAULT_IMQ_CLIENT_OPTIONS = {
|
|
94
|
+
export const DEFAULT_IMQ_CLIENT_OPTIONS = shared('DEFAULT_IMQ_CLIENT_OPTIONS', () => ({
|
|
73
95
|
...DEFAULT_IMQ_OPTIONS,
|
|
74
96
|
cleanup: true,
|
|
75
97
|
cleanupFilter: '*:client',
|
|
@@ -77,5 +99,5 @@ export const DEFAULT_IMQ_CLIENT_OPTIONS = {
|
|
|
77
99
|
compile: true,
|
|
78
100
|
timeout: 30000,
|
|
79
101
|
write: true,
|
|
80
|
-
};
|
|
102
|
+
}));
|
|
81
103
|
//# sourceMappingURL=IMQRPCOptions.js.map
|
package/src/decorators/lock.js
CHANGED
|
@@ -49,6 +49,10 @@ export function lock(enabledOrOptions = true) {
|
|
|
49
49
|
const withLocks = !parseInt(process.env['DISABLE_LOCKS'] + '') && enabled;
|
|
50
50
|
let lock;
|
|
51
51
|
let sig = '';
|
|
52
|
+
// identifies THIS call as the holder, so a release that arrives
|
|
53
|
+
// after the deadlock timeout gave the key away cannot land on
|
|
54
|
+
// whoever holds it now
|
|
55
|
+
let token;
|
|
52
56
|
if (withLocks) {
|
|
53
57
|
sig = signature(className, methodName, skipArgs
|
|
54
58
|
? args.filter((_, index) => !~skipArgs.indexOf(index))
|
|
@@ -61,6 +65,7 @@ export function lock(enabledOrOptions = true) {
|
|
|
61
65
|
if (!IMQLock.locked(sig)) {
|
|
62
66
|
return lock;
|
|
63
67
|
}
|
|
68
|
+
token = IMQLock.token(sig);
|
|
64
69
|
}
|
|
65
70
|
try {
|
|
66
71
|
let result = original
|
|
@@ -72,13 +77,13 @@ export function lock(enabledOrOptions = true) {
|
|
|
72
77
|
result = await result;
|
|
73
78
|
}
|
|
74
79
|
if (withLocks) {
|
|
75
|
-
IMQLock.release(sig, result);
|
|
80
|
+
IMQLock.release(sig, result, undefined, token);
|
|
76
81
|
}
|
|
77
82
|
return result;
|
|
78
83
|
}
|
|
79
84
|
catch (err) {
|
|
80
85
|
if (withLocks) {
|
|
81
|
-
IMQLock.release(sig, null, err);
|
|
86
|
+
IMQLock.release(sig, null, err, token);
|
|
82
87
|
}
|
|
83
88
|
throw err;
|
|
84
89
|
}
|