All files / src/modules/implementations/database database-rebuild-lock.js

100% Statements 37/37
90% Branches 9/10
100% Functions 3/3
100% Lines 37/37

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 3854x 54x 784x 784x 784x 1x 1x 784x 245x 245x 245x 245x 247x 247x 247x 247x 3x 3x 3x 3x 2x 2x 247x 244x 244x 244x 244x 244x 244x 244x 244x 245x 784x 784x 784x 784x 54x  
'use strict';
module.exports = ({ core: { publicErrors: { createError, errorCodes }, }, external: { fs, processRuntime, systemClock }, }) => {
    const LOCK_TIMEOUT_MILLISECONDS = 5_000;
    const RETRY_INTERVAL_MILLISECONDS = 25;
    function lockTimeout(databasePath) {
        return createError(errorCodes.DATABASE, `Timed out waiting for the Ledlight database rebuild lock at ${databasePath}.lock`);
    }
    function withRebuildLock(databasePath, operation) {
        const lockPath = `${databasePath}.lock`;
        const deadline = systemClock.now() + LOCK_TIMEOUT_MILLISECONDS;
        let descriptor;
        while (descriptor === undefined) {
            try {
                descriptor = fs.openSync(lockPath, 'wx');
            }
            catch (error) {
                if (!(typeof error === 'object' && error !== null && 'code' in error && error.code === 'EEXIST'))
                    throw error;
                if (systemClock.now() >= deadline)
                    throw lockTimeout(databasePath);
                systemClock.sleep(RETRY_INTERVAL_MILLISECONDS);
            }
        }
        try {
            fs.writeFileSync(descriptor, `${processRuntime.pid()}\n`);
            return operation();
        }
        finally {
            fs.closeSync(descriptor);
            fs.rmSync(lockPath, { force: true });
        }
    }
    return {
        withRebuildLock,
        $$private: { LOCK_TIMEOUT_MILLISECONDS, RETRY_INTERVAL_MILLISECONDS },
    };
};