@twin.org/core 0.0.4-next.10 → 0.0.4-next.12
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 +2 -0
- package/dist/es/index.js.map +1 -1
- package/dist/es/models/IDuration.js +4 -0
- package/dist/es/models/IDuration.js.map +1 -0
- package/dist/es/models/coerceType.js +5 -1
- package/dist/es/models/coerceType.js.map +1 -1
- package/dist/es/types/duration.js +83 -0
- package/dist/es/types/duration.js.map +1 -0
- package/dist/es/utils/coerce.js +21 -0
- package/dist/es/utils/coerce.js.map +1 -1
- package/dist/es/utils/guards.js +12 -0
- package/dist/es/utils/guards.js.map +1 -1
- package/dist/es/utils/is.js +12 -0
- package/dist/es/utils/is.js.map +1 -1
- package/dist/es/utils/mutex.js +15 -6
- package/dist/es/utils/mutex.js.map +1 -1
- package/dist/es/utils/sharedObjectBuffer.js +4 -1
- package/dist/es/utils/sharedObjectBuffer.js.map +1 -1
- package/dist/types/index.d.ts +2 -0
- package/dist/types/models/IDuration.d.ts +33 -0
- package/dist/types/models/coerceType.d.ts +4 -0
- package/dist/types/types/duration.d.ts +29 -0
- package/dist/types/utils/coerce.d.ts +9 -0
- package/dist/types/utils/guards.d.ts +8 -0
- package/dist/types/utils/is.d.ts +6 -0
- package/docs/changelog.md +34 -0
- package/docs/reference/classes/Coerce.md +24 -0
- package/docs/reference/classes/Duration.md +88 -0
- package/docs/reference/classes/Guards.md +36 -0
- package/docs/reference/classes/Is.md +22 -0
- package/docs/reference/index.md +2 -0
- package/docs/reference/interfaces/IDuration.md +59 -0
- package/docs/reference/variables/CoerceType.md +6 -0
- package/locales/en.json +2 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
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,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CAAC,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,CAAC;QAC1C,CAAC;QACD,OAAO,KAAK,CAAC;IACd,CAAC;IAED;;;;OAIG;IACH,sDAAsD;IACtD,sEAAsE;IAC9D,MAAM,CAAC,KAAK,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 * 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 * 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, default is 5000.\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\n\t\tconst timeoutMs = options?.timeoutMs ?? 5000;\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 to the worker before notifying so that it is guaranteed\n\t\t// to be in port1's receive queue when Atomics.wait returns on the worker side.\n\t\tmsg.port.postMessage({ buffer: locks[msg.key].buffer });\n\t\tAtomics.notify(new Int32Array(msg.signal), 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 posts the response and fires Atomics.notify.\n\t\t\t// The response is guaranteed to be in port1's queue at this point because\n\t\t\t// port.postMessage executes before Atomics.notify on the main thread.\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\tlet locks = SharedStore.get<{ [key: string]: Int32Array }>(Mutex._LOCKS_KEY);\n\t\tif (Is.undefined(locks)) {\n\t\t\tlocks = {};\n\t\t\tSharedStore.set(Mutex._LOCKS_KEY, locks);\n\t\t}\n\t\treturn locks;\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;AAEzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,gCAAgC,CAAC;AAEnE;;;;;;;;;;;;;;;GAeG;AACH,MAAM,OAAO,KAAK;IACjB;;OAEG;IACI,MAAM,CAAU,UAAU,WAA2B;IAE5D;;;OAGG;IACK,MAAM,CAAU,UAAU,GAAG,YAAY,CAAC;IAElD;;;OAGG;IACH,sDAAsD;IACtD,sEAAsE;IAC9D,MAAM,CAAC,oBAAoB,CAA0D;IAE7F;;;;;;;;;;;;;OAaG;IACI,MAAM,CAAC,KAAK,CAAC,IAAI,CACvB,GAAW,EACX,OAA0D;QAE1D,MAAM,CAAC,WAAW,CAAC,KAAK,CAAC,UAAU,SAAe,GAAG,CAAC,CAAC;QAEvD,MAAM,SAAS,GAAG,OAAO,EAAE,SAAS,IAAI,IA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nC,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 * 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 * 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, default is 5000.\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\n\t\tconst timeoutMs = options?.timeoutMs ?? 5000;\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\tlet locks = SharedStore.get<{ [key: string]: Int32Array }>(Mutex._LOCKS_KEY);\n\t\tif (Is.undefined(locks)) {\n\t\t\tlocks = {};\n\t\t\tSharedStore.set(Mutex._LOCKS_KEY, locks);\n\t\t}\n\t\treturn locks;\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,4 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Is } from "./is.js";
|
|
2
|
+
import { SharedStore } from "./sharedStore.js";
|
|
3
|
+
import { GeneralError } from "../errors/generalError.js";
|
|
4
|
+
import { ObjectHelper } from "../helpers/objectHelper.js";
|
|
2
5
|
import { SharedObjectBufferMessageTypes } from "../models/sharedObjectBufferMessageTypes.js";
|
|
3
6
|
/**
|
|
4
7
|
* Manages per-object SharedArrayBuffers that store objects as UTF-8 JSON.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sharedObjectBuffer.js","sourceRoot":"","sources":["../../../src/utils/sharedObjectBuffer.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,YAAY,EAAE,EAAE,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAI7E,OAAO,EAAE,8BAA8B,EAAE,MAAM,6CAA6C,CAAC;AAE7F;;;;;;;;;;GAUG;AACH,MAAM,OAAO,kBAAkB;IAC9B;;OAEG;IACI,MAAM,CAAU,UAAU,wBAAwC;IAEzE;;;;OAIG;IACI,MAAM,CAAU,sBAAsB,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC;IAEhE;;;OAGG;IACI,MAAM,CAAU,kBAAkB,GAAG,GAAG,GAAG,IAAI,GAAG,IAAI,CAAC;IAE9D;;;OAGG;IACK,MA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O,GAAG,EAAE,CAAC;YACb,WAAW,CAAC,GAAG,CAAC,kBAAkB,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QACzD,CAAC;QACD,OAAO,OAAO,CAAC;IAChB,CAAC;IAED;;;;OAIG;IACH,sDAAsD;IACtD,sEAAsE;IAC9D,MAAM,CAAC,KAAK,CAAC,iBAAiB;QACrC,IAAI,kBAAkB,CAAC,oBAAoB,KAAK,SAAS,EAAE,CAAC;YAC3D,IAAI,CAAC;gBACJ,kBAAkB,CAAC,oBAAoB,GAAG,MAAM,MAAM,CAAC,qBAAqB,CAAC,CAAC;YAC/E,CAAC;YAAC,MAAM,CAAC;gBACR,kBAAkB,CAAC,oBAAoB,GAAG,IAAI,CAAC;YAChD,CAAC;QACF,CAAC;QACD,OAAO,kBAAkB,CAAC,oBAAoB,CAAC;IAChD,CAAC","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { MessagePort } from \"node:worker_threads\";\nimport { GeneralError, Is, ObjectHelper, SharedStore } from \"@twin.org/core\";\nimport { nameof } from \"@twin.org/nameof\";\nimport type { ISharedObjectBufferOptions } from \"../models/ISharedObjectBufferOptions.js\";\nimport type { ISharedObjectBufferWorkerMessage } from \"../models/ISharedObjectBufferWorkerMessage.js\";\nimport { SharedObjectBufferMessageTypes } from \"../models/sharedObjectBufferMessageTypes.js\";\n\n/**\n * Manages per-object SharedArrayBuffers that store objects as UTF-8 JSON.\n * Buffer layout: 4-byte Int32 header (current data byte length) followed by the JSON-encoded object.\n * Buffers are explicitly created with create and cached in SharedStore.\n * On a worker thread an existing buffer is fetched via a MessagePort handshake\n * (same protocol as Mutex) and cached locally.\n * Buffers grow automatically when the payload exceeds capacity; when the payload drops well below\n * capacity the buffer is replaced with a smaller one. The caller must hold the objectId-keyed Mutex\n * around every read and write. The main thread's worker message handler must forward messages to\n * both Mutex.handleWorkerMessage and SharedObjectBuffer.handleWorkerMessage.\n */\nexport class SharedObjectBuffer {\n\t/**\n\t * Runtime name for the class.\n\t */\n\tpublic static readonly CLASS_NAME: string = nameof<SharedObjectBuffer>();\n\n\t/**\n\t * Default payload capacity per object (1 MiB). The first caller that creates the buffer\n\t * for an object determines its initial capacity; later callers that pass a different value\n\t * are ignored.\n\t */\n\tpublic static readonly DEFAULT_CAPACITY_BYTES = 1 * 1024 * 1024;\n\n\t/**\n\t * Default upper bound for how large a buffer may grow (256 MiB).\n\t * Override per-object via the maxCapacityBytes option on create.\n\t */\n\tpublic static readonly MAX_CAPACITY_BYTES = 256 * 1024 * 1024;\n\n\t/**\n\t * Bytes reserved for the data-length header at the start of each buffer.\n\t * @internal\n\t */\n\tprivate static readonly _HEADER_BYTES = 4;\n\n\t/**\n\t * Multiplier applied to the current capacity when growing or sizing a replacement buffer.\n\t * @internal\n\t */\n\tprivate static readonly _GROW_FACTOR = 2;\n\n\t/**\n\t * Fraction of payload capacity below which a buffer is replaced with a smaller one.\n\t * A value of 0.25 means the buffer is shrunk when the payload is below 25 % of capacity.\n\t * Shrinking only applies when the capacity already exceeds DEFAULT_CAPACITY_BYTES.\n\t * @internal\n\t */\n\tprivate static readonly _SHRINK_THRESHOLD = 0.25;\n\n\t/**\n\t * SharedStore key under which the per-object buffer map lives on each thread.\n\t * @internal\n\t */\n\tprivate static readonly _STORE_KEY = \"sharedObjectBuffers\";\n\n\t/**\n\t * Cached worker_threads module; undefined = not yet loaded, null = unavailable.\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 * Create the buffer for the given objectId if it does not already exist.\n\t * Must be called while holding Mutex.lock(objectId).\n\t * @param objectId The object id that identifies the buffer.\n\t * @param options Optional capacity configuration used when creating the buffer.\n\t */\n\tpublic static async create(\n\t\tobjectId: string,\n\t\toptions?: ISharedObjectBufferOptions\n\t): Promise<void> {\n\t\tawait SharedObjectBuffer.getOrFetchBuffer(objectId, options ?? {});\n\t}\n\n\t/**\n\t * Read and decode the object stored for the given objectId.\n\t * Must be called while holding Mutex.lock(objectId).\n\t * @param objectId The object id that identifies the buffer.\n\t * @returns The stored object, or undefined when nothing has been written yet.\n\t */\n\tpublic static async read<T>(objectId: string): Promise<T | undefined> {\n\t\tconst buf = await SharedObjectBuffer.getOrFetchBuffer(objectId);\n\t\tif (Is.undefined(buf)) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn SharedObjectBuffer.decode<T>(buf);\n\t}\n\n\t/**\n\t * Encode and write the object into the buffer for the given objectId.\n\t * The buffer must already exist, usually by calling create first.\n\t * When the encoded payload exceeds the current buffer capacity the buffer is grown\n\t * in-place via SharedArrayBuffer.grow so every thread with a reference sees the\n\t * new size without any pointer swap. When the payload is smaller than\n\t * _SHRINK_THRESHOLD of the current capacity and the capacity exceeds\n\t * DEFAULT_CAPACITY_BYTES, the buffer is replaced with a smaller one on the calling thread.\n\t * Must be called while holding Mutex.lock(objectId).\n\t * @param objectId The object id that identifies the buffer.\n\t * @param value The object to persist.\n\t */\n\tpublic static async write<T>(objectId: string, value: T): Promise<void> {\n\t\tconst encoded = ObjectHelper.toBytes(value);\n\t\tlet buf = await SharedObjectBuffer.getOrFetchBuffer(objectId);\n\n\t\tif (Is.undefined(buf)) {\n\t\t\tthrow new GeneralError(SharedObjectBuffer.CLASS_NAME, \"notCreated\", {\n\t\t\t\tobjectId\n\t\t\t});\n\t\t}\n\n\t\tconst payloadCapacity = buf.byteLength - SharedObjectBuffer._HEADER_BYTES;\n\t\tconst maxPayloadCapacity = buf.maxByteLength - SharedObjectBuffer._HEADER_BYTES;\n\n\t\tif (encoded.length > payloadCapacity) {\n\t\t\t// Grow the buffer in-place. SharedArrayBuffer.grow is atomic: all threads that\n\t\t\t// hold a reference see the enlarged buffer without a pointer swap.\n\t\t\tconst newPayloadCapacity = Math.max(\n\t\t\t\tencoded.length,\n\t\t\t\tpayloadCapacity * SharedObjectBuffer._GROW_FACTOR\n\t\t\t);\n\t\t\tconst newByteLength = Math.min(\n\t\t\t\tSharedObjectBuffer._HEADER_BYTES + newPayloadCapacity,\n\t\t\t\tbuf.maxByteLength\n\t\t\t);\n\t\t\tif (encoded.length > newByteLength - SharedObjectBuffer._HEADER_BYTES) {\n\t\t\t\tthrow new GeneralError(SharedObjectBuffer.CLASS_NAME, \"capacityExceeded\", {\n\t\t\t\t\tobjectId,\n\t\t\t\t\trequired: encoded.length,\n\t\t\t\t\tcapacity: maxPayloadCapacity\n\t\t\t\t});\n\t\t\t}\n\t\t\tbuf.grow(newByteLength);\n\t\t} else if (\n\t\t\tpayloadCapacity > SharedObjectBuffer.DEFAULT_CAPACITY_BYTES &&\n\t\t\tencoded.length < payloadCapacity * SharedObjectBuffer._SHRINK_THRESHOLD\n\t\t) {\n\t\t\t// Replace with a smaller buffer when far below capacity. The caller writes\n\t\t\t// the payload into the returned buffer immediately after.\n\t\t\tbuf = SharedObjectBuffer.shrinkBuffer(objectId, encoded.length, buf.maxByteLength);\n\t\t}\n\n\t\tnew Uint8Array(buf, SharedObjectBuffer._HEADER_BYTES).set(encoded);\n\t\tAtomics.store(new Int32Array(buf, 0, 1), 0, encoded.length);\n\t}\n\n\t/**\n\t * Remove the stored object and release the buffer for the given objectId.\n\t * The entry is deleted from the local cache so subsequent reads or writes will\n\t * create or fetch a fresh buffer. Worker threads that have cached the old buffer\n\t * reference continue using it until they restart or re-request via the worker protocol.\n\t * Must be called while holding Mutex.lock(objectId).\n\t * @param objectId The object id that identifies the buffer.\n\t */\n\tpublic static remove(objectId: string): void {\n\t\tdelete SharedObjectBuffer.getBuffers()[objectId];\n\t}\n\n\t/**\n\t * Inspect a message from a worker thread and, if it is a SharedObjectBuffer\n\t * buffer-fetch request, respond to it synchronously.\n\t * Call this from the main thread's worker message handler alongside\n\t * Mutex.handleWorkerMessage.\n\t * @param msg The raw message received from the worker.\n\t * @returns True if the message was a SharedObjectBuffer protocol message, false otherwise.\n\t */\n\tpublic static handleWorkerMessage(msg: unknown): boolean {\n\t\tif (\n\t\t\t!Is.object<ISharedObjectBufferWorkerMessage>(msg) ||\n\t\t\tmsg.type !== SharedObjectBufferMessageTypes.GetBuffer\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst {\n\t\t\tobjectId: objectName,\n\t\t\tport,\n\t\t\tsignal,\n\t\t\toptions\n\t\t} = msg as ISharedObjectBufferWorkerMessage & {\n\t\t\tport: MessagePort;\n\t\t};\n\n\t\tconst buf = Is.object(options)\n\t\t\t? SharedObjectBuffer.getOrCreateBuffer(objectName, options)\n\t\t\t: SharedObjectBuffer.getBuffers()[objectName];\n\n\t\t// Deliver the buffer before waking the worker so it is in the port's receive\n\t\t// queue when Atomics.wait returns (same ordering guarantee as Mutex).\n\t\tport.postMessage({ buffer: buf });\n\t\tAtomics.notify(new Int32Array(signal), 0, 1);\n\t\tport.close();\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Decode the object from a SharedArrayBuffer.\n\t * @param buf The SharedArrayBuffer to decode.\n\t * @returns The decoded object, or undefined when nothing has been written.\n\t * @internal\n\t */\n\tprivate static decode<T>(buf: SharedArrayBuffer): T | undefined {\n\t\tconst dataLen = Atomics.load(new Int32Array(buf, 0, 1), 0);\n\t\tif (dataLen === 0) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst bytes = new Uint8Array(buf, SharedObjectBuffer._HEADER_BYTES, dataLen);\n\t\treturn ObjectHelper.fromBytes<T>(bytes);\n\t}\n\n\t/**\n\t * Return the cached buffer for the object, creating or fetching it if needed.\n\t * Applies a double-check after the async loadWorkerThreads call to handle the\n\t * case where another coroutine populated the cache while this one yielded.\n\t * @param objectId The object id that identifies the buffer.\n\t * @param options Optional capacity configuration when creating the buffer.\n\t * @returns The SharedArrayBuffer for the object.\n\t * @internal\n\t */\n\tprivate static async getOrFetchBuffer(\n\t\tobjectId: string,\n\t\toptions?: ISharedObjectBufferOptions\n\t): Promise<SharedArrayBuffer | undefined> {\n\t\tconst buffers = SharedObjectBuffer.getBuffers();\n\n\t\tif (!Is.undefined(buffers[objectId])) {\n\t\t\treturn buffers[objectId];\n\t\t}\n\n\t\tconst wt = await SharedObjectBuffer.loadWorkerThreads();\n\n\t\t// Re-check after the await: another coroutine may have populated the cache.\n\t\tif (!Is.undefined(buffers[objectId])) {\n\t\t\treturn buffers[objectId];\n\t\t}\n\n\t\tif (Is.empty(wt) || wt.isMainThread) {\n\t\t\tif (!Is.object(options)) {\n\t\t\t\treturn buffers[objectId];\n\t\t\t}\n\t\t\treturn SharedObjectBuffer.getOrCreateBuffer(objectId, options);\n\t\t}\n\n\t\t// Worker thread: synchronously request the SharedArrayBuffer from the main thread.\n\t\tif (Is.empty(wt.parentPort)) {\n\t\t\tthrow new GeneralError(SharedObjectBuffer.CLASS_NAME, \"bufferFetchFailed\", { objectId });\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 request: ISharedObjectBufferWorkerMessage = {\n\t\t\ttype: SharedObjectBufferMessageTypes.GetBuffer,\n\t\t\tobjectId,\n\t\t\tsignal: signal.buffer,\n\t\t\tport: port2,\n\t\t\toptions\n\t\t};\n\n\t\twt.parentPort.postMessage(request, [port2]);\n\n\t\ttry {\n\t\t\t// Block until the main thread posts the buffer and fires Atomics.notify.\n\t\t\t// The response is guaranteed to be in port1's queue when wait returns because\n\t\t\t// port.postMessage executes before Atomics.notify on the main thread.\n\t\t\tconst waitResult = Atomics.wait(signal, 0, 0, 30_000);\n\t\t\tif (waitResult === \"timed-out\") {\n\t\t\t\tthrow new GeneralError(SharedObjectBuffer.CLASS_NAME, \"bufferFetchFailed\", { objectId });\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(SharedObjectBuffer.CLASS_NAME, \"bufferFetchFailed\", { objectId });\n\t\t\t}\n\n\t\t\tif (Is.undefined(response.message.buffer)) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\n\t\t\tbuffers[objectId] = response.message.buffer;\n\t\t\treturn buffers[objectId];\n\t\t} finally {\n\t\t\tport1.close();\n\t\t}\n\t}\n\n\t/**\n\t * Get or create the growable buffer on the main thread (or in a fork-mode process).\n\t * @param objectId The object id that identifies the buffer.\n\t * @param options Optional capacity configuration for new buffers.\n\t * @returns The existing or newly created SharedArrayBuffer.\n\t * @internal\n\t */\n\tprivate static getOrCreateBuffer(\n\t\tobjectId: string,\n\t\toptions?: ISharedObjectBufferOptions\n\t): SharedArrayBuffer {\n\t\tconst buffers = SharedObjectBuffer.getBuffers();\n\t\tif (Is.undefined(buffers[objectId])) {\n\t\t\tconst maxCapacity = options?.maxCapacityBytes ?? SharedObjectBuffer.MAX_CAPACITY_BYTES;\n\t\t\tconst initialCapacity = Math.min(\n\t\t\t\toptions?.initialCapacityBytes ?? SharedObjectBuffer.DEFAULT_CAPACITY_BYTES,\n\t\t\t\tmaxCapacity\n\t\t\t);\n\t\t\tbuffers[objectId] = new SharedArrayBuffer(\n\t\t\t\tSharedObjectBuffer._HEADER_BYTES + initialCapacity,\n\t\t\t\t{\n\t\t\t\t\tmaxByteLength: SharedObjectBuffer._HEADER_BYTES + maxCapacity\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t\treturn buffers[objectId];\n\t}\n\n\t/**\n\t * Create a new smaller SharedArrayBuffer, register it in SharedStore, and return it.\n\t * The new buffer is empty; write writes the current payload into it immediately\n\t * after this call returns. Callers on other threads that have cached the old buffer\n\t * reference continue using it until they restart or re-request via the worker protocol.\n\t * @param objectId The object id that identifies the buffer.\n\t * @param dataLen Byte length of the payload that will be written next.\n\t * @param maxByteLength The maxByteLength to preserve from the old buffer.\n\t * @returns The new, smaller SharedArrayBuffer registered in SharedStore.\n\t * @internal\n\t */\n\tprivate static shrinkBuffer(\n\t\tobjectId: string,\n\t\tdataLen: number,\n\t\tmaxByteLength: number\n\t): SharedArrayBuffer {\n\t\tconst newCapacity = Math.max(\n\t\t\tdataLen * SharedObjectBuffer._GROW_FACTOR,\n\t\t\tSharedObjectBuffer.DEFAULT_CAPACITY_BYTES\n\t\t);\n\t\tconst newBuf = new SharedArrayBuffer(SharedObjectBuffer._HEADER_BYTES + newCapacity, {\n\t\t\tmaxByteLength\n\t\t});\n\t\tSharedObjectBuffer.getBuffers()[objectId] = newBuf;\n\t\treturn newBuf;\n\t}\n\n\t/**\n\t * Return the per-thread buffer map from SharedStore, creating it if absent.\n\t * @returns The map of object id to SharedArrayBuffer.\n\t * @internal\n\t */\n\tprivate static getBuffers(): { [objectId: string]: SharedArrayBuffer } {\n\t\tlet buffers = SharedStore.get<{ [objectId: string]: SharedArrayBuffer }>(\n\t\t\tSharedObjectBuffer._STORE_KEY\n\t\t);\n\t\tif (Is.undefined(buffers)) {\n\t\t\tbuffers = {};\n\t\t\tSharedStore.set(SharedObjectBuffer._STORE_KEY, buffers);\n\t\t}\n\t\treturn buffers;\n\t}\n\n\t/**\n\t * Lazily load 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 (SharedObjectBuffer._workerThreadsModule === undefined) {\n\t\t\ttry {\n\t\t\t\tSharedObjectBuffer._workerThreadsModule = await import(\"node:worker_threads\");\n\t\t\t} catch {\n\t\t\t\tSharedObjectBuffer._workerThreadsModule = null;\n\t\t\t}\n\t\t}\n\t\treturn SharedObjectBuffer._workerThreadsModule;\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"sharedObjectBuffer.js","sourceRoot":"","sources":["../../../src/utils/sharedObjectBuffer.ts"],"names":[],"mappings":"AAIA,OA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AAqB;QAErB,MAAM,WAAW,GAAG,IAAI,CAAC,GAAG,CAC3B,OAAO,GAAG,kBAAkB,CAAC,YAAY,EACzC,kBAAkB,CAAC,sBAAsB,CACzC,CAAC;QACF,MAAM,MAAM,GAAG,IAAI,iBAAiB,CAAC,kBAAkB,CAAC,aAAa,GAAG,WAAW,EAAE;YACpF,aAAa;SACb,CAAC,CAAC;QACH,kBAAkB,CAAC,UAAU,EAAE,CAAC,QAAQ,CAAC,GAAG,MAAM,CAAC;QACnD,OAAO,MAAM,CAAC;IACf,CAAC;IAED;;;;OAIG;IACK,MAAM,CAAC,UAAU;QACxB,IAAI,OAAO,GAAG,WAAW,CAAC,GAAG,CAC5B,kBAAkB,CAAC,UAAU,CAC7B,CAAC;QACF,IAAI,EAAE,CAAC,SAAS,CAAC,OAAO,CAAC,EAAE,CAAC;YAC3B,OAAO,GAAG,EAAE,CAAC;YACb,WAAW,CAAC,GAAG,CAAC,kBAAkB,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QACzD,CAAC;QACD,OAAO,OAAO,CAAC;IAChB,CAAC;IAED;;;;OAIG;IACH,sDAAsD;IACtD,sEAAsE;IAC9D,MAAM,CAAC,KAAK,CAAC,iBAAiB;QACrC,IAAI,kBAAkB,CAAC,oBAAoB,KAAK,SAAS,EAAE,CAAC;YAC3D,IAAI,CAAC;gBACJ,kBAAkB,CAAC,oBAAoB,GAAG,MAAM,MAAM,CAAC,qBAAqB,CAAC,CAAC;YAC/E,CAAC;YAAC,MAAM,CAAC;gBACR,kBAAkB,CAAC,oBAAoB,GAAG,IAAI,CAAC;YAChD,CAAC;QACF,CAAC;QACD,OAAO,kBAAkB,CAAC,oBAAoB,CAAC;IAChD,CAAC","sourcesContent":["// Copyright 2024 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { MessagePort } from \"node:worker_threads\";\nimport { nameof } from \"@twin.org/nameof\";\nimport { Is } from \"./is.js\";\nimport { SharedStore } from \"./sharedStore.js\";\nimport { GeneralError } from \"../errors/generalError.js\";\nimport { ObjectHelper } from \"../helpers/objectHelper.js\";\nimport type { ISharedObjectBufferOptions } from \"../models/ISharedObjectBufferOptions.js\";\nimport type { ISharedObjectBufferWorkerMessage } from \"../models/ISharedObjectBufferWorkerMessage.js\";\nimport { SharedObjectBufferMessageTypes } from \"../models/sharedObjectBufferMessageTypes.js\";\n\n/**\n * Manages per-object SharedArrayBuffers that store objects as UTF-8 JSON.\n * Buffer layout: 4-byte Int32 header (current data byte length) followed by the JSON-encoded object.\n * Buffers are explicitly created with create and cached in SharedStore.\n * On a worker thread an existing buffer is fetched via a MessagePort handshake\n * (same protocol as Mutex) and cached locally.\n * Buffers grow automatically when the payload exceeds capacity; when the payload drops well below\n * capacity the buffer is replaced with a smaller one. The caller must hold the objectId-keyed Mutex\n * around every read and write. The main thread's worker message handler must forward messages to\n * both Mutex.handleWorkerMessage and SharedObjectBuffer.handleWorkerMessage.\n */\nexport class SharedObjectBuffer {\n\t/**\n\t * Runtime name for the class.\n\t */\n\tpublic static readonly CLASS_NAME: string = nameof<SharedObjectBuffer>();\n\n\t/**\n\t * Default payload capacity per object (1 MiB). The first caller that creates the buffer\n\t * for an object determines its initial capacity; later callers that pass a different value\n\t * are ignored.\n\t */\n\tpublic static readonly DEFAULT_CAPACITY_BYTES = 1 * 1024 * 1024;\n\n\t/**\n\t * Default upper bound for how large a buffer may grow (256 MiB).\n\t * Override per-object via the maxCapacityBytes option on create.\n\t */\n\tpublic static readonly MAX_CAPACITY_BYTES = 256 * 1024 * 1024;\n\n\t/**\n\t * Bytes reserved for the data-length header at the start of each buffer.\n\t * @internal\n\t */\n\tprivate static readonly _HEADER_BYTES = 4;\n\n\t/**\n\t * Multiplier applied to the current capacity when growing or sizing a replacement buffer.\n\t * @internal\n\t */\n\tprivate static readonly _GROW_FACTOR = 2;\n\n\t/**\n\t * Fraction of payload capacity below which a buffer is replaced with a smaller one.\n\t * A value of 0.25 means the buffer is shrunk when the payload is below 25 % of capacity.\n\t * Shrinking only applies when the capacity already exceeds DEFAULT_CAPACITY_BYTES.\n\t * @internal\n\t */\n\tprivate static readonly _SHRINK_THRESHOLD = 0.25;\n\n\t/**\n\t * SharedStore key under which the per-object buffer map lives on each thread.\n\t * @internal\n\t */\n\tprivate static readonly _STORE_KEY = \"sharedObjectBuffers\";\n\n\t/**\n\t * Cached worker_threads module; undefined = not yet loaded, null = unavailable.\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 * Create the buffer for the given objectId if it does not already exist.\n\t * Must be called while holding Mutex.lock(objectId).\n\t * @param objectId The object id that identifies the buffer.\n\t * @param options Optional capacity configuration used when creating the buffer.\n\t */\n\tpublic static async create(\n\t\tobjectId: string,\n\t\toptions?: ISharedObjectBufferOptions\n\t): Promise<void> {\n\t\tawait SharedObjectBuffer.getOrFetchBuffer(objectId, options ?? {});\n\t}\n\n\t/**\n\t * Read and decode the object stored for the given objectId.\n\t * Must be called while holding Mutex.lock(objectId).\n\t * @param objectId The object id that identifies the buffer.\n\t * @returns The stored object, or undefined when nothing has been written yet.\n\t */\n\tpublic static async read<T>(objectId: string): Promise<T | undefined> {\n\t\tconst buf = await SharedObjectBuffer.getOrFetchBuffer(objectId);\n\t\tif (Is.undefined(buf)) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn SharedObjectBuffer.decode<T>(buf);\n\t}\n\n\t/**\n\t * Encode and write the object into the buffer for the given objectId.\n\t * The buffer must already exist, usually by calling create first.\n\t * When the encoded payload exceeds the current buffer capacity the buffer is grown\n\t * in-place via SharedArrayBuffer.grow so every thread with a reference sees the\n\t * new size without any pointer swap. When the payload is smaller than\n\t * _SHRINK_THRESHOLD of the current capacity and the capacity exceeds\n\t * DEFAULT_CAPACITY_BYTES, the buffer is replaced with a smaller one on the calling thread.\n\t * Must be called while holding Mutex.lock(objectId).\n\t * @param objectId The object id that identifies the buffer.\n\t * @param value The object to persist.\n\t */\n\tpublic static async write<T>(objectId: string, value: T): Promise<void> {\n\t\tconst encoded = ObjectHelper.toBytes(value);\n\t\tlet buf = await SharedObjectBuffer.getOrFetchBuffer(objectId);\n\n\t\tif (Is.undefined(buf)) {\n\t\t\tthrow new GeneralError(SharedObjectBuffer.CLASS_NAME, \"notCreated\", {\n\t\t\t\tobjectId\n\t\t\t});\n\t\t}\n\n\t\tconst payloadCapacity = buf.byteLength - SharedObjectBuffer._HEADER_BYTES;\n\t\tconst maxPayloadCapacity = buf.maxByteLength - SharedObjectBuffer._HEADER_BYTES;\n\n\t\tif (encoded.length > payloadCapacity) {\n\t\t\t// Grow the buffer in-place. SharedArrayBuffer.grow is atomic: all threads that\n\t\t\t// hold a reference see the enlarged buffer without a pointer swap.\n\t\t\tconst newPayloadCapacity = Math.max(\n\t\t\t\tencoded.length,\n\t\t\t\tpayloadCapacity * SharedObjectBuffer._GROW_FACTOR\n\t\t\t);\n\t\t\tconst newByteLength = Math.min(\n\t\t\t\tSharedObjectBuffer._HEADER_BYTES + newPayloadCapacity,\n\t\t\t\tbuf.maxByteLength\n\t\t\t);\n\t\t\tif (encoded.length > newByteLength - SharedObjectBuffer._HEADER_BYTES) {\n\t\t\t\tthrow new GeneralError(SharedObjectBuffer.CLASS_NAME, \"capacityExceeded\", {\n\t\t\t\t\tobjectId,\n\t\t\t\t\trequired: encoded.length,\n\t\t\t\t\tcapacity: maxPayloadCapacity\n\t\t\t\t});\n\t\t\t}\n\t\t\tbuf.grow(newByteLength);\n\t\t} else if (\n\t\t\tpayloadCapacity > SharedObjectBuffer.DEFAULT_CAPACITY_BYTES &&\n\t\t\tencoded.length < payloadCapacity * SharedObjectBuffer._SHRINK_THRESHOLD\n\t\t) {\n\t\t\t// Replace with a smaller buffer when far below capacity. The caller writes\n\t\t\t// the payload into the returned buffer immediately after.\n\t\t\tbuf = SharedObjectBuffer.shrinkBuffer(objectId, encoded.length, buf.maxByteLength);\n\t\t}\n\n\t\tnew Uint8Array(buf, SharedObjectBuffer._HEADER_BYTES).set(encoded);\n\t\tAtomics.store(new Int32Array(buf, 0, 1), 0, encoded.length);\n\t}\n\n\t/**\n\t * Remove the stored object and release the buffer for the given objectId.\n\t * The entry is deleted from the local cache so subsequent reads or writes will\n\t * create or fetch a fresh buffer. Worker threads that have cached the old buffer\n\t * reference continue using it until they restart or re-request via the worker protocol.\n\t * Must be called while holding Mutex.lock(objectId).\n\t * @param objectId The object id that identifies the buffer.\n\t */\n\tpublic static remove(objectId: string): void {\n\t\tdelete SharedObjectBuffer.getBuffers()[objectId];\n\t}\n\n\t/**\n\t * Inspect a message from a worker thread and, if it is a SharedObjectBuffer\n\t * buffer-fetch request, respond to it synchronously.\n\t * Call this from the main thread's worker message handler alongside\n\t * Mutex.handleWorkerMessage.\n\t * @param msg The raw message received from the worker.\n\t * @returns True if the message was a SharedObjectBuffer protocol message, false otherwise.\n\t */\n\tpublic static handleWorkerMessage(msg: unknown): boolean {\n\t\tif (\n\t\t\t!Is.object<ISharedObjectBufferWorkerMessage>(msg) ||\n\t\t\tmsg.type !== SharedObjectBufferMessageTypes.GetBuffer\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst {\n\t\t\tobjectId: objectName,\n\t\t\tport,\n\t\t\tsignal,\n\t\t\toptions\n\t\t} = msg as ISharedObjectBufferWorkerMessage & {\n\t\t\tport: MessagePort;\n\t\t};\n\n\t\tconst buf = Is.object(options)\n\t\t\t? SharedObjectBuffer.getOrCreateBuffer(objectName, options)\n\t\t\t: SharedObjectBuffer.getBuffers()[objectName];\n\n\t\t// Deliver the buffer before waking the worker so it is in the port's receive\n\t\t// queue when Atomics.wait returns (same ordering guarantee as Mutex).\n\t\tport.postMessage({ buffer: buf });\n\t\tAtomics.notify(new Int32Array(signal), 0, 1);\n\t\tport.close();\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Decode the object from a SharedArrayBuffer.\n\t * @param buf The SharedArrayBuffer to decode.\n\t * @returns The decoded object, or undefined when nothing has been written.\n\t * @internal\n\t */\n\tprivate static decode<T>(buf: SharedArrayBuffer): T | undefined {\n\t\tconst dataLen = Atomics.load(new Int32Array(buf, 0, 1), 0);\n\t\tif (dataLen === 0) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst bytes = new Uint8Array(buf, SharedObjectBuffer._HEADER_BYTES, dataLen);\n\t\treturn ObjectHelper.fromBytes<T>(bytes);\n\t}\n\n\t/**\n\t * Return the cached buffer for the object, creating or fetching it if needed.\n\t * Applies a double-check after the async loadWorkerThreads call to handle the\n\t * case where another coroutine populated the cache while this one yielded.\n\t * @param objectId The object id that identifies the buffer.\n\t * @param options Optional capacity configuration when creating the buffer.\n\t * @returns The SharedArrayBuffer for the object.\n\t * @internal\n\t */\n\tprivate static async getOrFetchBuffer(\n\t\tobjectId: string,\n\t\toptions?: ISharedObjectBufferOptions\n\t): Promise<SharedArrayBuffer | undefined> {\n\t\tconst buffers = SharedObjectBuffer.getBuffers();\n\n\t\tif (!Is.undefined(buffers[objectId])) {\n\t\t\treturn buffers[objectId];\n\t\t}\n\n\t\tconst wt = await SharedObjectBuffer.loadWorkerThreads();\n\n\t\t// Re-check after the await: another coroutine may have populated the cache.\n\t\tif (!Is.undefined(buffers[objectId])) {\n\t\t\treturn buffers[objectId];\n\t\t}\n\n\t\tif (Is.empty(wt) || wt.isMainThread) {\n\t\t\tif (!Is.object(options)) {\n\t\t\t\treturn buffers[objectId];\n\t\t\t}\n\t\t\treturn SharedObjectBuffer.getOrCreateBuffer(objectId, options);\n\t\t}\n\n\t\t// Worker thread: synchronously request the SharedArrayBuffer from the main thread.\n\t\tif (Is.empty(wt.parentPort)) {\n\t\t\tthrow new GeneralError(SharedObjectBuffer.CLASS_NAME, \"bufferFetchFailed\", { objectId });\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 request: ISharedObjectBufferWorkerMessage = {\n\t\t\ttype: SharedObjectBufferMessageTypes.GetBuffer,\n\t\t\tobjectId,\n\t\t\tsignal: signal.buffer,\n\t\t\tport: port2,\n\t\t\toptions\n\t\t};\n\n\t\twt.parentPort.postMessage(request, [port2]);\n\n\t\ttry {\n\t\t\t// Block until the main thread posts the buffer and fires Atomics.notify.\n\t\t\t// The response is guaranteed to be in port1's queue when wait returns because\n\t\t\t// port.postMessage executes before Atomics.notify on the main thread.\n\t\t\tconst waitResult = Atomics.wait(signal, 0, 0, 30_000);\n\t\t\tif (waitResult === \"timed-out\") {\n\t\t\t\tthrow new GeneralError(SharedObjectBuffer.CLASS_NAME, \"bufferFetchFailed\", { objectId });\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(SharedObjectBuffer.CLASS_NAME, \"bufferFetchFailed\", { objectId });\n\t\t\t}\n\n\t\t\tif (Is.undefined(response.message.buffer)) {\n\t\t\t\treturn undefined;\n\t\t\t}\n\n\t\t\tbuffers[objectId] = response.message.buffer;\n\t\t\treturn buffers[objectId];\n\t\t} finally {\n\t\t\tport1.close();\n\t\t}\n\t}\n\n\t/**\n\t * Get or create the growable buffer on the main thread (or in a fork-mode process).\n\t * @param objectId The object id that identifies the buffer.\n\t * @param options Optional capacity configuration for new buffers.\n\t * @returns The existing or newly created SharedArrayBuffer.\n\t * @internal\n\t */\n\tprivate static getOrCreateBuffer(\n\t\tobjectId: string,\n\t\toptions?: ISharedObjectBufferOptions\n\t): SharedArrayBuffer {\n\t\tconst buffers = SharedObjectBuffer.getBuffers();\n\t\tif (Is.undefined(buffers[objectId])) {\n\t\t\tconst maxCapacity = options?.maxCapacityBytes ?? SharedObjectBuffer.MAX_CAPACITY_BYTES;\n\t\t\tconst initialCapacity = Math.min(\n\t\t\t\toptions?.initialCapacityBytes ?? SharedObjectBuffer.DEFAULT_CAPACITY_BYTES,\n\t\t\t\tmaxCapacity\n\t\t\t);\n\t\t\tbuffers[objectId] = new SharedArrayBuffer(\n\t\t\t\tSharedObjectBuffer._HEADER_BYTES + initialCapacity,\n\t\t\t\t{\n\t\t\t\t\tmaxByteLength: SharedObjectBuffer._HEADER_BYTES + maxCapacity\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\t\treturn buffers[objectId];\n\t}\n\n\t/**\n\t * Create a new smaller SharedArrayBuffer, register it in SharedStore, and return it.\n\t * The new buffer is empty; write writes the current payload into it immediately\n\t * after this call returns. Callers on other threads that have cached the old buffer\n\t * reference continue using it until they restart or re-request via the worker protocol.\n\t * @param objectId The object id that identifies the buffer.\n\t * @param dataLen Byte length of the payload that will be written next.\n\t * @param maxByteLength The maxByteLength to preserve from the old buffer.\n\t * @returns The new, smaller SharedArrayBuffer registered in SharedStore.\n\t * @internal\n\t */\n\tprivate static shrinkBuffer(\n\t\tobjectId: string,\n\t\tdataLen: number,\n\t\tmaxByteLength: number\n\t): SharedArrayBuffer {\n\t\tconst newCapacity = Math.max(\n\t\t\tdataLen * SharedObjectBuffer._GROW_FACTOR,\n\t\t\tSharedObjectBuffer.DEFAULT_CAPACITY_BYTES\n\t\t);\n\t\tconst newBuf = new SharedArrayBuffer(SharedObjectBuffer._HEADER_BYTES + newCapacity, {\n\t\t\tmaxByteLength\n\t\t});\n\t\tSharedObjectBuffer.getBuffers()[objectId] = newBuf;\n\t\treturn newBuf;\n\t}\n\n\t/**\n\t * Return the per-thread buffer map from SharedStore, creating it if absent.\n\t * @returns The map of object id to SharedArrayBuffer.\n\t * @internal\n\t */\n\tprivate static getBuffers(): { [objectId: string]: SharedArrayBuffer } {\n\t\tlet buffers = SharedStore.get<{ [objectId: string]: SharedArrayBuffer }>(\n\t\t\tSharedObjectBuffer._STORE_KEY\n\t\t);\n\t\tif (Is.undefined(buffers)) {\n\t\t\tbuffers = {};\n\t\t\tSharedStore.set(SharedObjectBuffer._STORE_KEY, buffers);\n\t\t}\n\t\treturn buffers;\n\t}\n\n\t/**\n\t * Lazily load 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 (SharedObjectBuffer._workerThreadsModule === undefined) {\n\t\t\ttry {\n\t\t\t\tSharedObjectBuffer._workerThreadsModule = await import(\"node:worker_threads\");\n\t\t\t} catch {\n\t\t\t\tSharedObjectBuffer._workerThreadsModule = null;\n\t\t\t}\n\t\t}\n\t\treturn SharedObjectBuffer._workerThreadsModule;\n\t}\n}\n"]}
|
package/dist/types/index.d.ts
CHANGED
|
@@ -27,6 +27,7 @@ export * from "./helpers/randomHelper.js";
|
|
|
27
27
|
export * from "./helpers/stringHelper.js";
|
|
28
28
|
export * from "./helpers/uint8ArrayHelper.js";
|
|
29
29
|
export * from "./models/coerceType.js";
|
|
30
|
+
export * from "./models/IDuration.js";
|
|
30
31
|
export * from "./models/compressionType.js";
|
|
31
32
|
export * from "./models/healthStatus.js";
|
|
32
33
|
export * from "./models/IComponent.js";
|
|
@@ -47,6 +48,7 @@ export * from "./models/IValidationFailure.js";
|
|
|
47
48
|
export * from "./models/mutexMessageTypes.js";
|
|
48
49
|
export * from "./models/sharedObjectBufferMessageTypes.js";
|
|
49
50
|
export * from "./types/bitString.js";
|
|
51
|
+
export * from "./types/duration.js";
|
|
50
52
|
export * from "./types/objectOrArray.js";
|
|
51
53
|
export * from "./types/singleOccurrenceArray.js";
|
|
52
54
|
export * from "./types/singleOccurrenceArrayDepthHelper.js";
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Represents a duration broken down into its component parts.
|
|
3
|
+
*/
|
|
4
|
+
export interface IDuration {
|
|
5
|
+
/**
|
|
6
|
+
* The number of years.
|
|
7
|
+
*/
|
|
8
|
+
years: number;
|
|
9
|
+
/**
|
|
10
|
+
* The number of months.
|
|
11
|
+
*/
|
|
12
|
+
months: number;
|
|
13
|
+
/**
|
|
14
|
+
* The number of weeks.
|
|
15
|
+
*/
|
|
16
|
+
weeks: number;
|
|
17
|
+
/**
|
|
18
|
+
* The number of days.
|
|
19
|
+
*/
|
|
20
|
+
days: number;
|
|
21
|
+
/**
|
|
22
|
+
* The number of hours.
|
|
23
|
+
*/
|
|
24
|
+
hours: number;
|
|
25
|
+
/**
|
|
26
|
+
* The number of minutes.
|
|
27
|
+
*/
|
|
28
|
+
minutes: number;
|
|
29
|
+
/**
|
|
30
|
+
* The number of seconds.
|
|
31
|
+
*/
|
|
32
|
+
seconds: number;
|
|
33
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { IDuration } from "../models/IDuration.js";
|
|
2
|
+
/**
|
|
3
|
+
* Helper methods for working with ISO 8601 durations.
|
|
4
|
+
*/
|
|
5
|
+
export declare class Duration {
|
|
6
|
+
/**
|
|
7
|
+
* Runtime name for the class.
|
|
8
|
+
*/
|
|
9
|
+
static readonly CLASS_NAME: string;
|
|
10
|
+
/**
|
|
11
|
+
* Parse an ISO 8601 duration string into its component parts.
|
|
12
|
+
* @param value The string to parse.
|
|
13
|
+
* @returns The parsed duration, or undefined if the string is not a valid ISO 8601 duration.
|
|
14
|
+
*/
|
|
15
|
+
static parse(value: string): IDuration | undefined;
|
|
16
|
+
/**
|
|
17
|
+
* Convert a duration object to an ISO 8601 duration string.
|
|
18
|
+
* @param duration The duration to convert.
|
|
19
|
+
* @returns The ISO 8601 duration string (e.g. "P1Y2M3DT4H5M6S").
|
|
20
|
+
*/
|
|
21
|
+
static toString(duration: IDuration): string;
|
|
22
|
+
/**
|
|
23
|
+
* Convert a duration object to total seconds.
|
|
24
|
+
* Year and month components use the average values 365.25 days and 30.4375 days.
|
|
25
|
+
* @param duration The duration to convert.
|
|
26
|
+
* @returns The total number of seconds.
|
|
27
|
+
*/
|
|
28
|
+
static toSeconds(duration: IDuration): number;
|
|
29
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { CoerceType } from "../models/coerceType.js";
|
|
2
|
+
import type { IDuration } from "../models/IDuration.js";
|
|
2
3
|
/**
|
|
3
4
|
* Coerce an object from one type to another.
|
|
4
5
|
*/
|
|
@@ -51,6 +52,14 @@ export declare class Coerce {
|
|
|
51
52
|
* @returns The coerced time, or undefined if the value cannot be coerced.
|
|
52
53
|
*/
|
|
53
54
|
static time(value: unknown): Date | undefined;
|
|
55
|
+
/**
|
|
56
|
+
* Coerce the value to a duration object.
|
|
57
|
+
* Accepts ISO 8601 duration strings (e.g. "PT1H", "P1Y2M3DT4H5M6S") or numeric
|
|
58
|
+
* values already expressed as seconds (stored in the seconds field).
|
|
59
|
+
* @param value The value to coerce.
|
|
60
|
+
* @returns The duration object, or undefined if the value cannot be coerced.
|
|
61
|
+
*/
|
|
62
|
+
static duration(value: unknown): IDuration | undefined;
|
|
54
63
|
/**
|
|
55
64
|
* Coerce the value to an object.
|
|
56
65
|
* @param value The value to coerce.
|
|
@@ -254,4 +254,12 @@ export declare class Guards {
|
|
|
254
254
|
* @throws GuardError If the value does not match the assertion.
|
|
255
255
|
*/
|
|
256
256
|
static uuidV7(source: string, property: string, value: unknown, format?: "standard" | "compact"): asserts value is string;
|
|
257
|
+
/**
|
|
258
|
+
* Is the property a valid ISO 8601 duration string.
|
|
259
|
+
* @param source The source of the error.
|
|
260
|
+
* @param property The name of the property.
|
|
261
|
+
* @param value The value to test.
|
|
262
|
+
* @throws GuardError If the value does not match the assertion.
|
|
263
|
+
*/
|
|
264
|
+
static duration(source: string, property: string, value: unknown): asserts value is string;
|
|
257
265
|
}
|
package/dist/types/utils/is.d.ts
CHANGED
|
@@ -227,4 +227,10 @@ export declare class Is {
|
|
|
227
227
|
* @returns True if the value is a uuidV7 string.
|
|
228
228
|
*/
|
|
229
229
|
static uuidV7(value: unknown, format?: "standard" | "compact"): value is string;
|
|
230
|
+
/**
|
|
231
|
+
* Is the value a valid ISO 8601 duration string.
|
|
232
|
+
* @param value The value to test.
|
|
233
|
+
* @returns True if the value is a valid ISO 8601 duration string.
|
|
234
|
+
*/
|
|
235
|
+
static duration(value: unknown): value is string;
|
|
230
236
|
}
|
package/docs/changelog.md
CHANGED
|
@@ -1,5 +1,39 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.0.4-next.12](https://github.com/iotaledger/twin-framework/compare/core-v0.0.4-next.11...core-v0.0.4-next.12) (2026-06-18)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### Features
|
|
7
|
+
|
|
8
|
+
* add duration support ([#362](https://github.com/iotaledger/twin-framework/issues/362)) ([24dbe8b](https://github.com/iotaledger/twin-framework/commit/24dbe8b208eb127a52024cb219d31d27731e9ae3))
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
### Dependencies
|
|
12
|
+
|
|
13
|
+
* The following workspace dependencies were updated
|
|
14
|
+
* dependencies
|
|
15
|
+
* @twin.org/nameof bumped from 0.0.4-next.11 to 0.0.4-next.12
|
|
16
|
+
* devDependencies
|
|
17
|
+
* @twin.org/nameof-transformer bumped from 0.0.4-next.11 to 0.0.4-next.12
|
|
18
|
+
* @twin.org/nameof-vitest-plugin bumped from 0.0.4-next.11 to 0.0.4-next.12
|
|
19
|
+
|
|
20
|
+
## [0.0.4-next.11](https://github.com/iotaledger/twin-framework/compare/core-v0.0.4-next.10...core-v0.0.4-next.11) (2026-06-15)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
### Bug Fixes
|
|
24
|
+
|
|
25
|
+
* mutex locking ([d5af3c1](https://github.com/iotaledger/twin-framework/commit/d5af3c1e66070f86408ba1410809689c6d22958b))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
### Dependencies
|
|
29
|
+
|
|
30
|
+
* The following workspace dependencies were updated
|
|
31
|
+
* dependencies
|
|
32
|
+
* @twin.org/nameof bumped from 0.0.4-next.10 to 0.0.4-next.11
|
|
33
|
+
* devDependencies
|
|
34
|
+
* @twin.org/nameof-transformer bumped from 0.0.4-next.10 to 0.0.4-next.11
|
|
35
|
+
* @twin.org/nameof-vitest-plugin bumped from 0.0.4-next.10 to 0.0.4-next.11
|
|
36
|
+
|
|
3
37
|
## [0.0.4-next.10](https://github.com/iotaledger/twin-framework/compare/core-v0.0.4-next.9...core-v0.0.4-next.10) (2026-06-15)
|
|
4
38
|
|
|
5
39
|
|
|
@@ -190,6 +190,30 @@ The coerced time, or undefined if the value cannot be coerced.
|
|
|
190
190
|
|
|
191
191
|
***
|
|
192
192
|
|
|
193
|
+
### duration() {#duration}
|
|
194
|
+
|
|
195
|
+
> `static` **duration**(`value`): [`IDuration`](../interfaces/IDuration.md) \| `undefined`
|
|
196
|
+
|
|
197
|
+
Coerce the value to a duration object.
|
|
198
|
+
Accepts ISO 8601 duration strings (e.g. "PT1H", "P1Y2M3DT4H5M6S") or numeric
|
|
199
|
+
values already expressed as seconds (stored in the seconds field).
|
|
200
|
+
|
|
201
|
+
#### Parameters
|
|
202
|
+
|
|
203
|
+
##### value
|
|
204
|
+
|
|
205
|
+
`unknown`
|
|
206
|
+
|
|
207
|
+
The value to coerce.
|
|
208
|
+
|
|
209
|
+
#### Returns
|
|
210
|
+
|
|
211
|
+
[`IDuration`](../interfaces/IDuration.md) \| `undefined`
|
|
212
|
+
|
|
213
|
+
The duration object, or undefined if the value cannot be coerced.
|
|
214
|
+
|
|
215
|
+
***
|
|
216
|
+
|
|
193
217
|
### object() {#object}
|
|
194
218
|
|
|
195
219
|
> `static` **object**\<`T`\>(`value`): `T` \| `undefined`
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Class: Duration
|
|
2
|
+
|
|
3
|
+
Helper methods for working with ISO 8601 durations.
|
|
4
|
+
|
|
5
|
+
## Constructors
|
|
6
|
+
|
|
7
|
+
### Constructor
|
|
8
|
+
|
|
9
|
+
> **new Duration**(): `Duration`
|
|
10
|
+
|
|
11
|
+
#### Returns
|
|
12
|
+
|
|
13
|
+
`Duration`
|
|
14
|
+
|
|
15
|
+
## Properties
|
|
16
|
+
|
|
17
|
+
### CLASS\_NAME {#class_name}
|
|
18
|
+
|
|
19
|
+
> `readonly` `static` **CLASS\_NAME**: `string`
|
|
20
|
+
|
|
21
|
+
Runtime name for the class.
|
|
22
|
+
|
|
23
|
+
## Methods
|
|
24
|
+
|
|
25
|
+
### parse() {#parse}
|
|
26
|
+
|
|
27
|
+
> `static` **parse**(`value`): [`IDuration`](../interfaces/IDuration.md) \| `undefined`
|
|
28
|
+
|
|
29
|
+
Parse an ISO 8601 duration string into its component parts.
|
|
30
|
+
|
|
31
|
+
#### Parameters
|
|
32
|
+
|
|
33
|
+
##### value
|
|
34
|
+
|
|
35
|
+
`string`
|
|
36
|
+
|
|
37
|
+
The string to parse.
|
|
38
|
+
|
|
39
|
+
#### Returns
|
|
40
|
+
|
|
41
|
+
[`IDuration`](../interfaces/IDuration.md) \| `undefined`
|
|
42
|
+
|
|
43
|
+
The parsed duration, or undefined if the string is not a valid ISO 8601 duration.
|
|
44
|
+
|
|
45
|
+
***
|
|
46
|
+
|
|
47
|
+
### toString() {#tostring}
|
|
48
|
+
|
|
49
|
+
> `static` **toString**(`duration`): `string`
|
|
50
|
+
|
|
51
|
+
Convert a duration object to an ISO 8601 duration string.
|
|
52
|
+
|
|
53
|
+
#### Parameters
|
|
54
|
+
|
|
55
|
+
##### duration
|
|
56
|
+
|
|
57
|
+
[`IDuration`](../interfaces/IDuration.md)
|
|
58
|
+
|
|
59
|
+
The duration to convert.
|
|
60
|
+
|
|
61
|
+
#### Returns
|
|
62
|
+
|
|
63
|
+
`string`
|
|
64
|
+
|
|
65
|
+
The ISO 8601 duration string (e.g. "P1Y2M3DT4H5M6S").
|
|
66
|
+
|
|
67
|
+
***
|
|
68
|
+
|
|
69
|
+
### toSeconds() {#toseconds}
|
|
70
|
+
|
|
71
|
+
> `static` **toSeconds**(`duration`): `number`
|
|
72
|
+
|
|
73
|
+
Convert a duration object to total seconds.
|
|
74
|
+
Year and month components use the average values 365.25 days and 30.4375 days.
|
|
75
|
+
|
|
76
|
+
#### Parameters
|
|
77
|
+
|
|
78
|
+
##### duration
|
|
79
|
+
|
|
80
|
+
[`IDuration`](../interfaces/IDuration.md)
|
|
81
|
+
|
|
82
|
+
The duration to convert.
|
|
83
|
+
|
|
84
|
+
#### Returns
|
|
85
|
+
|
|
86
|
+
`number`
|
|
87
|
+
|
|
88
|
+
The total number of seconds.
|
|
@@ -1181,3 +1181,39 @@ The format of the uuidV7, either standard or compact.
|
|
|
1181
1181
|
#### Throws
|
|
1182
1182
|
|
|
1183
1183
|
GuardError If the value does not match the assertion.
|
|
1184
|
+
|
|
1185
|
+
***
|
|
1186
|
+
|
|
1187
|
+
### duration() {#duration}
|
|
1188
|
+
|
|
1189
|
+
> `static` **duration**(`source`, `property`, `value`): `asserts value is string`
|
|
1190
|
+
|
|
1191
|
+
Is the property a valid ISO 8601 duration string.
|
|
1192
|
+
|
|
1193
|
+
#### Parameters
|
|
1194
|
+
|
|
1195
|
+
##### source
|
|
1196
|
+
|
|
1197
|
+
`string`
|
|
1198
|
+
|
|
1199
|
+
The source of the error.
|
|
1200
|
+
|
|
1201
|
+
##### property
|
|
1202
|
+
|
|
1203
|
+
`string`
|
|
1204
|
+
|
|
1205
|
+
The name of the property.
|
|
1206
|
+
|
|
1207
|
+
##### value
|
|
1208
|
+
|
|
1209
|
+
`unknown`
|
|
1210
|
+
|
|
1211
|
+
The value to test.
|
|
1212
|
+
|
|
1213
|
+
#### Returns
|
|
1214
|
+
|
|
1215
|
+
`asserts value is string`
|
|
1216
|
+
|
|
1217
|
+
#### Throws
|
|
1218
|
+
|
|
1219
|
+
GuardError If the value does not match the assertion.
|
|
@@ -881,3 +881,25 @@ The format of the UUIDv7 string.
|
|
|
881
881
|
`value is string`
|
|
882
882
|
|
|
883
883
|
True if the value is a uuidV7 string.
|
|
884
|
+
|
|
885
|
+
***
|
|
886
|
+
|
|
887
|
+
### duration() {#duration}
|
|
888
|
+
|
|
889
|
+
> `static` **duration**(`value`): `value is string`
|
|
890
|
+
|
|
891
|
+
Is the value a valid ISO 8601 duration string.
|
|
892
|
+
|
|
893
|
+
#### Parameters
|
|
894
|
+
|
|
895
|
+
##### value
|
|
896
|
+
|
|
897
|
+
`unknown`
|
|
898
|
+
|
|
899
|
+
The value to test.
|
|
900
|
+
|
|
901
|
+
#### Returns
|
|
902
|
+
|
|
903
|
+
`value is string`
|
|
904
|
+
|
|
905
|
+
True if the value is a valid ISO 8601 duration string.
|
package/docs/reference/index.md
CHANGED
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
- [StringHelper](classes/StringHelper.md)
|
|
31
31
|
- [Uint8ArrayHelper](classes/Uint8ArrayHelper.md)
|
|
32
32
|
- [BitString](classes/BitString.md)
|
|
33
|
+
- [Duration](classes/Duration.md)
|
|
33
34
|
- [Url](classes/Url.md)
|
|
34
35
|
- [Urn](classes/Urn.md)
|
|
35
36
|
- [AsyncCache](classes/AsyncCache.md)
|
|
@@ -47,6 +48,7 @@
|
|
|
47
48
|
## Interfaces
|
|
48
49
|
|
|
49
50
|
- [IComponent](interfaces/IComponent.md)
|
|
51
|
+
- [IDuration](interfaces/IDuration.md)
|
|
50
52
|
- [IError](interfaces/IError.md)
|
|
51
53
|
- [IHealth](interfaces/IHealth.md)
|
|
52
54
|
- [II18nShared](interfaces/II18nShared.md)
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# Interface: IDuration
|
|
2
|
+
|
|
3
|
+
Represents a duration broken down into its component parts.
|
|
4
|
+
|
|
5
|
+
## Properties
|
|
6
|
+
|
|
7
|
+
### years {#years}
|
|
8
|
+
|
|
9
|
+
> **years**: `number`
|
|
10
|
+
|
|
11
|
+
The number of years.
|
|
12
|
+
|
|
13
|
+
***
|
|
14
|
+
|
|
15
|
+
### months {#months}
|
|
16
|
+
|
|
17
|
+
> **months**: `number`
|
|
18
|
+
|
|
19
|
+
The number of months.
|
|
20
|
+
|
|
21
|
+
***
|
|
22
|
+
|
|
23
|
+
### weeks {#weeks}
|
|
24
|
+
|
|
25
|
+
> **weeks**: `number`
|
|
26
|
+
|
|
27
|
+
The number of weeks.
|
|
28
|
+
|
|
29
|
+
***
|
|
30
|
+
|
|
31
|
+
### days {#days}
|
|
32
|
+
|
|
33
|
+
> **days**: `number`
|
|
34
|
+
|
|
35
|
+
The number of days.
|
|
36
|
+
|
|
37
|
+
***
|
|
38
|
+
|
|
39
|
+
### hours {#hours}
|
|
40
|
+
|
|
41
|
+
> **hours**: `number`
|
|
42
|
+
|
|
43
|
+
The number of hours.
|
|
44
|
+
|
|
45
|
+
***
|
|
46
|
+
|
|
47
|
+
### minutes {#minutes}
|
|
48
|
+
|
|
49
|
+
> **minutes**: `number`
|
|
50
|
+
|
|
51
|
+
The number of minutes.
|
|
52
|
+
|
|
53
|
+
***
|
|
54
|
+
|
|
55
|
+
### seconds {#seconds}
|
|
56
|
+
|
|
57
|
+
> **seconds**: `number`
|
|
58
|
+
|
|
59
|
+
The number of seconds.
|