execution-engine
Version:
A TypeScript library for tracing and visualizing code execution workflows.
57 lines (56 loc) • 2.43 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.cacheStoreKey = void 0;
exports.executeCache = executeCache;
const execute_1 = require("./execute");
const crypto_1 = require("../common/utils/crypto");
const functionMetadata_1 = require("../common/utils/functionMetadata");
const mapStore_1 = require("../common/utils/mapStore");
exports.cacheStoreKey = Symbol('execution-engine/cache');
/**
* Caches function results to avoid redundant expensive computations
* If the result is already cached, it returns the cached value; otherwise, it executes the function and stores the result.
*
* This is useful for optimizing expensive computations or API calls by reducing duplicate executions.
* @remarks
* - Errors are thrown immediately and **not cached** to allow retries.
*/
async function executeCache(blockFunction, inputs = [], options) {
const functionMetadata = (0, functionMetadata_1.extractFunctionMetadata)(blockFunction);
const cacheKey = options.cacheKey?.({ metadata: functionMetadata, inputs }) ?? (0, crypto_1.generateHashId)(...inputs);
const bypass = typeof options.bypass === 'function' && !!options.bypass?.({ metadata: functionMetadata, inputs });
const ttl = typeof options.ttl === 'function' ? options.ttl({ metadata: functionMetadata, inputs }) : options.ttl;
let cacheStore;
if (options.cacheManager) {
cacheStore = typeof options.cacheManager === 'function' ? options.cacheManager(this) : options.cacheManager;
}
else {
cacheStore = new mapStore_1.MapCacheStore(this[exports.cacheStoreKey], options.functionId);
}
const cachedValue = (await cacheStore.get(cacheKey));
if (typeof options.onCacheEvent === 'function') {
options.onCacheEvent({
ttl,
metadata: functionMetadata,
inputs,
cacheKey,
isBypassed: !!bypass,
isCached: !!cachedValue,
value: cachedValue
});
}
if (!bypass && cachedValue) {
return cachedValue;
}
else {
return execute_1.execute.bind(this)(blockFunction.bind(this), inputs, [], (res) => {
cacheStore.set(cacheKey, res, ttl);
if (cacheStore.fullStorage) {
this[exports.cacheStoreKey] = cacheStore.fullStorage;
}
return res;
}, (error) => {
throw error;
});
}
}
;