execution-engine
Version:
A TypeScript library for tracing and visualizing code execution workflows.
50 lines (49 loc) • 2.64 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.executeMemoize = executeMemoize;
const execute_1 = require("./execute");
const executionMemoization_model_1 = require("../common/models/executionMemoization.model");
const crypto_1 = require("../common/utils/crypto");
const functionMetadata_1 = require("../common/utils/functionMetadata");
/**
* Executes a function with memoization to prevent redundant executions.
* The result is stored temporarily and cleared after a short delay.
*
* @param blockFunction - The function to execute and memoize.
* @param inputs - Arguments used to generate a unique memoization key.
* @param options - Additional options.
* @returns The memoized result or a newly computed value.
*
* @remarks
* The JavaScript engine may clear the memoized value before another call retrieves it.
* A short delay (e.g., 100ms) ensures that multiple rapid calls can reuse the stored result.
* The expiration is capped at 1000ms for efficiency and to avoid unnecessary memory usage.
*/
function executeMemoize(blockFunction, inputs = [], options) {
const ttl = Math.min(options.ttl ?? executionMemoization_model_1.memoizationDefaultTTL, executionMemoization_model_1.memoizationMaxTTL); // Default short delay and Prevent excessive retention
const memoizationFullStore = (this[executionMemoization_model_1.memoizationKey] ??= new Map());
const memoizationStore = memoizationFullStore.get(options.functionId) ?? new Map();
const inputsHash = (0, crypto_1.generateHashId)(...inputs);
const memoizedValue = memoizationStore.get(inputsHash);
if (typeof options.onMemoizeEvent === 'function') {
const functionMetadata = (0, functionMetadata_1.extractFunctionMetadata)(blockFunction);
options.onMemoizeEvent({ metadata: functionMetadata, inputsHash, isMemoized: !!memoizedValue, value: memoizedValue });
}
if (memoizedValue) {
return memoizedValue;
}
else {
const callResponseOrPromise = execute_1.execute.bind(this)(blockFunction.bind(this), inputs, [], (res) => res, (error) => {
throw error;
});
memoizationStore.set(inputsHash, callResponseOrPromise);
this[executionMemoization_model_1.memoizationKey].set(options.functionId, memoizationStore);
if (callResponseOrPromise instanceof Promise) {
return callResponseOrPromise.finally(() => setTimeout(() => memoizationStore.delete(inputsHash), ttl));
}
else {
setTimeout(() => memoizationStore.delete(inputsHash), ttl);
return callResponseOrPromise;
}
}
}
;