webdriver | Cell 11 | Cell 13 | Search

The getSessions function retrieves available sessions for a given client, filtering out inactive sessions based on the lastActive timestamp. It uses a multi-step process to verify sessions, including loading sessions, filtering, mapping, running promises, and deduplicating results.

Cell 12

var importer = require('../Core');
var readSessions = importer.import("load webdriver sessions");
var {
    verifySession,
    lockPromise,
    updateOrAddSession
} = importer.import("verify session");

var TIMEOUT = 10000;

function getSessions(client, inactive = false) {
    const sessions = readSessions();
    const original = client.sessionId;
    var active = [].concat(sessions)
        .filter(session => typeof session[1] !== 'undefined'
                && session[1] !== null && session[1].length > 0);
    if(inactive) {
        active = active.filter(session => (new Date()).getTime() - session[0] > TIMEOUT);
    }
    var cancelled = false;
    return importer.runAllPromises(active.map(session => (resolve) => {
        if(cancelled) {
            return resolve();
        }
        console.log(session);
        return verifySession(client, session)
            .catch(e => console.log(e))
            .then(r => {
                // only try to find 1 decent session
                if(inactive && typeof r !== 'undefined') {
                    cancelled = true;
                }
                return resolve(r);
            })
    }))
        .then(available => {
            client.sessionId = original;
            return available
                .filter(sess => typeof sess !== 'undefined' && sess !== null)
                .filter((elem, pos, arr) => arr.indexOf(elem) === pos)
        })
}

module.exports = {
    getSessions,
    lockPromise,
    updateOrAddSession
};

What the code could have been:

const Core = require('../Core');

const {
  loadWebDriverSessions,
  verifySession,
  lockPromise,
  updateOrAddSession
} = Core;

const DEFAULT_TIMEOUT = 10000;

/**
 * Retrieves active WebDriver sessions from storage.
 * If inactive sessions are requested, filters sessions by last usage date.
 *
 * @param {object} client - WebDriver client instance
 * @param {boolean} inactive - If true, returns inactive sessions (default: false)
 * @param {number} [timeout=DEFAULT_TIMEOUT] - Session inactivity timeout in milliseconds
 * @returns {Promise<object[]>} Resolved array of available sessions
 */
function getSessions(client, inactive = false, timeout = DEFAULT_TIMEOUT) {
  // Retrieve all sessions from storage
  const sessions = loadWebDriverSessions();

  // Keep track of original client ID
  const originalSessionId = client.sessionId;

  // Filter sessions based on input parameters
  const sessionsToCheck = sessions.filter(session => {
    // Only consider sessions with a valid timestamp
    return typeof session[0]!== 'undefined' && session[0]!== null;
  });

  // Filter inactive sessions by last usage date
  if (inactive) {
    sessionsToCheck.filter(session => {
      // Consider the session inactive if its last usage date is older than the specified timeout
      return (new Date()).getTime() - session[0] > timeout;
    });
  }

  // Use Promise.all to check all sessions concurrently
  const checkSessions = sessionsToCheck.map(session => {
    // Create a resolve function to be used when verifying the session
    const resolve = (result) => {
      // If a decent session is found, cancel further checks
      if (inactive && result!== undefined && result!== null) {
        return Promise.resolve();
      }
      // Otherwise, return the resolved result
      return Promise.resolve(result);
    };

    // Return a function that verifies the session and resolves the promise
    return () => verifySession(client, session)
     .catch((error) => console.error(error))
     .then((result) => resolve(result));
  });

  // Use lockPromise to prevent concurrent access to the sessions
  return lockPromise(checkSessions, timeout)
   .then((results) => {
      // Restore the original client session ID
      client.sessionId = originalSessionId;

      // Remove duplicates and filter out null/undefined values
      return results.filter((result) => result!== undefined && result!== null).filter((elem, pos, arr) => arr.indexOf(elem) === pos);
    });
}

module.exports = {
  getSessions,
  lockPromise,
  updateOrAddSession
};

Function Breakdown

getSessions Function

Parameters

Description

The getSessions function retrieves available sessions for a given client. It filters sessions based on their lastActive timestamp and returns the verified sessions.

Steps

  1. Load sessions using readSessions() function.
  2. Filter active sessions based on the inactive flag. If inactive is true, filter sessions older than the specified TIMEOUT (10 seconds).
  3. Map sessions to a new array of promises, each resolving with a verified session.
  4. Run all promises using importer.runAllPromises() and wait for the results.
  5. If an inactive session is found, cancel the rest of the promises.
  6. Filter and deduplicate the verified sessions.

Exports