@comake/skl-js-engine
Version:
Standard Knowledge Language Javascript Engine
92 lines • 3.21 kB
JavaScript
;
/**
* Utility for polling operations with timeout
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.pollUntilSuccess = exports.pollUntilTrue = void 0;
const logger_1 = require("../../../logger");
/**
* Poll a condition function until it returns true or timeout is reached
*
* @param conditionFn - Function that returns true when condition is met, false to continue polling
* @param options - Polling configuration
* @param timeoutErrorMessage - Custom error message for timeout
* @returns Promise that resolves when condition is met or rejects on timeout
*
* @example
* ```typescript
* // Wait for process to be ready
* await pollUntilTrue(
* () => process.isRunning(),
* { timeout: 5000, interval: 100 },
* 'Process failed to start'
* );
* ```
*/
async function pollUntilTrue(conditionFn, options, timeoutErrorMessage) {
const { timeout, interval = 100, initialDelay = 0 } = options;
const startTime = Date.now();
// Initial delay if specified
if (initialDelay > 0) {
await new Promise((resolve) => setTimeout(resolve, initialDelay));
}
while (Date.now() - startTime < timeout) {
try {
// Condition met!
if (await conditionFn()) {
return;
}
}
catch (error) {
logger_1.Logger.getInstance().error(new Error(`${timeoutErrorMessage} after ${timeout}ms`), error);
}
// Wait before next check
await new Promise((resolve) => setTimeout(resolve, interval));
}
// Timeout reached
throw new Error(`${timeoutErrorMessage} after ${timeout}ms`);
}
exports.pollUntilTrue = pollUntilTrue;
/**
* Poll an async operation until it succeeds or timeout is reached
*
* @param operationFn - Async function to retry until it succeeds
* @param options - Polling configuration
* @param timeoutErrorMessage - Custom error message for timeout
* @returns Promise that resolves with operation result or rejects on timeout
*
* @example
* ```typescript
* // Wait for ping to succeed
* await pollUntilSuccess(
* () => client.ping(),
* { timeout: 10000, interval: 500 },
* 'Failed to connect'
* );
* ```
*/
async function pollUntilSuccess(operationFn, options, timeoutErrorMessage) {
const { timeout, interval = 100, initialDelay = 0 } = options;
const startTime = Date.now();
// Initial delay if specified
if (initialDelay > 0) {
await new Promise((resolve) => setTimeout(resolve, initialDelay));
}
while (Date.now() - startTime < timeout) {
try {
// Success!
return await operationFn();
}
catch (error) {
logger_1.Logger.getInstance().error(new Error(`${timeoutErrorMessage} after ${timeout}ms`), error);
// Operation failed, continue polling if we have time
if (Date.now() - startTime < timeout) {
await new Promise((resolve) => setTimeout(resolve, interval));
}
}
}
// Timeout reached
throw new Error(`${timeoutErrorMessage} after ${timeout}ms`);
}
exports.pollUntilSuccess = pollUntilSuccess;
//# sourceMappingURL=PollingUtils.js.map