"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.UsageTracker = void 0; var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _toolingLog = require("@kbn/tooling-log"); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ /* eslint-disable max-classes-per-file */ /** * Keep track of usage of stuff. Example: can track how many time a given utility/function was called. * * ** Should not be used for production code ** */ class UsageTracker { constructor({ logger = new _toolingLog.ToolingLog(), dumpOnProcessExit = false, maxRecordsPerType = 25 } = {}) { (0, _defineProperty2.default)(this, "records", {}); (0, _defineProperty2.default)(this, "options", void 0); this.options = { logger, dumpOnProcessExit, maxRecordsPerType }; try { if (dumpOnProcessExit && process && process.once) { ['SIGINT', 'exit', 'uncaughtException', 'unhandledRejection'].forEach(event => { process.once(event, () => { // }); }); } } catch (err) { logger.debug(`Unable to setup 'dumpOnProcessExit': ${err.message}`); } } create(id) { var _this$records$id; this.records[id] = (_this$records$id = this.records[id]) !== null && _this$records$id !== void 0 ? _this$records$id : { count: 0, records: [] }; const maxRecords = this.options.maxRecordsPerType; const usageRecord = new UsageRecord(id); const usageForId = this.records[id]; usageForId.count++; usageForId.records.push(usageRecord); if (usageForId.records.length > maxRecords) { usageForId.records.splice(0, usageForId.records.length - maxRecords); } return usageRecord; } toJSON() { return Object.values(this.records).map(({ records }) => records).flat().map(record => record.toJSON()); } toString() { return JSON.stringify(this.toJSON()); } dump(logger) { (logger !== null && logger !== void 0 ? logger : this.options.logger).info(Object.entries(this.records).map(([key, { count, records: usageRecords }]) => { return ` [${key}] Invoked ${count} times. Last ${this.options.maxRecordsPerType}: ${usageRecords.map(record => { return record.toString(); }).join('\n ')} `; }).join('\n')); } } exports.UsageTracker = UsageTracker; class UsageRecord { constructor(id) { (0, _defineProperty2.default)(this, "start", new Date().toISOString()); (0, _defineProperty2.default)(this, "finish", ''); (0, _defineProperty2.default)(this, "status", 'pending'); (0, _defineProperty2.default)(this, "error", void 0); this.id = id; } set(status, error) { this.finish = new Date().toISOString(); this.error = error; } toJSON() { const { id, start, finish, status, error } = this; return { id, start, finish, status, ...(error ? { error } : {}) }; } toString() { return JSON.stringify(this.toJSON()); } }