@netlify/content-engine
Version:
41 lines • 1.46 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.createMutex = createMutex;
exports.releaseAllMutexes = releaseAllMutexes;
const get_storage_1 = require("./utils/get-storage");
// Random number to re-check if mutex got released
const DEFAULT_MUTEX_INTERVAL = 3000;
async function waitUntilUnlocked(storage, key, timeout) {
const isUnlocked = await storage.mutex.ifNoExists(key, () => {
storage.mutex.put(key, get_storage_1.LockStatus.Locked);
});
if (isUnlocked) {
return;
}
await new Promise((resolve) => {
setTimeout(() => {
resolve(waitUntilUnlocked(storage, key, timeout));
}, timeout);
});
}
/**
* Creates a mutex, make sure to call `release` when you're done with it.
*
* @param {string} key A unique key
*/
function createMutex(key, timeout = DEFAULT_MUTEX_INTERVAL) {
const storage = (0, get_storage_1.getStorage)((0, get_storage_1.getDatabaseDir)());
const BUILD_ID = global.__GATSBY?.buildId ?? ``;
const prefixedKey = `${BUILD_ID}-${key}`;
return {
acquire: () => waitUntilUnlocked(storage, prefixedKey, timeout),
release: async () => {
await storage.mutex.remove(prefixedKey);
},
};
}
async function releaseAllMutexes() {
const storage = (0, get_storage_1.getStorage)((0, get_storage_1.getDatabaseDir)());
await storage.mutex.clearAsync();
}
//# sourceMappingURL=mutex.js.map
;