@twin.org/core 0.9.3-next.4 → 0.9.3-next.5
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/dist/es/index.js +1 -0
- package/dist/es/index.js.map +1 -1
- package/dist/es/models/IMutexWaiter.js +4 -0
- package/dist/es/models/IMutexWaiter.js.map +1 -0
- package/dist/es/utils/mutex.js +170 -23
- package/dist/es/utils/mutex.js.map +1 -1
- package/dist/types/index.d.ts +1 -0
- package/dist/types/models/IMutexWaiter.d.ts +17 -0
- package/dist/types/utils/mutex.d.ts +9 -0
- package/docs/changelog.md +17 -0
- package/docs/reference/classes/Mutex.md +9 -0
- package/docs/reference/index.md +1 -0
- package/docs/reference/interfaces/IMutexWaiter.md +37 -0
- package/locales/en.json +1 -1
- package/package.json +2 -2
package/dist/es/index.js
CHANGED
|
@@ -41,6 +41,7 @@ export * from "./models/ILabelledValue.js";
|
|
|
41
41
|
export * from "./models/ILocale.js";
|
|
42
42
|
export * from "./models/ILocaleDictionary.js";
|
|
43
43
|
export * from "./models/ILocalesIndex.js";
|
|
44
|
+
export * from "./models/IMutexWaiter.js";
|
|
44
45
|
export * from "./models/IMutexWorkerMessage.js";
|
|
45
46
|
export * from "./models/IPatchOperation.js";
|
|
46
47
|
export * from "./models/ISharedObjectBufferOptions.js";
|
package/dist/es/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AACvC,cAAc,sBAAsB,CAAC;AACrC,cAAc,sBAAsB,CAAC;AACrC,cAAc,sBAAsB,CAAC;AACrC,cAAc,yBAAyB,CAAC;AACxC,cAAc,gCAAgC,CAAC;AAC/C,cAAc,uBAAuB,CAAC;AACtC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,0BAA0B,CAAC;AACzC,cAAc,wBAAwB,CAAC;AACvC,cAAc,2BAA2B,C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Ac,gBAAgB,CAAC;AAC/B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,uBAAuB,CAAC;AACtC,cAAc,qBAAqB,CAAC;AACpC,cAAc,qBAAqB,CAAC;AACpC,cAAc,mBAAmB,CAAC;AAClC,cAAc,wBAAwB,CAAC;AACvC,cAAc,sBAAsB,CAAC;AACrC,cAAc,mBAAmB,CAAC;AAClC,cAAc,iBAAiB,CAAC;AAChC,cAAc,eAAe,CAAC;AAC9B,cAAc,kBAAkB,CAAC;AACjC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,wBAAwB,CAAC;AACvC,cAAc,uBAAuB,CAAC","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nexport * from \"./encoding/base32.js\";\nexport * from \"./encoding/base58.js\";\nexport * from \"./encoding/base64.js\";\nexport * from \"./encoding/base64Url.js\";\nexport * from \"./errors/alreadyExistsError.js\";\nexport * from \"./errors/baseError.js\";\nexport * from \"./errors/conflictError.js\";\nexport * from \"./errors/generalError.js\";\nexport * from \"./errors/guardError.js\";\nexport * from \"./errors/notFoundError.js\";\nexport * from \"./errors/notImplementedError.js\";\nexport * from \"./errors/notSupportedError.js\";\nexport * from \"./errors/unauthorizedError.js\";\nexport * from \"./errors/unprocessableError.js\";\nexport * from \"./errors/validationError.js\";\nexport * from \"./factories/componentFactory.js\";\nexport * from \"./factories/facadeFactory.js\";\nexport * from \"./factories/factory.js\";\nexport * from \"./helpers/arrayHelper.js\";\nexport * from \"./helpers/envHelper.js\";\nexport * from \"./helpers/errorHelper.js\";\nexport * from \"./helpers/filenameHelper.js\";\nexport * from \"./helpers/hexHelper.js\";\nexport * from \"./helpers/jsonHelper.js\";\nexport * from \"./helpers/numberHelper.js\";\nexport * from \"./helpers/objectHelper.js\";\nexport * from \"./helpers/randomHelper.js\";\nexport * from \"./helpers/stringHelper.js\";\nexport * from \"./helpers/uint8ArrayHelper.js\";\nexport * from \"./models/coerceType.js\";\nexport * from \"./models/IDuration.js\";\nexport * from \"./models/compressionType.js\";\nexport * from \"./models/IComponent.js\";\nexport * from \"./models/IFacade.js\";\nexport * from \"./models/IError.js\";\nexport * from \"./models/II18nShared.js\";\nexport * from \"./models/IKeyValue.js\";\nexport * from \"./models/ILabelledValue.js\";\nexport * from \"./models/ILocale.js\";\nexport * from \"./models/ILocaleDictionary.js\";\nexport * from \"./models/ILocalesIndex.js\";\nexport * from \"./models/IMutexWorkerMessage.js\";\nexport * from \"./models/IPatchOperation.js\";\nexport * from \"./models/ISharedObjectBufferOptions.js\";\nexport * from \"./models/ISharedObjectBufferWorkerMessage.js\";\nexport * from \"./models/IUrlParts.js\";\nexport * from \"./models/IValidationFailure.js\";\nexport * from \"./models/mutexMessageTypes.js\";\nexport * from \"./models/sharedObjectBufferMessageTypes.js\";\nexport * from \"./types/bitString.js\";\nexport * from \"./types/duration.js\";\nexport * from \"./types/durationRegExp.js\";\nexport * from \"./types/objectOrArray.js\";\nexport * from \"./types/singleOccurrenceArray.js\";\nexport * from \"./types/singleOccurrenceArrayDepthHelper.js\";\nexport * from \"./types/url.js\";\nexport * from \"./types/urn.js\";\nexport * from \"./utils/asyncCache.js\";\nexport * from \"./utils/lfuCache.js\";\nexport * from \"./utils/lruCache.js\";\nexport * from \"./utils/coerce.js\";\nexport * from \"./utils/compression.js\";\nexport * from \"./utils/converter.js\";\nexport * from \"./utils/guards.js\";\nexport * from \"./utils/i18n.js\";\nexport * from \"./utils/is.js\";\nexport * from \"./utils/mutex.js\";\nexport * from \"./utils/sharedObjectBuffer.js\";\nexport * from \"./utils/sharedStore.js\";\nexport * from \"./utils/validation.js\";\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AACvC,cAAc,sBAAsB,CAAC;AACrC,cAAc,sBAAsB,CAAC;AACrC,cAAc,sBAAsB,CAAC;AACrC,cAAc,yBAAyB,CAAC;AACxC,cAAc,g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AC3D,cAAc,sBAAsB,CAAC;AACrC,cAAc,qBAAqB,CAAC;AACpC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,0BAA0B,CAAC;AACzC,cAAc,kCAAkC,CAAC;AACjD,cAAc,6CAA6C,CAAC;AAC5D,cAAc,gBAAgB,CAAC;AAC/B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,uBAAuB,CAAC;AACtC,cAAc,qBAAqB,CAAC;AACpC,cAAc,qBAAqB,CAAC;AACpC,cAAc,mBAAmB,CAAC;AAClC,cAAc,wBAAwB,CAAC;AACvC,cAAc,sBAAsB,CAAC;AACrC,cAAc,mBAAmB,CAAC;AAClC,cAAc,iBAAiB,CAAC;AAChC,cAAc,eAAe,CAAC;AAC9B,cAAc,kBAAkB,CAAC;AACjC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,wBAAwB,CAAC;AACvC,cAAc,uBAAuB,CAAC","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nexport * from \"./encoding/base32.js\";\nexport * from \"./encoding/base58.js\";\nexport * from \"./encoding/base64.js\";\nexport * from \"./encoding/base64Url.js\";\nexport * from \"./errors/alreadyExistsError.js\";\nexport * from \"./errors/baseError.js\";\nexport * from \"./errors/conflictError.js\";\nexport * from \"./errors/generalError.js\";\nexport * from \"./errors/guardError.js\";\nexport * from \"./errors/notFoundError.js\";\nexport * from \"./errors/notImplementedError.js\";\nexport * from \"./errors/notSupportedError.js\";\nexport * from \"./errors/unauthorizedError.js\";\nexport * from \"./errors/unprocessableError.js\";\nexport * from \"./errors/validationError.js\";\nexport * from \"./factories/componentFactory.js\";\nexport * from \"./factories/facadeFactory.js\";\nexport * from \"./factories/factory.js\";\nexport * from \"./helpers/arrayHelper.js\";\nexport * from \"./helpers/envHelper.js\";\nexport * from \"./helpers/errorHelper.js\";\nexport * from \"./helpers/filenameHelper.js\";\nexport * from \"./helpers/hexHelper.js\";\nexport * from \"./helpers/jsonHelper.js\";\nexport * from \"./helpers/numberHelper.js\";\nexport * from \"./helpers/objectHelper.js\";\nexport * from \"./helpers/randomHelper.js\";\nexport * from \"./helpers/stringHelper.js\";\nexport * from \"./helpers/uint8ArrayHelper.js\";\nexport * from \"./models/coerceType.js\";\nexport * from \"./models/IDuration.js\";\nexport * from \"./models/compressionType.js\";\nexport * from \"./models/IComponent.js\";\nexport * from \"./models/IFacade.js\";\nexport * from \"./models/IError.js\";\nexport * from \"./models/II18nShared.js\";\nexport * from \"./models/IKeyValue.js\";\nexport * from \"./models/ILabelledValue.js\";\nexport * from \"./models/ILocale.js\";\nexport * from \"./models/ILocaleDictionary.js\";\nexport * from \"./models/ILocalesIndex.js\";\nexport * from \"./models/IMutexWaiter.js\";\nexport * from \"./models/IMutexWorkerMessage.js\";\nexport * from \"./models/IPatchOperation.js\";\nexport * from \"./models/ISharedObjectBufferOptions.js\";\nexport * from \"./models/ISharedObjectBufferWorkerMessage.js\";\nexport * from \"./models/IUrlParts.js\";\nexport * from \"./models/IValidationFailure.js\";\nexport * from \"./models/mutexMessageTypes.js\";\nexport * from \"./models/sharedObjectBufferMessageTypes.js\";\nexport * from \"./types/bitString.js\";\nexport * from \"./types/duration.js\";\nexport * from \"./types/durationRegExp.js\";\nexport * from \"./types/objectOrArray.js\";\nexport * from \"./types/singleOccurrenceArray.js\";\nexport * from \"./types/singleOccurrenceArrayDepthHelper.js\";\nexport * from \"./types/url.js\";\nexport * from \"./types/urn.js\";\nexport * from \"./utils/asyncCache.js\";\nexport * from \"./utils/lfuCache.js\";\nexport * from \"./utils/lruCache.js\";\nexport * from \"./utils/coerce.js\";\nexport * from \"./utils/compression.js\";\nexport * from \"./utils/converter.js\";\nexport * from \"./utils/guards.js\";\nexport * from \"./utils/i18n.js\";\nexport * from \"./utils/is.js\";\nexport * from \"./utils/mutex.js\";\nexport * from \"./utils/sharedObjectBuffer.js\";\nexport * from \"./utils/sharedStore.js\";\nexport * from \"./utils/validation.js\";\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"IMutexWaiter.js","sourceRoot":"","sources":["../../../src/models/IMutexWaiter.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\n\n/**\n * A caller queued on a mutex key, waiting to be handed the lock.\n */\nexport interface IMutexWaiter {\n\t/**\n\t * Has the waiter already been granted the lock or given up waiting.\n\t */\n\tsettled: boolean;\n\n\t/**\n\t * Resolves the queued caller, true when it now owns the lock.\n\t */\n\tresolve?: (granted: boolean) => void;\n\n\t/**\n\t * Timer which enforces the waiter's deadline.\n\t */\n\ttimer?: ReturnType<typeof setTimeout>;\n}\n"]}
|
package/dist/es/utils/mutex.js
CHANGED
|
@@ -16,6 +16,13 @@ import { MutexMessageTypes } from "../models/mutexMessageTypes.js";
|
|
|
16
16
|
* The main thread must call Mutex.handleWorkerMessage(msg) from its worker message handler
|
|
17
17
|
* before that worker first calls Mutex.lock().
|
|
18
18
|
*
|
|
19
|
+
* Callers on the same thread are served in the order they arrived. Each key has a FIFO
|
|
20
|
+
* queue of waiters, unlock() hands the lock directly to the waiter at the front, and a new
|
|
21
|
+
* caller only takes the lock outright when that queue is empty. Without this a caller that
|
|
22
|
+
* arrives while a waiter is being woken can take the lock first, which lets a busy key
|
|
23
|
+
* starve a waiter until its timeout elapses. Threads still contend with each other for the
|
|
24
|
+
* shared lock, so the ordering guarantee is per thread rather than global.
|
|
25
|
+
*
|
|
19
26
|
* The lock is not re-entrant: a thread that already holds a key and calls lock() again on
|
|
20
27
|
* the same key will block until the timeout elapses.
|
|
21
28
|
*/
|
|
@@ -34,6 +41,23 @@ export class Mutex {
|
|
|
34
41
|
* @internal
|
|
35
42
|
*/
|
|
36
43
|
static _DEFAULT_TIMEOUT_KEY = "mutexDefaultTimeoutMs";
|
|
44
|
+
/**
|
|
45
|
+
* SharedStore key for the per-thread map from lock key strings to FIFO waiter queues.
|
|
46
|
+
* @internal
|
|
47
|
+
*/
|
|
48
|
+
static _WAITERS_KEY = "mutexWaiters";
|
|
49
|
+
/**
|
|
50
|
+
* SharedStore key for the per-thread map from lock key strings to the running watch task.
|
|
51
|
+
* @internal
|
|
52
|
+
*/
|
|
53
|
+
static _WATCHERS_KEY = "mutexWatchers";
|
|
54
|
+
/**
|
|
55
|
+
* How long the watch task waits on the shared lock before re-reading the queue, in
|
|
56
|
+
* milliseconds. It only bounds how quickly the task notices that the queue has drained,
|
|
57
|
+
* releases from other threads wake it immediately.
|
|
58
|
+
* @internal
|
|
59
|
+
*/
|
|
60
|
+
static _WATCH_TIMEOUT_MS = 250;
|
|
37
61
|
/**
|
|
38
62
|
* Cached reference to the node:worker_threads module, null if unavailable (browser).
|
|
39
63
|
* @internal
|
|
@@ -65,6 +89,8 @@ export class Mutex {
|
|
|
65
89
|
* held, it suspends the current async task until the lock is released or the timeout is reached.
|
|
66
90
|
* Use this in async single-threaded contexts (e.g. the main thread or a Fastify route handler)
|
|
67
91
|
* where calling the synchronous lock() would freeze the event loop and deadlock.
|
|
92
|
+
* Callers on the same thread are served in the order they arrived, so a contended key
|
|
93
|
+
* cannot starve an earlier caller.
|
|
68
94
|
* The lock is not re-entrant: if the same context holds the key and calls lockAsync() again on
|
|
69
95
|
* the same key, it will suspend until the timeout elapses.
|
|
70
96
|
* @param key The key to lock on.
|
|
@@ -90,31 +116,39 @@ export class Mutex {
|
|
|
90
116
|
// getOrFetchLock may block once per key on worker threads to negotiate the
|
|
91
117
|
// shared buffer with the main thread; that one-time fetch is acceptable here.
|
|
92
118
|
const lock = await Mutex.getOrFetchLock(key, deadline);
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
if (
|
|
102
|
-
|
|
103
|
-
throw new GeneralError(Mutex.CLASS_NAME, "lockTimeout", { key, timeoutMs });
|
|
104
|
-
}
|
|
105
|
-
return false;
|
|
106
|
-
}
|
|
107
|
-
// Suspend without blocking the event loop so the lock holder's async
|
|
108
|
-
// continuations can run and eventually call unlock().
|
|
109
|
-
const waitResult = Atomics.waitAsync(lock, 0, 1, remaining);
|
|
110
|
-
const outcome = waitResult.async ? await waitResult.value : waitResult.value;
|
|
111
|
-
if (outcome === "timed-out") {
|
|
112
|
-
if (throwOnTimeout) {
|
|
113
|
-
throw new GeneralError(Mutex.CLASS_NAME, "lockTimeout", { key, timeoutMs });
|
|
114
|
-
}
|
|
115
|
-
return false;
|
|
119
|
+
const queue = Mutex.getQueue(key);
|
|
120
|
+
// Atomically swap 0 → 1; if the previous value was 0 we acquired the lock. Only take
|
|
121
|
+
// it outright when nothing on this thread is already queued, otherwise this caller
|
|
122
|
+
// would barge in front of waiters that arrived earlier.
|
|
123
|
+
if (queue.length === 0 && Atomics.compareExchange(lock, 0, 0, 1) === 0) {
|
|
124
|
+
return true;
|
|
125
|
+
}
|
|
126
|
+
if (deadline - Date.now() <= 0) {
|
|
127
|
+
if (throwOnTimeout) {
|
|
128
|
+
throw new GeneralError(Mutex.CLASS_NAME, "lockTimeout", { key, timeoutMs });
|
|
116
129
|
}
|
|
130
|
+
return false;
|
|
117
131
|
}
|
|
132
|
+
// Join the back of the queue and suspend without blocking the event loop, so the
|
|
133
|
+
// holder's async continuations can run and eventually call unlock(). The lock is
|
|
134
|
+
// handed over either by unlock() on this thread or by the watch task below when
|
|
135
|
+
// another thread releases it.
|
|
136
|
+
const waiter = { settled: false };
|
|
137
|
+
const granted = new Promise(resolve => {
|
|
138
|
+
waiter.resolve = resolve;
|
|
139
|
+
});
|
|
140
|
+
queue.push(waiter);
|
|
141
|
+
// The deadline is enforced by a timer rather than only by the atomic wait, so a
|
|
142
|
+
// congested event loop cannot stretch the wait well beyond the requested timeout.
|
|
143
|
+
waiter.timer = setTimeout(() => Mutex.settleWaiter(key, waiter, false), deadline - Date.now());
|
|
144
|
+
Mutex.startWatching(key, lock);
|
|
145
|
+
if (await granted) {
|
|
146
|
+
return true;
|
|
147
|
+
}
|
|
148
|
+
if (throwOnTimeout) {
|
|
149
|
+
throw new GeneralError(Mutex.CLASS_NAME, "lockTimeout", { key, timeoutMs });
|
|
150
|
+
}
|
|
151
|
+
return false;
|
|
118
152
|
}
|
|
119
153
|
/**
|
|
120
154
|
* Releases the lock for the given key.
|
|
@@ -132,6 +166,14 @@ export class Mutex {
|
|
|
132
166
|
if (previous !== 1) {
|
|
133
167
|
throw new GeneralError(Mutex.CLASS_NAME, "lockAlreadyReleased", { key });
|
|
134
168
|
}
|
|
169
|
+
// Hand the lock straight to the caller at the front of this thread's queue. Nothing
|
|
170
|
+
// else on this thread can run between the release above and the re-acquire below, so
|
|
171
|
+
// no later caller can see the released state and take it first.
|
|
172
|
+
const next = Mutex.getWaiters()[key]?.[0];
|
|
173
|
+
if (!Is.empty(next) && Atomics.compareExchange(lock, 0, 0, 1) === 0) {
|
|
174
|
+
Mutex.settleWaiter(key, next, true);
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
135
177
|
Atomics.notify(lock, 0, 1);
|
|
136
178
|
}
|
|
137
179
|
/**
|
|
@@ -223,6 +265,111 @@ export class Mutex {
|
|
|
223
265
|
port1.close();
|
|
224
266
|
}
|
|
225
267
|
}
|
|
268
|
+
/**
|
|
269
|
+
* Settle a queued waiter, remove it from the queue and resume its caller.
|
|
270
|
+
* @param key The lock key.
|
|
271
|
+
* @param waiter The waiter to settle.
|
|
272
|
+
* @param granted True when the waiter has been handed the lock and now owns it.
|
|
273
|
+
* @internal
|
|
274
|
+
*/
|
|
275
|
+
static settleWaiter(key, waiter, granted) {
|
|
276
|
+
if (waiter.settled) {
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
waiter.settled = true;
|
|
280
|
+
if (!Is.empty(waiter.timer)) {
|
|
281
|
+
clearTimeout(waiter.timer);
|
|
282
|
+
waiter.timer = undefined;
|
|
283
|
+
}
|
|
284
|
+
const queue = Mutex.getWaiters()[key];
|
|
285
|
+
const index = queue?.indexOf(waiter) ?? -1;
|
|
286
|
+
if (index >= 0) {
|
|
287
|
+
queue.splice(index, 1);
|
|
288
|
+
}
|
|
289
|
+
waiter.resolve?.(granted);
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Start the watch task for a key if one is not already running.
|
|
293
|
+
* @param key The lock key.
|
|
294
|
+
* @param lock The shared lock for the key.
|
|
295
|
+
* @internal
|
|
296
|
+
*/
|
|
297
|
+
static startWatching(key, lock) {
|
|
298
|
+
const watchers = Mutex.getWatchers();
|
|
299
|
+
watchers[key] ??= Mutex.runWatcher(key, lock);
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Run the watch task for a key and clear its registry entry once it ends. The entry is
|
|
303
|
+
* only cleared after an await, so it cannot be removed before startWatching has recorded
|
|
304
|
+
* it, even when the task itself completes without suspending.
|
|
305
|
+
* @param key The lock key.
|
|
306
|
+
* @param lock The shared lock for the key.
|
|
307
|
+
* @returns A promise that resolves when the task ends.
|
|
308
|
+
* @internal
|
|
309
|
+
*/
|
|
310
|
+
static async runWatcher(key, lock) {
|
|
311
|
+
try {
|
|
312
|
+
await Mutex.watchQueue(key, lock);
|
|
313
|
+
}
|
|
314
|
+
finally {
|
|
315
|
+
delete Mutex.getWatchers()[key];
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Watch the shared lock for a key and hand it to the waiter at the front of the queue.
|
|
320
|
+
* This covers releases from other threads, a release on this thread hands the lock over
|
|
321
|
+
* directly in unlock(). The task ends once the queue for the key has drained.
|
|
322
|
+
* @param key The lock key.
|
|
323
|
+
* @param lock The shared lock for the key.
|
|
324
|
+
* @returns A promise that resolves when the task ends.
|
|
325
|
+
* @internal
|
|
326
|
+
*/
|
|
327
|
+
static async watchQueue(key, lock) {
|
|
328
|
+
for (;;) {
|
|
329
|
+
// Re-read the front of the queue on every pass, waiters that reached their
|
|
330
|
+
// deadline have already removed themselves.
|
|
331
|
+
const head = Mutex.getWaiters()[key]?.[0];
|
|
332
|
+
if (Is.empty(head)) {
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
if (Atomics.compareExchange(lock, 0, 0, 1) === 0) {
|
|
336
|
+
Mutex.settleWaiter(key, head, true);
|
|
337
|
+
}
|
|
338
|
+
else {
|
|
339
|
+
const waitResult = Atomics.waitAsync(lock, 0, 1, Mutex._WATCH_TIMEOUT_MS);
|
|
340
|
+
if (waitResult.async) {
|
|
341
|
+
await waitResult.value;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Get the FIFO waiter queue for a key, creating it if it does not exist.
|
|
348
|
+
* @param key The lock key.
|
|
349
|
+
* @returns The waiter queue for the key.
|
|
350
|
+
* @internal
|
|
351
|
+
*/
|
|
352
|
+
static getQueue(key) {
|
|
353
|
+
const waiters = Mutex.getWaiters();
|
|
354
|
+
waiters[key] ??= [];
|
|
355
|
+
return waiters[key];
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Get the shared waiter queues map, creating it if it does not exist.
|
|
359
|
+
* @returns The shared waiter queues map.
|
|
360
|
+
* @internal
|
|
361
|
+
*/
|
|
362
|
+
static getWaiters() {
|
|
363
|
+
return SharedStore.get(Mutex._WAITERS_KEY, () => ({}));
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Get the shared watch tasks map, creating it if it does not exist.
|
|
367
|
+
* @returns The shared watch tasks map.
|
|
368
|
+
* @internal
|
|
369
|
+
*/
|
|
370
|
+
static getWatchers() {
|
|
371
|
+
return SharedStore.get(Mutex._WATCHERS_KEY, () => ({}));
|
|
372
|
+
}
|
|
226
373
|
/**
|
|
227
374
|
* Get the shared locks map, creating it if it does not exist.
|
|
228
375
|
* @returns The shared locks map.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mutex.js","sourceRoot":"","sources":["../../../src/utils/mutex.ts"],"names":[],"mappings":"AA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AK,CAAC,iBAAiB;QACrC,IAAI,KAAK,CAAC,oBAAoB,KAAK,SAAS,EAAE,CAAC;YAC9C,IAAI,CAAC;gBACJ,KAAK,CAAC,oBAAoB,GAAG,MAAM,MAAM,CAAC,qBAAqB,CAAC,CAAC;YAClE,CAAC;YAAC,MAAM,CAAC;gBACR,KAAK,CAAC,oBAAoB,GAAG,IAAI,CAAC;YACnC,CAAC;QACF,CAAC;QACD,OAAO,KAAK,CAAC,oBAAoB,CAAC;IACnC,CAAC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { MessagePort } from \"node:worker_threads\";\nimport { nameof } from \"@twin.org/nameof\";\nimport { Guards } from \"./guards.js\";\nimport { Is } from \"./is.js\";\nimport { SharedStore } from \"./sharedStore.js\";\nimport { GeneralError } from \"../errors/generalError.js\";\nimport type { IMutexWorkerMessage } from \"../models/IMutexWorkerMessage.js\";\nimport { MutexMessageTypes } from \"../models/mutexMessageTypes.js\";\n\n/**\n * A cross-thread mutex built on Atomics and SharedArrayBuffer.\n *\n * When isMainThread is true (main thread or fork-mode child process) the class acts as\n * the authoritative registry: it creates a SharedArrayBuffer-backed Int32Array for each\n * key on first use and never discards it, because worker threads may hold references to\n * the same underlying memory.\n *\n * When isMainThread is false (a true worker thread) the class synchronously negotiates\n * the shared buffer with the main thread on first use of each key, then caches it locally.\n * The main thread must call Mutex.handleWorkerMessage(msg) from its worker message handler\n * before that worker first calls Mutex.lock().\n *\n * The lock is not re-entrant: a thread that already holds a key and calls lock() again on\n * the same key will block until the timeout elapses.\n */\nexport class Mutex {\n\t/**\n\t * Runtime name for the class.\n\t */\n\tpublic static readonly CLASS_NAME: string = nameof<Mutex>();\n\n\t/**\n\t * SharedStore key for the per-thread sparse map from lock key strings to Int32Arrays.\n\t * @internal\n\t */\n\tprivate static readonly _LOCKS_KEY = \"mutexLocks\";\n\n\t/**\n\t * SharedStore key for the default timeout in milliseconds.\n\t * @internal\n\t */\n\tprivate static readonly _DEFAULT_TIMEOUT_KEY = \"mutexDefaultTimeoutMs\";\n\n\t/**\n\t * Cached reference to the node:worker_threads module, null if unavailable (browser).\n\t * @internal\n\t */\n\t// false positive: this is a type not an actual import\n\t// eslint-disable-next-line @typescript-eslint/consistent-type-imports\n\tprivate static _workerThreadsModule: typeof import(\"node:worker_threads\") | null | undefined;\n\n\t/**\n\t * Gets the default timeout in milliseconds for lock acquisition.\n\t * @returns The default timeout in milliseconds.\n\t */\n\tpublic static getDefaultTimeoutMs(): number {\n\t\treturn SharedStore.get<number>(Mutex._DEFAULT_TIMEOUT_KEY) ?? 5000;\n\t}\n\n\t/**\n\t * Sets the default timeout in milliseconds for lock acquisition.\n\t * @param timeoutMs The default timeout in milliseconds.\n\t * @throws GeneralError if timeoutMs is not a non-negative integer.\n\t */\n\tpublic static setDefaultTimeoutMs(timeoutMs: number): void {\n\t\tGuards.integer(Mutex.CLASS_NAME, nameof(timeoutMs), timeoutMs);\n\t\tif (timeoutMs < 0) {\n\t\t\tthrow new GeneralError(Mutex.CLASS_NAME, \"invalidTimeout\", { timeoutMs });\n\t\t}\n\t\tSharedStore.set(Mutex._DEFAULT_TIMEOUT_KEY, timeoutMs);\n\t}\n\n\t/**\n\t * Acquires a lock for the given key without blocking the event loop. If the lock is already\n\t * held, it suspends the current async task until the lock is released or the timeout is reached.\n\t * Use this in async single-threaded contexts (e.g. the main thread or a Fastify route handler)\n\t * where calling the synchronous lock() would freeze the event loop and deadlock.\n\t * The lock is not re-entrant: if the same context holds the key and calls lockAsync() again on\n\t * the same key, it will suspend until the timeout elapses.\n\t * @param key The key to lock on.\n\t * @param options Lock options.\n\t * @param options.timeoutMs The maximum time to wait for the lock in milliseconds, defaults to getDefaultTimeoutMs().\n\t * @param options.throwOnTimeout Whether to throw an error if the lock could not be acquired within the timeout, default is false.\n\t * @returns True if the lock was acquired, false if it timed out and throwOnTimeout is false.\n\t * @throws GeneralError if the key is invalid or if the lock could not be acquired within the timeout and throwOnTimeout is true.\n\t */\n\tpublic static async lock(\n\t\tkey: string,\n\t\toptions?: { timeoutMs?: number; throwOnTimeout?: boolean }\n\t): Promise<boolean> {\n\t\tGuards.stringValue(Mutex.CLASS_NAME, nameof(key), key);\n\t\tif (!Is.empty(options?.timeoutMs)) {\n\t\t\tGuards.integer(Mutex.CLASS_NAME, nameof(options.timeoutMs), options.timeoutMs);\n\t\t\tif (options.timeoutMs < 0) {\n\t\t\t\tthrow new GeneralError(Mutex.CLASS_NAME, \"invalidTimeout\", {\n\t\t\t\t\ttimeoutMs: options.timeoutMs\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tconst timeoutMs = options?.timeoutMs ?? Mutex.getDefaultTimeoutMs();\n\t\tconst throwOnTimeout = options?.throwOnTimeout ?? false;\n\t\tconst deadline = Date.now() + timeoutMs;\n\n\t\t// getOrFetchLock may block once per key on worker threads to negotiate the\n\t\t// shared buffer with the main thread; that one-time fetch is acceptable here.\n\t\tconst lock = await Mutex.getOrFetchLock(key, deadline);\n\n\t\tfor (;;) {\n\t\t\t// Atomically swap 0 → 1; if the previous value was 0 we acquired the lock.\n\t\t\tconst previous = Atomics.compareExchange(lock, 0, 0, 1);\n\t\t\tif (previous === 0) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\t// Otherwise, the lock is held by someone else. Check if we've already timed out.\n\t\t\tconst remaining = deadline - Date.now();\n\t\t\tif (remaining <= 0) {\n\t\t\t\tif (throwOnTimeout) {\n\t\t\t\t\tthrow new GeneralError(Mutex.CLASS_NAME, \"lockTimeout\", { key, timeoutMs });\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t// Suspend without blocking the event loop so the lock holder's async\n\t\t\t// continuations can run and eventually call unlock().\n\t\t\tconst waitResult = Atomics.waitAsync(lock, 0, 1, remaining);\n\t\t\tconst outcome = waitResult.async ? await waitResult.value : waitResult.value;\n\t\t\tif (outcome === \"timed-out\") {\n\t\t\t\tif (throwOnTimeout) {\n\t\t\t\t\tthrow new GeneralError(Mutex.CLASS_NAME, \"lockTimeout\", { key, timeoutMs });\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Releases the lock for the given key.\n\t * @param key The key to unlock.\n\t * @throws GeneralError if the key is invalid or the lock is not currently held.\n\t */\n\tpublic static unlock(key: string): void {\n\t\tGuards.stringValue(Mutex.CLASS_NAME, nameof(key), key);\n\n\t\tconst locks = Mutex.getLocks();\n\t\tconst lock = locks[key];\n\t\tif (Is.empty(lock)) {\n\t\t\tthrow new GeneralError(Mutex.CLASS_NAME, \"lockNotFound\", { key });\n\t\t}\n\n\t\tconst previous = Atomics.compareExchange(lock, 0, 1, 0);\n\t\tif (previous !== 1) {\n\t\t\tthrow new GeneralError(Mutex.CLASS_NAME, \"lockAlreadyReleased\", { key });\n\t\t}\n\n\t\tAtomics.notify(lock, 0, 1);\n\t}\n\n\t/**\n\t * Inspect a message received from a worker and, if it is a Mutex buffer-fetch request,\n\t * respond to it synchronously. Call from the main thread's worker message handler.\n\t * @param msg The raw message received from the worker.\n\t * @returns True if the message was a Mutex protocol message and was handled, false otherwise.\n\t */\n\tpublic static handleWorkerMessage(msg: unknown): boolean {\n\t\tif (!Is.object<IMutexWorkerMessage>(msg) || msg.type !== MutexMessageTypes.GetBuffer) {\n\t\t\treturn false;\n\t\t}\n\n\t\tGuards.stringValue(Mutex.CLASS_NAME, nameof(msg.key), msg.key);\n\t\tGuards.object<SharedArrayBuffer>(Mutex.CLASS_NAME, nameof(msg.signal), msg.signal);\n\t\tGuards.object<MessagePort>(Mutex.CLASS_NAME, nameof(msg.port), msg.port);\n\n\t\tconst locks = Mutex.getLocks();\n\t\tlocks[msg.key] ??= new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));\n\t\t// Send the buffer before updating the signal so it is guaranteed to be in\n\t\t// port1's receive queue when Atomics.wait returns on the worker side.\n\t\tmsg.port.postMessage({ buffer: locks[msg.key].buffer });\n\t\t// Set signal[0] = 1 before notifying. If the OS scheduled the main thread\n\t\t// to process this request before the worker reached Atomics.wait, the notify\n\t\t// would fire with no waiters (lost wakeup). Setting the value first means\n\t\t// Atomics.wait(signal, 0, 0) sees a non-zero value and returns \"not-equal\"\n\t\t// immediately instead of blocking indefinitely.\n\t\tconst signalArr = new Int32Array(msg.signal);\n\t\tAtomics.store(signalArr, 0, 1);\n\t\tAtomics.notify(signalArr, 0, 1);\n\t\tmsg.port.close();\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns the Int32Array for the given key, fetching it from the main thread if this\n\t * is a worker thread and the key is not yet in the local cache.\n\t * @param key The lock key.\n\t * @param deadline The deadline to use while waiting for the main thread to provide the lock.\n\t * @returns The Int32Array backed by a SharedArrayBuffer for this key.\n\t * @internal\n\t */\n\tprivate static async getOrFetchLock(key: string, deadline: number): Promise<Int32Array> {\n\t\tconst locks = Mutex.getLocks();\n\t\tif (!Is.empty(locks[key])) {\n\t\t\treturn locks[key];\n\t\t}\n\n\t\tconst wt = await Mutex.loadWorkerThreads();\n\n\t\t// Re-check after the await: another coroutine that was also waiting on\n\t\t// loadWorkerThreads() may have allocated the buffer while we yielded.\n\t\tif (!Is.empty(locks[key])) {\n\t\t\treturn locks[key];\n\t\t}\n\n\t\tif (Is.empty(wt) || wt.isMainThread) {\n\t\t\t// Main thread, fork-mode process, or browser: own the registry entry.\n\t\t\tlocks[key] = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));\n\t\t\treturn locks[key];\n\t\t}\n\n\t\t// Worker thread: synchronously request the SharedArrayBuffer from the main thread.\n\t\t// Mutex.handleWorkerMessage(msg) must be called on the main thread's worker message handler.\n\t\tif (Is.empty(wt.parentPort)) {\n\t\t\tthrow new GeneralError(Mutex.CLASS_NAME, \"bufferFetchFailed\", { key });\n\t\t}\n\n\t\tconst { port1, port2 } = new wt.MessageChannel();\n\t\tconst signal = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));\n\n\t\tconst msg: IMutexWorkerMessage = {\n\t\t\ttype: MutexMessageTypes.GetBuffer,\n\t\t\tkey,\n\t\t\tsignal: signal.buffer,\n\t\t\tport: port2\n\t\t};\n\n\t\twt.parentPort.postMessage(msg, [port2]);\n\n\t\ttry {\n\t\t\t// Block until the main thread signals readiness. The main thread sets\n\t\t\t// signal[0] = 1 before calling notify, so if the notify fired before this\n\t\t\t// wait call (lost-wakeup scenario with concurrent workers), Atomics.wait\n\t\t\t// sees a non-zero value and returns \"not-equal\" immediately.\n\t\t\t// Either way the port message is already in port1's receive queue.\n\t\t\t// Use the lock deadline so the buffer fetch is bounded by the same timeout.\n\t\t\tconst waitResult = Atomics.wait(signal, 0, 0, Math.max(0, deadline - Date.now()));\n\t\t\tif (waitResult === \"timed-out\") {\n\t\t\t\tthrow new GeneralError(Mutex.CLASS_NAME, \"bufferFetchFailed\", { key });\n\t\t\t}\n\n\t\t\tconst response = wt.receiveMessageOnPort(port1) as {\n\t\t\t\tmessage: { buffer: SharedArrayBuffer };\n\t\t\t} | null;\n\n\t\t\tif (Is.empty(response)) {\n\t\t\t\tthrow new GeneralError(Mutex.CLASS_NAME, \"bufferFetchFailed\", { key });\n\t\t\t}\n\n\t\t\tlocks[key] = new Int32Array(response.message.buffer);\n\t\t\treturn locks[key];\n\t\t} finally {\n\t\t\tport1.close();\n\t\t}\n\t}\n\n\t/**\n\t * Get the shared locks map, creating it if it does not exist.\n\t * @returns The shared locks map.\n\t * @internal\n\t */\n\tprivate static getLocks(): { [key: string]: Int32Array } {\n\t\treturn SharedStore.get<{ [key: string]: Int32Array }>(Mutex._LOCKS_KEY, () => ({}));\n\t}\n\n\t/**\n\t * Lazily loads node:worker_threads, returning null in environments where it is unavailable.\n\t * @returns The worker_threads module or null.\n\t * @internal\n\t */\n\t// false positive: this is a type not an actual import\n\t// eslint-disable-next-line @typescript-eslint/consistent-type-imports\n\tprivate static async loadWorkerThreads(): Promise<typeof import(\"node:worker_threads\") | null> {\n\t\tif (Mutex._workerThreadsModule === undefined) {\n\t\t\ttry {\n\t\t\t\tMutex._workerThreadsModule = await import(\"node:worker_threads\");\n\t\t\t} catch {\n\t\t\t\tMutex._workerThreadsModule = null;\n\t\t\t}\n\t\t}\n\t\treturn Mutex._workerThreadsModule;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"mutex.js","sourceRoot":"","sources":["../../../src/utils/mutex.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,EAAE,EAAE,MAAM,SAAS,CAAC;AAC7B,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAGzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AAEnE;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,OAAO,KAAK;IACjB;;OAEG;IACI,MAAM,CAAU,UAAU,WAA2B;IAE5D;;;OAGG;IACK,MAAM,CAAU,UAAU,GAAG,YAAY,CAAC;IAElD;;;OAGG;IACK,MAAM,CAAU,oBAAoB,GAAG,uBAAuB,CAAC;IAEvE;;;OAGG;IACK,MAAM,CAAU,YAAY,GAAG,cAAc,CAAC;IAEtD;;;OAGG;IACK,MAAM,CAAU,aAAa,GAAG,eAAe,CAAC;IAExD;;;;;OAKG;IACK,MAAM,CAAU,iBAAiB,GAAG,GAAG,CAAC;IAEhD;;;OAGG;IACH,sDAAsD;IACtD,sEAAsE;IAC9D,MAAM,CAAC,oBAAoB,CAA0D;IAE7F;;;OAGG;IACI,MAAM,CAAC,mBAAmB;QAChC,OAAO,WAAW,CAAC,GAAG,CAAS,KAAK,CAAC,oBAAoB,CAAC,IAAI,IAAI,CAAC;IACpE,CAAC;IAED;;;;OAIG;IACI,MAAM,CAAC,mBAAmB,CAAC,SAAiB;QAClD,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,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AI,KAAK,CAAC,oBAAoB,KAAK,SAAS,EAAE,CAAC;YAC9C,IAAI,CAAC;gBACJ,KAAK,CAAC,oBAAoB,GAAG,MAAM,MAAM,CAAC,qBAAqB,CAAC,CAAC;YAClE,CAAC;YAAC,MAAM,CAAC;gBACR,KAAK,CAAC,oBAAoB,GAAG,IAAI,CAAC;YACnC,CAAC;QACF,CAAC;QACD,OAAO,KAAK,CAAC,oBAAoB,CAAC;IACnC,CAAC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { MessagePort } from \"node:worker_threads\";\nimport { nameof } from \"@twin.org/nameof\";\nimport { Guards } from \"./guards.js\";\nimport { Is } from \"./is.js\";\nimport { SharedStore } from \"./sharedStore.js\";\nimport { GeneralError } from \"../errors/generalError.js\";\nimport type { IMutexWaiter } from \"../models/IMutexWaiter.js\";\nimport type { IMutexWorkerMessage } from \"../models/IMutexWorkerMessage.js\";\nimport { MutexMessageTypes } from \"../models/mutexMessageTypes.js\";\n\n/**\n * A cross-thread mutex built on Atomics and SharedArrayBuffer.\n *\n * When isMainThread is true (main thread or fork-mode child process) the class acts as\n * the authoritative registry: it creates a SharedArrayBuffer-backed Int32Array for each\n * key on first use and never discards it, because worker threads may hold references to\n * the same underlying memory.\n *\n * When isMainThread is false (a true worker thread) the class synchronously negotiates\n * the shared buffer with the main thread on first use of each key, then caches it locally.\n * The main thread must call Mutex.handleWorkerMessage(msg) from its worker message handler\n * before that worker first calls Mutex.lock().\n *\n * Callers on the same thread are served in the order they arrived. Each key has a FIFO\n * queue of waiters, unlock() hands the lock directly to the waiter at the front, and a new\n * caller only takes the lock outright when that queue is empty. Without this a caller that\n * arrives while a waiter is being woken can take the lock first, which lets a busy key\n * starve a waiter until its timeout elapses. Threads still contend with each other for the\n * shared lock, so the ordering guarantee is per thread rather than global.\n *\n * The lock is not re-entrant: a thread that already holds a key and calls lock() again on\n * the same key will block until the timeout elapses.\n */\nexport class Mutex {\n\t/**\n\t * Runtime name for the class.\n\t */\n\tpublic static readonly CLASS_NAME: string = nameof<Mutex>();\n\n\t/**\n\t * SharedStore key for the per-thread sparse map from lock key strings to Int32Arrays.\n\t * @internal\n\t */\n\tprivate static readonly _LOCKS_KEY = \"mutexLocks\";\n\n\t/**\n\t * SharedStore key for the default timeout in milliseconds.\n\t * @internal\n\t */\n\tprivate static readonly _DEFAULT_TIMEOUT_KEY = \"mutexDefaultTimeoutMs\";\n\n\t/**\n\t * SharedStore key for the per-thread map from lock key strings to FIFO waiter queues.\n\t * @internal\n\t */\n\tprivate static readonly _WAITERS_KEY = \"mutexWaiters\";\n\n\t/**\n\t * SharedStore key for the per-thread map from lock key strings to the running watch task.\n\t * @internal\n\t */\n\tprivate static readonly _WATCHERS_KEY = \"mutexWatchers\";\n\n\t/**\n\t * How long the watch task waits on the shared lock before re-reading the queue, in\n\t * milliseconds. It only bounds how quickly the task notices that the queue has drained,\n\t * releases from other threads wake it immediately.\n\t * @internal\n\t */\n\tprivate static readonly _WATCH_TIMEOUT_MS = 250;\n\n\t/**\n\t * Cached reference to the node:worker_threads module, null if unavailable (browser).\n\t * @internal\n\t */\n\t// false positive: this is a type not an actual import\n\t// eslint-disable-next-line @typescript-eslint/consistent-type-imports\n\tprivate static _workerThreadsModule: typeof import(\"node:worker_threads\") | null | undefined;\n\n\t/**\n\t * Gets the default timeout in milliseconds for lock acquisition.\n\t * @returns The default timeout in milliseconds.\n\t */\n\tpublic static getDefaultTimeoutMs(): number {\n\t\treturn SharedStore.get<number>(Mutex._DEFAULT_TIMEOUT_KEY) ?? 5000;\n\t}\n\n\t/**\n\t * Sets the default timeout in milliseconds for lock acquisition.\n\t * @param timeoutMs The default timeout in milliseconds.\n\t * @throws GeneralError if timeoutMs is not a non-negative integer.\n\t */\n\tpublic static setDefaultTimeoutMs(timeoutMs: number): void {\n\t\tGuards.integer(Mutex.CLASS_NAME, nameof(timeoutMs), timeoutMs);\n\t\tif (timeoutMs < 0) {\n\t\t\tthrow new GeneralError(Mutex.CLASS_NAME, \"invalidTimeout\", { timeoutMs });\n\t\t}\n\t\tSharedStore.set(Mutex._DEFAULT_TIMEOUT_KEY, timeoutMs);\n\t}\n\n\t/**\n\t * Acquires a lock for the given key without blocking the event loop. If the lock is already\n\t * held, it suspends the current async task until the lock is released or the timeout is reached.\n\t * Use this in async single-threaded contexts (e.g. the main thread or a Fastify route handler)\n\t * where calling the synchronous lock() would freeze the event loop and deadlock.\n\t * Callers on the same thread are served in the order they arrived, so a contended key\n\t * cannot starve an earlier caller.\n\t * The lock is not re-entrant: if the same context holds the key and calls lockAsync() again on\n\t * the same key, it will suspend until the timeout elapses.\n\t * @param key The key to lock on.\n\t * @param options Lock options.\n\t * @param options.timeoutMs The maximum time to wait for the lock in milliseconds, defaults to getDefaultTimeoutMs().\n\t * @param options.throwOnTimeout Whether to throw an error if the lock could not be acquired within the timeout, default is false.\n\t * @returns True if the lock was acquired, false if it timed out and throwOnTimeout is false.\n\t * @throws GeneralError if the key is invalid or if the lock could not be acquired within the timeout and throwOnTimeout is true.\n\t */\n\tpublic static async lock(\n\t\tkey: string,\n\t\toptions?: { timeoutMs?: number; throwOnTimeout?: boolean }\n\t): Promise<boolean> {\n\t\tGuards.stringValue(Mutex.CLASS_NAME, nameof(key), key);\n\t\tif (!Is.empty(options?.timeoutMs)) {\n\t\t\tGuards.integer(Mutex.CLASS_NAME, nameof(options.timeoutMs), options.timeoutMs);\n\t\t\tif (options.timeoutMs < 0) {\n\t\t\t\tthrow new GeneralError(Mutex.CLASS_NAME, \"invalidTimeout\", {\n\t\t\t\t\ttimeoutMs: options.timeoutMs\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tconst timeoutMs = options?.timeoutMs ?? Mutex.getDefaultTimeoutMs();\n\t\tconst throwOnTimeout = options?.throwOnTimeout ?? false;\n\t\tconst deadline = Date.now() + timeoutMs;\n\n\t\t// getOrFetchLock may block once per key on worker threads to negotiate the\n\t\t// shared buffer with the main thread; that one-time fetch is acceptable here.\n\t\tconst lock = await Mutex.getOrFetchLock(key, deadline);\n\t\tconst queue = Mutex.getQueue(key);\n\n\t\t// Atomically swap 0 → 1; if the previous value was 0 we acquired the lock. Only take\n\t\t// it outright when nothing on this thread is already queued, otherwise this caller\n\t\t// would barge in front of waiters that arrived earlier.\n\t\tif (queue.length === 0 && Atomics.compareExchange(lock, 0, 0, 1) === 0) {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (deadline - Date.now() <= 0) {\n\t\t\tif (throwOnTimeout) {\n\t\t\t\tthrow new GeneralError(Mutex.CLASS_NAME, \"lockTimeout\", { key, timeoutMs });\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\t\t// Join the back of the queue and suspend without blocking the event loop, so the\n\t\t// holder's async continuations can run and eventually call unlock(). The lock is\n\t\t// handed over either by unlock() on this thread or by the watch task below when\n\t\t// another thread releases it.\n\t\tconst waiter: IMutexWaiter = { settled: false };\n\t\tconst granted = new Promise<boolean>(resolve => {\n\t\t\twaiter.resolve = resolve;\n\t\t});\n\t\tqueue.push(waiter);\n\n\t\t// The deadline is enforced by a timer rather than only by the atomic wait, so a\n\t\t// congested event loop cannot stretch the wait well beyond the requested timeout.\n\t\twaiter.timer = setTimeout(() => Mutex.settleWaiter(key, waiter, false), deadline - Date.now());\n\n\t\tMutex.startWatching(key, lock);\n\n\t\tif (await granted) {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (throwOnTimeout) {\n\t\t\tthrow new GeneralError(Mutex.CLASS_NAME, \"lockTimeout\", { key, timeoutMs });\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Releases the lock for the given key.\n\t * @param key The key to unlock.\n\t * @throws GeneralError if the key is invalid or the lock is not currently held.\n\t */\n\tpublic static unlock(key: string): void {\n\t\tGuards.stringValue(Mutex.CLASS_NAME, nameof(key), key);\n\n\t\tconst locks = Mutex.getLocks();\n\t\tconst lock = locks[key];\n\t\tif (Is.empty(lock)) {\n\t\t\tthrow new GeneralError(Mutex.CLASS_NAME, \"lockNotFound\", { key });\n\t\t}\n\n\t\tconst previous = Atomics.compareExchange(lock, 0, 1, 0);\n\t\tif (previous !== 1) {\n\t\t\tthrow new GeneralError(Mutex.CLASS_NAME, \"lockAlreadyReleased\", { key });\n\t\t}\n\n\t\t// Hand the lock straight to the caller at the front of this thread's queue. Nothing\n\t\t// else on this thread can run between the release above and the re-acquire below, so\n\t\t// no later caller can see the released state and take it first.\n\t\tconst next = Mutex.getWaiters()[key]?.[0];\n\t\tif (!Is.empty(next) && Atomics.compareExchange(lock, 0, 0, 1) === 0) {\n\t\t\tMutex.settleWaiter(key, next, true);\n\t\t\treturn;\n\t\t}\n\n\t\tAtomics.notify(lock, 0, 1);\n\t}\n\n\t/**\n\t * Inspect a message received from a worker and, if it is a Mutex buffer-fetch request,\n\t * respond to it synchronously. Call from the main thread's worker message handler.\n\t * @param msg The raw message received from the worker.\n\t * @returns True if the message was a Mutex protocol message and was handled, false otherwise.\n\t */\n\tpublic static handleWorkerMessage(msg: unknown): boolean {\n\t\tif (!Is.object<IMutexWorkerMessage>(msg) || msg.type !== MutexMessageTypes.GetBuffer) {\n\t\t\treturn false;\n\t\t}\n\n\t\tGuards.stringValue(Mutex.CLASS_NAME, nameof(msg.key), msg.key);\n\t\tGuards.object<SharedArrayBuffer>(Mutex.CLASS_NAME, nameof(msg.signal), msg.signal);\n\t\tGuards.object<MessagePort>(Mutex.CLASS_NAME, nameof(msg.port), msg.port);\n\n\t\tconst locks = Mutex.getLocks();\n\t\tlocks[msg.key] ??= new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));\n\t\t// Send the buffer before updating the signal so it is guaranteed to be in\n\t\t// port1's receive queue when Atomics.wait returns on the worker side.\n\t\tmsg.port.postMessage({ buffer: locks[msg.key].buffer });\n\t\t// Set signal[0] = 1 before notifying. If the OS scheduled the main thread\n\t\t// to process this request before the worker reached Atomics.wait, the notify\n\t\t// would fire with no waiters (lost wakeup). Setting the value first means\n\t\t// Atomics.wait(signal, 0, 0) sees a non-zero value and returns \"not-equal\"\n\t\t// immediately instead of blocking indefinitely.\n\t\tconst signalArr = new Int32Array(msg.signal);\n\t\tAtomics.store(signalArr, 0, 1);\n\t\tAtomics.notify(signalArr, 0, 1);\n\t\tmsg.port.close();\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Returns the Int32Array for the given key, fetching it from the main thread if this\n\t * is a worker thread and the key is not yet in the local cache.\n\t * @param key The lock key.\n\t * @param deadline The deadline to use while waiting for the main thread to provide the lock.\n\t * @returns The Int32Array backed by a SharedArrayBuffer for this key.\n\t * @internal\n\t */\n\tprivate static async getOrFetchLock(key: string, deadline: number): Promise<Int32Array> {\n\t\tconst locks = Mutex.getLocks();\n\t\tif (!Is.empty(locks[key])) {\n\t\t\treturn locks[key];\n\t\t}\n\n\t\tconst wt = await Mutex.loadWorkerThreads();\n\n\t\t// Re-check after the await: another coroutine that was also waiting on\n\t\t// loadWorkerThreads() may have allocated the buffer while we yielded.\n\t\tif (!Is.empty(locks[key])) {\n\t\t\treturn locks[key];\n\t\t}\n\n\t\tif (Is.empty(wt) || wt.isMainThread) {\n\t\t\t// Main thread, fork-mode process, or browser: own the registry entry.\n\t\t\tlocks[key] = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));\n\t\t\treturn locks[key];\n\t\t}\n\n\t\t// Worker thread: synchronously request the SharedArrayBuffer from the main thread.\n\t\t// Mutex.handleWorkerMessage(msg) must be called on the main thread's worker message handler.\n\t\tif (Is.empty(wt.parentPort)) {\n\t\t\tthrow new GeneralError(Mutex.CLASS_NAME, \"bufferFetchFailed\", { key });\n\t\t}\n\n\t\tconst { port1, port2 } = new wt.MessageChannel();\n\t\tconst signal = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));\n\n\t\tconst msg: IMutexWorkerMessage = {\n\t\t\ttype: MutexMessageTypes.GetBuffer,\n\t\t\tkey,\n\t\t\tsignal: signal.buffer,\n\t\t\tport: port2\n\t\t};\n\n\t\twt.parentPort.postMessage(msg, [port2]);\n\n\t\ttry {\n\t\t\t// Block until the main thread signals readiness. The main thread sets\n\t\t\t// signal[0] = 1 before calling notify, so if the notify fired before this\n\t\t\t// wait call (lost-wakeup scenario with concurrent workers), Atomics.wait\n\t\t\t// sees a non-zero value and returns \"not-equal\" immediately.\n\t\t\t// Either way the port message is already in port1's receive queue.\n\t\t\t// Use the lock deadline so the buffer fetch is bounded by the same timeout.\n\t\t\tconst waitResult = Atomics.wait(signal, 0, 0, Math.max(0, deadline - Date.now()));\n\t\t\tif (waitResult === \"timed-out\") {\n\t\t\t\tthrow new GeneralError(Mutex.CLASS_NAME, \"bufferFetchFailed\", { key });\n\t\t\t}\n\n\t\t\tconst response = wt.receiveMessageOnPort(port1) as {\n\t\t\t\tmessage: { buffer: SharedArrayBuffer };\n\t\t\t} | null;\n\n\t\t\tif (Is.empty(response)) {\n\t\t\t\tthrow new GeneralError(Mutex.CLASS_NAME, \"bufferFetchFailed\", { key });\n\t\t\t}\n\n\t\t\tlocks[key] = new Int32Array(response.message.buffer);\n\t\t\treturn locks[key];\n\t\t} finally {\n\t\t\tport1.close();\n\t\t}\n\t}\n\n\t/**\n\t * Settle a queued waiter, remove it from the queue and resume its caller.\n\t * @param key The lock key.\n\t * @param waiter The waiter to settle.\n\t * @param granted True when the waiter has been handed the lock and now owns it.\n\t * @internal\n\t */\n\tprivate static settleWaiter(key: string, waiter: IMutexWaiter, granted: boolean): void {\n\t\tif (waiter.settled) {\n\t\t\treturn;\n\t\t}\n\t\twaiter.settled = true;\n\n\t\tif (!Is.empty(waiter.timer)) {\n\t\t\tclearTimeout(waiter.timer);\n\t\t\twaiter.timer = undefined;\n\t\t}\n\n\t\tconst queue = Mutex.getWaiters()[key];\n\t\tconst index = queue?.indexOf(waiter) ?? -1;\n\t\tif (index >= 0) {\n\t\t\tqueue.splice(index, 1);\n\t\t}\n\n\t\twaiter.resolve?.(granted);\n\t}\n\n\t/**\n\t * Start the watch task for a key if one is not already running.\n\t * @param key The lock key.\n\t * @param lock The shared lock for the key.\n\t * @internal\n\t */\n\tprivate static startWatching(key: string, lock: Int32Array): void {\n\t\tconst watchers = Mutex.getWatchers();\n\t\twatchers[key] ??= Mutex.runWatcher(key, lock);\n\t}\n\n\t/**\n\t * Run the watch task for a key and clear its registry entry once it ends. The entry is\n\t * only cleared after an await, so it cannot be removed before startWatching has recorded\n\t * it, even when the task itself completes without suspending.\n\t * @param key The lock key.\n\t * @param lock The shared lock for the key.\n\t * @returns A promise that resolves when the task ends.\n\t * @internal\n\t */\n\tprivate static async runWatcher(key: string, lock: Int32Array): Promise<void> {\n\t\ttry {\n\t\t\tawait Mutex.watchQueue(key, lock);\n\t\t} finally {\n\t\t\tdelete Mutex.getWatchers()[key];\n\t\t}\n\t}\n\n\t/**\n\t * Watch the shared lock for a key and hand it to the waiter at the front of the queue.\n\t * This covers releases from other threads, a release on this thread hands the lock over\n\t * directly in unlock(). The task ends once the queue for the key has drained.\n\t * @param key The lock key.\n\t * @param lock The shared lock for the key.\n\t * @returns A promise that resolves when the task ends.\n\t * @internal\n\t */\n\tprivate static async watchQueue(key: string, lock: Int32Array): Promise<void> {\n\t\tfor (;;) {\n\t\t\t// Re-read the front of the queue on every pass, waiters that reached their\n\t\t\t// deadline have already removed themselves.\n\t\t\tconst head = Mutex.getWaiters()[key]?.[0];\n\t\t\tif (Is.empty(head)) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (Atomics.compareExchange(lock, 0, 0, 1) === 0) {\n\t\t\t\tMutex.settleWaiter(key, head, true);\n\t\t\t} else {\n\t\t\t\tconst waitResult = Atomics.waitAsync(lock, 0, 1, Mutex._WATCH_TIMEOUT_MS);\n\t\t\t\tif (waitResult.async) {\n\t\t\t\t\tawait waitResult.value;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Get the FIFO waiter queue for a key, creating it if it does not exist.\n\t * @param key The lock key.\n\t * @returns The waiter queue for the key.\n\t * @internal\n\t */\n\tprivate static getQueue(key: string): IMutexWaiter[] {\n\t\tconst waiters = Mutex.getWaiters();\n\t\twaiters[key] ??= [];\n\t\treturn waiters[key];\n\t}\n\n\t/**\n\t * Get the shared waiter queues map, creating it if it does not exist.\n\t * @returns The shared waiter queues map.\n\t * @internal\n\t */\n\tprivate static getWaiters(): { [key: string]: IMutexWaiter[] } {\n\t\treturn SharedStore.get<{ [key: string]: IMutexWaiter[] }>(Mutex._WAITERS_KEY, () => ({}));\n\t}\n\n\t/**\n\t * Get the shared watch tasks map, creating it if it does not exist.\n\t * @returns The shared watch tasks map.\n\t * @internal\n\t */\n\tprivate static getWatchers(): { [key: string]: Promise<void> } {\n\t\treturn SharedStore.get<{ [key: string]: Promise<void> }>(Mutex._WATCHERS_KEY, () => ({}));\n\t}\n\n\t/**\n\t * Get the shared locks map, creating it if it does not exist.\n\t * @returns The shared locks map.\n\t * @internal\n\t */\n\tprivate static getLocks(): { [key: string]: Int32Array } {\n\t\treturn SharedStore.get<{ [key: string]: Int32Array }>(Mutex._LOCKS_KEY, () => ({}));\n\t}\n\n\t/**\n\t * Lazily loads node:worker_threads, returning null in environments where it is unavailable.\n\t * @returns The worker_threads module or null.\n\t * @internal\n\t */\n\t// false positive: this is a type not an actual import\n\t// eslint-disable-next-line @typescript-eslint/consistent-type-imports\n\tprivate static async loadWorkerThreads(): Promise<typeof import(\"node:worker_threads\") | null> {\n\t\tif (Mutex._workerThreadsModule === undefined) {\n\t\t\ttry {\n\t\t\t\tMutex._workerThreadsModule = await import(\"node:worker_threads\");\n\t\t\t} catch {\n\t\t\t\tMutex._workerThreadsModule = null;\n\t\t\t}\n\t\t}\n\t\treturn Mutex._workerThreadsModule;\n\t}\n}\n"]}
|
package/dist/types/index.d.ts
CHANGED
|
@@ -39,6 +39,7 @@ export * from "./models/ILabelledValue.js";
|
|
|
39
39
|
export * from "./models/ILocale.js";
|
|
40
40
|
export * from "./models/ILocaleDictionary.js";
|
|
41
41
|
export * from "./models/ILocalesIndex.js";
|
|
42
|
+
export * from "./models/IMutexWaiter.js";
|
|
42
43
|
export * from "./models/IMutexWorkerMessage.js";
|
|
43
44
|
export * from "./models/IPatchOperation.js";
|
|
44
45
|
export * from "./models/ISharedObjectBufferOptions.js";
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A caller queued on a mutex key, waiting to be handed the lock.
|
|
3
|
+
*/
|
|
4
|
+
export interface IMutexWaiter {
|
|
5
|
+
/**
|
|
6
|
+
* Has the waiter already been granted the lock or given up waiting.
|
|
7
|
+
*/
|
|
8
|
+
settled: boolean;
|
|
9
|
+
/**
|
|
10
|
+
* Resolves the queued caller, true when it now owns the lock.
|
|
11
|
+
*/
|
|
12
|
+
resolve?: (granted: boolean) => void;
|
|
13
|
+
/**
|
|
14
|
+
* Timer which enforces the waiter's deadline.
|
|
15
|
+
*/
|
|
16
|
+
timer?: ReturnType<typeof setTimeout>;
|
|
17
|
+
}
|
|
@@ -11,6 +11,13 @@
|
|
|
11
11
|
* The main thread must call Mutex.handleWorkerMessage(msg) from its worker message handler
|
|
12
12
|
* before that worker first calls Mutex.lock().
|
|
13
13
|
*
|
|
14
|
+
* Callers on the same thread are served in the order they arrived. Each key has a FIFO
|
|
15
|
+
* queue of waiters, unlock() hands the lock directly to the waiter at the front, and a new
|
|
16
|
+
* caller only takes the lock outright when that queue is empty. Without this a caller that
|
|
17
|
+
* arrives while a waiter is being woken can take the lock first, which lets a busy key
|
|
18
|
+
* starve a waiter until its timeout elapses. Threads still contend with each other for the
|
|
19
|
+
* shared lock, so the ordering guarantee is per thread rather than global.
|
|
20
|
+
*
|
|
14
21
|
* The lock is not re-entrant: a thread that already holds a key and calls lock() again on
|
|
15
22
|
* the same key will block until the timeout elapses.
|
|
16
23
|
*/
|
|
@@ -35,6 +42,8 @@ export declare class Mutex {
|
|
|
35
42
|
* held, it suspends the current async task until the lock is released or the timeout is reached.
|
|
36
43
|
* Use this in async single-threaded contexts (e.g. the main thread or a Fastify route handler)
|
|
37
44
|
* where calling the synchronous lock() would freeze the event loop and deadlock.
|
|
45
|
+
* Callers on the same thread are served in the order they arrived, so a contended key
|
|
46
|
+
* cannot starve an earlier caller.
|
|
38
47
|
* The lock is not re-entrant: if the same context holds the key and calls lockAsync() again on
|
|
39
48
|
* the same key, it will suspend until the timeout elapses.
|
|
40
49
|
* @param key The key to lock on.
|
package/docs/changelog.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.9.3-next.5](https://github.com/iotaledger/twin-framework/compare/core-v0.9.3-next.4...core-v0.9.3-next.5) (2026-09-04)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### Bug Fixes
|
|
7
|
+
|
|
8
|
+
* mutex ordering ([#476](https://github.com/iotaledger/twin-framework/issues/476)) ([45ed50a](https://github.com/iotaledger/twin-framework/commit/45ed50aab9f40b4d94921926e13deb37bcac8a70))
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
### Dependencies
|
|
12
|
+
|
|
13
|
+
* The following workspace dependencies were updated
|
|
14
|
+
* dependencies
|
|
15
|
+
* @twin.org/nameof bumped from 0.9.3-next.4 to 0.9.3-next.5
|
|
16
|
+
* devDependencies
|
|
17
|
+
* @twin.org/nameof-transformer bumped from 0.9.3-next.4 to 0.9.3-next.5
|
|
18
|
+
* @twin.org/nameof-vitest-plugin bumped from 0.9.3-next.4 to 0.9.3-next.5
|
|
19
|
+
|
|
3
20
|
## [0.9.3-next.4](https://github.com/iotaledger/twin-framework/compare/core-v0.9.3-next.3...core-v0.9.3-next.4) (2026-09-04)
|
|
4
21
|
|
|
5
22
|
|
|
@@ -12,6 +12,13 @@ the shared buffer with the main thread on first use of each key, then caches it
|
|
|
12
12
|
The main thread must call Mutex.handleWorkerMessage(msg) from its worker message handler
|
|
13
13
|
before that worker first calls Mutex.lock().
|
|
14
14
|
|
|
15
|
+
Callers on the same thread are served in the order they arrived. Each key has a FIFO
|
|
16
|
+
queue of waiters, unlock() hands the lock directly to the waiter at the front, and a new
|
|
17
|
+
caller only takes the lock outright when that queue is empty. Without this a caller that
|
|
18
|
+
arrives while a waiter is being woken can take the lock first, which lets a busy key
|
|
19
|
+
starve a waiter until its timeout elapses. Threads still contend with each other for the
|
|
20
|
+
shared lock, so the ordering guarantee is per thread rather than global.
|
|
21
|
+
|
|
15
22
|
The lock is not re-entrant: a thread that already holds a key and calls lock() again on
|
|
16
23
|
the same key will block until the timeout elapses.
|
|
17
24
|
|
|
@@ -81,6 +88,8 @@ Acquires a lock for the given key without blocking the event loop. If the lock i
|
|
|
81
88
|
held, it suspends the current async task until the lock is released or the timeout is reached.
|
|
82
89
|
Use this in async single-threaded contexts (e.g. the main thread or a Fastify route handler)
|
|
83
90
|
where calling the synchronous lock() would freeze the event loop and deadlock.
|
|
91
|
+
Callers on the same thread are served in the order they arrived, so a contended key
|
|
92
|
+
cannot starve an earlier caller.
|
|
84
93
|
The lock is not re-entrant: if the same context holds the key and calls lockAsync() again on
|
|
85
94
|
the same key, it will suspend until the timeout elapses.
|
|
86
95
|
|
package/docs/reference/index.md
CHANGED
|
@@ -59,6 +59,7 @@
|
|
|
59
59
|
- [ILocale](interfaces/ILocale.md)
|
|
60
60
|
- [ILocaleDictionary](interfaces/ILocaleDictionary.md)
|
|
61
61
|
- [ILocalesIndex](interfaces/ILocalesIndex.md)
|
|
62
|
+
- [IMutexWaiter](interfaces/IMutexWaiter.md)
|
|
62
63
|
- [IMutexWorkerMessage](interfaces/IMutexWorkerMessage.md)
|
|
63
64
|
- [IPatchOperation](interfaces/IPatchOperation.md)
|
|
64
65
|
- [ISharedObjectBufferOptions](interfaces/ISharedObjectBufferOptions.md)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# Interface: IMutexWaiter
|
|
2
|
+
|
|
3
|
+
A caller queued on a mutex key, waiting to be handed the lock.
|
|
4
|
+
|
|
5
|
+
## Properties
|
|
6
|
+
|
|
7
|
+
### settled {#settled}
|
|
8
|
+
|
|
9
|
+
> **settled**: `boolean`
|
|
10
|
+
|
|
11
|
+
Has the waiter already been granted the lock or given up waiting.
|
|
12
|
+
|
|
13
|
+
***
|
|
14
|
+
|
|
15
|
+
### resolve? {#resolve}
|
|
16
|
+
|
|
17
|
+
> `optional` **resolve?**: (`granted`) => `void`
|
|
18
|
+
|
|
19
|
+
Resolves the queued caller, true when it now owns the lock.
|
|
20
|
+
|
|
21
|
+
#### Parameters
|
|
22
|
+
|
|
23
|
+
##### granted
|
|
24
|
+
|
|
25
|
+
`boolean`
|
|
26
|
+
|
|
27
|
+
#### Returns
|
|
28
|
+
|
|
29
|
+
`void`
|
|
30
|
+
|
|
31
|
+
***
|
|
32
|
+
|
|
33
|
+
### timer? {#timer}
|
|
34
|
+
|
|
35
|
+
> `optional` **timer?**: `Timeout`
|
|
36
|
+
|
|
37
|
+
Timer which enforces the waiter's deadline.
|
package/locales/en.json
CHANGED
|
@@ -114,7 +114,7 @@
|
|
|
114
114
|
"mutex": {
|
|
115
115
|
"lockNotFound": "The key \"{key}\" has no active lock",
|
|
116
116
|
"lockAlreadyReleased": "The key \"{key}\" is not currently locked",
|
|
117
|
-
"lockTimeout": "Failed to acquire lock for key \"{key}\" within the timeout of {
|
|
117
|
+
"lockTimeout": "Failed to acquire lock for key \"{key}\" within the timeout of {timeoutMs} milliseconds",
|
|
118
118
|
"bufferFetchFailed": "Failed to retrieve shared buffer for key \"{key}\" from the main thread",
|
|
119
119
|
"invalidTimeout": "The timeout value \"{timeoutMs}\" is invalid, it must be a non-negative integer"
|
|
120
120
|
},
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@twin.org/core",
|
|
3
|
-
"version": "0.9.3-next.
|
|
3
|
+
"version": "0.9.3-next.5",
|
|
4
4
|
"description": "Helper methods/classes for data type checking/validation/guarding/error handling",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"node": ">=24.0.0"
|
|
15
15
|
},
|
|
16
16
|
"dependencies": {
|
|
17
|
-
"@twin.org/nameof": "0.9.3-next.
|
|
17
|
+
"@twin.org/nameof": "0.9.3-next.5",
|
|
18
18
|
"intl-messageformat": "11.2.13",
|
|
19
19
|
"rfc6902": "5.3.0"
|
|
20
20
|
},
|