webdriver | Cell 10 | Cell 12 | Search

This Node.js module manages lock files and session data, providing functions to lock/unlock files and update or add sessions to a JSON file. The module uses the lockfile, fs, and path modules, as well as a custom ../Core module, to perform its operations.

Cell 11

var lockFile = require('lockfile');
var fs = require('fs');
var path = require('path');
var importer = require('../Core');
var readSessions = importer.import("load webdriver sessions");

var TOKEN_DIR = path.join(process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE, '.credentials');
var SESSIONS_PATH = path.join(TOKEN_DIR, 'sessions.json');
var INIT_WAIT = 60000; // 36 * session test time * number of simultaneous sessions
var UPDATE_WAIT = 1000;

// lock / unlock
// insert - posibility of a session being reused, but sych session starts
function lockPromise(lock = true, init = false) {
    console.log((init ? 'init' : 'update') + ' - ' + (lock ? 'locking' : 'unlocking'));
    return new Promise((resolve, reject) => {
        const func = lock ? lockFile.lock : lockFile.unlock;
        const p = SESSIONS_PATH + '.' + (init ? 'init' : 'update') + '.lock';
        return func.apply(lockFile, [p].concat(lock ? [{
            stale: init ? INIT_WAIT : UPDATE_WAIT,
            wait: init ? INIT_WAIT : UPDATE_WAIT
        }] : []).concat([(err) => {
            if(err) {
                return reject(err);
            }
            console.log((init ? 'init' : 'update') + ' - ' + (lock ? 'lock' : 'unlock'));
            resolve();
        }]));
    });
}

function updateOrAddSession(currentSession) {
    const sessions = readSessions();
    if(!currentSession) {
        return sessions;
    }
    // don't update sessions while scanning
    const updateSession = sessions.filter(s => s[1] === currentSession)[0];
    if(typeof updateSession !== 'undefined') {
        console.log('update ' + currentSession);
        updateSession[0] = (new Date()).getTime();
    } else {
        console.log('insert ' + currentSession);
        const oldSession = sessions[sessions.length] = [];
        // http://www.english.upenn.edu/~jenglish/English104/tzara.html
        oldSession[1] = currentSession;
        oldSession[0] = (new Date()).getTime();
    }
    fs.writeFileSync(
        SESSIONS_PATH,
        JSON.stringify(sessions, null, 4));
    return sessions;
}
module.exports = {
    updateOrAddSession,
    lockPromise
};

What the code could have been:

const lockfile = require('lockfile');
const fs = require('fs');
const path = require('path');
const { loadWebdriverSessions } = require('../Core');

const DEFAULT_SESSION_DIR = path.join(process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE, '.credentials');
const SESSIONS_FILE = path.join(DEFAULT_SESSION_DIR,'sessions.json');
const INIT_WAIT = 60 * 1000; // 60 seconds (1 minute)
const UPDATE_WAIT = 1 * 1000; // 1 second

const getLockFilePath = (init) => {
    return `${SESSIONS_FILE}.${init? 'init' : 'update'}.lock`;
};

const lockFile = (lock, init) => {
    const lockFilePath = getLockFilePath(init);
    const stale = init? INIT_WAIT : UPDATE_WAIT;
    const wait = init? INIT_WAIT : UPDATE_WAIT;

    return new Promise((resolve, reject) => {
        const func = lock? lockfile.lock : lockfile.unlock;
        func(lockFilePath, [stale, wait], (err) => {
            if (err) {
                return reject(err);
            }
            console.log(`${init? 'init' : 'update'} - ${lock? 'lock' : 'unlock'}`);
            resolve();
        });
    });
};

const loadSessionsOrAddNew = (currentSession) => {
    try {
        const sessions = loadWebdriverSessions();
        if (!currentSession) {
            return sessions;
        }

        const updateSession = sessions.find((session) => session[1] === currentSession);
        if (updateSession) {
            console.log(`update ${currentSession}`);
            updateSession[0] = Date.now();
        } else {
            console.log(`insert ${currentSession}`);
            const newSession = sessions.push([Date.now(), currentSession]);
            sessions[sessions.length - 1][0] = Date.now();
        }

        fs.writeFileSync(SESSIONS_FILE, JSON.stringify(sessions, null, 4));
        return sessions;
    } catch (error) {
        console.error('Error loading sessions:', error);
        throw error;
    }
};

module.exports = {
    lockFile,
    loadSessionsOrAddNew,
};

Overview

This code is a Node.js module that manages a lock file and a sessions JSON file to keep track of active sessions. It provides two main functions: lockPromise and updateOrAddSession.

Dependencies

Constants

Functions

lockPromise(lock, init)

The function creates a lock or unlock operation using the lockfile module and returns a promise that resolves when the operation is complete. If an error occurs, the promise is rejected.

updateOrAddSession(currentSession)

The function reads the sessions JSON file, checks if the current session already exists, and updates or adds it accordingly. If the session is not found, a new entry is created. The updated sessions are written back to the JSON file using fs.writeFileSync.

Note that the code uses some unusual variable names and formatting conventions, which may not be consistent with standard JavaScript coding practices.