/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
'use strict';

const fs = require('fs');
const path = require('path');
const v8 = require('v8');
const logger = require('../core/logger')('contrast:heapDump');

/**
 * @param {string} localPath location from config.path
 */
const writeHeapSnapshot = function writeHeapSnapshot(localPath) {
  const dumpPath = path.join(process.cwd(), localPath);

  fs.mkdir(dumpPath, { recursive: true }, (err) => {
    if (err) {
      logger.error('Unable to create directory for heap snapshots: %o', err);
      return;
    }

    // create dump at ${path}/${time}.heapdump
    const filename = path.format({
      dir: dumpPath,
      name: `${Date.now()}-contrast`,
      ext: '.heapsnapshot',
    });

    logger.info('Writing heap snapshot at %s', filename);
    v8.writeHeapSnapshot(filename);
  });
};

/**
 * setup x heap dumps to be created every y seconds after z seconds.
 * @param {Object} config config blob from config/options.js
 * @param {boolean} config.enable
 * @param {string} config.path
 * @param {number} config.count x
 * @param {number} config.window_ms y
 * @param {number} config.delay_ms z
 */
const init = function init(config) {
  if (!config.enable) return;

  setTimeout(() => {
    let count = 0;

    const interval = setInterval(() => {
      writeHeapSnapshot(config.path);
      count++;

      if (count === config.count) {
        clearInterval(interval);
      }
    }, config.window_ms);
  }, config.delay_ms).unref();
};

module.exports = { writeHeapSnapshot, init };
