synchronous-timeout
v1.0.3
Published
`synchronous-timeout` allows developers to wrap arbitrary synchronous or asynchronous functions so that they can self-abort based on a signal from a worker thread. This is achieved by automatically injecting checks into the function code at the beginning
Downloads
261
Maintainers
Readme
synchronous-timeout
synchronous-timeout
allows developers to wrap arbitrary synchronous or asynchronous functions so that they can self-abort based on a signal from a worker thread. This is achieved by automatically injecting checks into the function code at the beginning of all the function's block statements. When a shared memory byte is set by the worker thread, the running function detects this and aborts its execution.
Key Feature
- Automatic Injection of Abort Checks: Wrap any function to automatically include checks that monitor a shared memory signal. If the signal indicates an abort (set by a worker thread), the function will self-terminate.
Installation
Install via npm:
npm install synchronous-timeout
Usage
injectAbortCheck(fn)
Wraps a function with abort-checking capability. The wrapped function will periodically check a shared memory byte to determine if it should self-abort, as signaled by a worker thread.
Parameters
fn
(Function): The function you want to wrap. This can be any synchronous or asynchronous function.
Returns
- A new function that behaves like the original but will self-abort if the shared memory signal is set.
Example
import { injectAbortCheck } from 'synchronous-timeout';
// Original function
function computePrimes(limit) {
const primes = [];
for (let num = 2; num <= limit; num++) {
let isPrime = true;
for (let factor = 2; factor <= Math.sqrt(num); factor++) {
if (num % factor === 0) {
isPrime = false;
break;
}
}
if (isPrime) primes.push(num);
}
return primes;
}
// Wrap the function to enable aborting
const abortableComputePrimes = injectAbortCheck(computePrimes);
// Start the worker thread to signal an abort after a timeout
// Assume startAbortWorker is a function that starts the worker and sets the abort signal
import { startAbortWorker } from 'synchronous-timeout';
const worker = startAbortWorker(5000); // Abort after 5 seconds
// Use the wrapped function
try {
const primes = abortableComputePrimes(1e7);
console.log('Primes computed:', primes);
} catch (error) {
console.error('Function aborted:', error.message);
} finally {
worker.terminate();
}
In this example:
- The
computePrimes
function is CPU-intensive and may run for a long time. - By wrapping it with
injectAbortCheck
, it will periodically check if it should abort. - A separate worker thread signals an abort by setting a shared memory byte after 5 seconds.
- If the abort signal is set, the function will throw an error and terminate early.
How It Works
- Code Transformation:
injectAbortCheck
converts the original function into a string and uses Babel to inject abort checks at the beginning of each code block (e.g., loops, functions). - Shared Memory Monitoring: The injected checks read a shared byte from a
SharedArrayBuffer
. If the byte indicates an abort signal, the function throws an error. - Worker Thread Signal: A separate worker thread can set the abort signal by modifying the shared memory byte. This allows for asynchronous control over the function's execution.
Example
For a function like this:
async function long_running_code(n) {
let result = 0;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
result += i + j;
if (i % 10 === 0) {
console.log(`Intermediate result at i=${i}, j=${j}: ${result}`);
}
}
}
return result;
}
Code is injected in every block statement, resulting in the following abort-enabled function:
async function long_running_code(n) {
check_abort(); // Injected ABORT check
let result = 0;
for (let i = 0; i < n; i++) {
check_abort(); // Injected ABORT check
for (let j = 0; j < n; j++) {
check_abort(); // Injected ABORT check
result += i + j;
if (i % 10 === 0) {
check_abort(); // Injected ABORT check
console.log(`Intermediate result at i=${i}, j=${j}: ${result}`);
}
}
}
return result;
}
SharedArrayBuffer Compatibility
synchronous-timeout
relies on SharedArrayBuffer
for communication between the main thread and the worker thread. Please note that SharedArrayBuffer
availability depends on the environment and browser support. For more information on compatibility, refer to the MDN documentation on SharedArrayBuffer.
Ensure that your target environment supports SharedArrayBuffer
and that any necessary cross-origin isolation policies are correctly configured.
Notes
- The function wrapping is transparent; you use the wrapped function just like the original.
- The abort mechanism is cooperative. The function checks the abort signal at block-level boundaries, so it won't abort during atomic operations.
- This is particularly useful for long-running synchronous functions where you might need to enforce a timeout.
Limitations
- Granularity of Checks: Abort checks are injected at the beginning of code blocks. Internal blocks that call other (non-abort-injected) functions will abort only at the block level that last supported the check.
- Environment Requirements: Requires an environment that supports
SharedArrayBuffer
and worker threads (e.g., modern browsers with proper cross-origin isolation, Node.js with worker support).
License
ISC License