"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.otel = exports.MultiSpanExporter = exports.MultiMetricExporter = void 0;
var os = require("os");
var Config_1 = require("./Config");
var openflow_api_1 = require("@openiap/openflow-api");
var license_file_1 = require("./license-file");
var tracing_1 = require("@opentelemetry/tracing");
var metrics_1 = require("@opentelemetry/metrics");
var exporter_collector_grpc_1 = require("@opentelemetry/exporter-collector-grpc");
var api_1 = require("@opentelemetry/api");
var core_1 = require("@opentelemetry/core");
var api_2 = require("@opentelemetry/api");
var Logger_1 = require("./Logger");
var MultiMetricExporter = /** @class */ (function () {
    function MultiMetricExporter(exporters) {
        this.exporters = exporters;
    }
    MultiMetricExporter.prototype.export = function (record, callback) {
        this.exporters.forEach(function (exporter) {
            exporter.export(record, callback);
        });
    };
    MultiMetricExporter.prototype.shutdown = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, Promise.all(this.exporters.map(function (e) { return e.shutdown(); }))];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    return MultiMetricExporter;
}());
exports.MultiMetricExporter = MultiMetricExporter;
var MultiSpanExporter = /** @class */ (function () {
    function MultiSpanExporter(exporters) {
        this.exporters = exporters;
    }
    MultiSpanExporter.prototype.export = function (spans, callback) {
        this.exporters.forEach(function (exporter) {
            exporter.export(spans, callback);
        });
    };
    MultiSpanExporter.prototype.shutdown = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, Promise.all(this.exporters.map(function (e) { return e.shutdown(); }))];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    return MultiSpanExporter;
}());
exports.MultiSpanExporter = MultiSpanExporter;
var otel = /** @class */ (function () {
    function otel() {
        this.default_boundaries = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 25, 50, 75, 100];
        this.defaultlabels = {};
    }
    otel.configure = function () {
        var hasLicense = true;
        try {
            license_file_1.LicenseFile.validate();
        }
        catch (error) {
            hasLicense = false;
            Logger_1.Logger.instanse.info(error.message ? error.message : error);
        }
        if (otel.instance != null)
            return otel.instance;
        if (license_file_1.LicenseFile.validlicense) {
            if (openflow_api_1.NoderedUtil.IsNullEmpty(license_file_1.LicenseFile.data.domain)) {
                Logger_1.Logger.instanse.info("License valid to " + license_file_1.LicenseFile.data.expirationDate);
            }
            else {
                Logger_1.Logger.instanse.info("License valid for " + license_file_1.LicenseFile.data.domain + " until the " + license_file_1.LicenseFile.data.expirationDate);
            }
        }
        otel.instance = new otel();
        // diag.setLogger(d, DiagLogLevel.ALL);
        // diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.ALL);
        // diag.setLogger(new DiagConsoleLogger());
        // if (Config.otel_debug_log) diag.setLogLevel(DiagLogLevel.ALL);
        if (Config_1.Config.otel_debug_log)
            api_1.diag.setLogger(new api_1.DiagConsoleLogger(), api_1.DiagLogLevel.ALL);
        var metricExporters = [];
        var spanExporters = [];
        // console.log("otel_servicename=", Config.otel_servicename);
        // console.log("otel_metric_url", Config.otel_metric_url);
        console.log("otel_trace_url", Config_1.Config.otel_trace_url);
        if (hasLicense) {
            if (!openflow_api_1.NoderedUtil.IsNullEmpty(Config_1.Config.otel_metric_url) && !openflow_api_1.NoderedUtil.IsNullEmpty(Config_1.Config.otel_servicename)) {
                metricExporters.push(new exporter_collector_grpc_1.CollectorMetricExporter({
                    serviceName: Config_1.Config.otel_servicename,
                    url: Config_1.Config.otel_metric_url
                }));
            }
            if (!openflow_api_1.NoderedUtil.IsNullEmpty(Config_1.Config.otel_trace_url) && !openflow_api_1.NoderedUtil.IsNullEmpty(Config_1.Config.otel_servicename)) {
                spanExporters.push(new exporter_collector_grpc_1.CollectorTraceExporter({
                    serviceName: Config_1.Config.otel_servicename,
                    url: Config_1.Config.otel_trace_url
                }));
            }
        }
        if (Config_1.Config.enable_analytics) {
            //     url: "https://exporter.stats.openiap.io/v1/metrics"
            //     url: "https://exporter.stats.openiap.io/v1/trace"
            metricExporters.push(new exporter_collector_grpc_1.CollectorMetricExporter({
                serviceName: Config_1.Config.otel_servicename,
                url: "http://otel.stats.openiap.io:80"
            }));
            spanExporters.push(new exporter_collector_grpc_1.CollectorTraceExporter({
                serviceName: Config_1.Config.otel_servicename,
                url: "http://otel.stats.openiap.io:80"
            }));
        }
        else {
            console.log("analytics disabled, please consider enabling this, to help us improve the product!");
            console.warn("analytics disabled, please consider enabling this, to help us improve the product!");
        }
        otel.instance.setdefaultlabels();
        if (spanExporters.length > 0) {
            var traceExporter = new MultiSpanExporter(spanExporters);
            otel.instance.traceprovider = new tracing_1.BasicTracerProvider();
            otel.instance.traceprovider.addSpanProcessor(new tracing_1.BatchSpanProcessor(traceExporter, {
                maxExportBatchSize: 512,
                scheduledDelayMillis: Config_1.Config.otel_trace_interval,
            }));
            // otel.instance.traceprovider.addSpanProcessor(new SimpleSpanProcessor(traceExporter));
            otel.instance.traceprovider.register();
        }
        if (metricExporters.length > 0) {
            var metricExporter = new MultiMetricExporter(metricExporters);
            otel.instance.meterprovider = new metrics_1.MeterProvider({
                exporter: metricExporter,
                interval: Config_1.Config.otel_metric_interval
            });
            otel.instance.meter = otel.instance.meterprovider.getMeter(Config_1.Config.otel_servicename);
            otel.nodejs_heap_size_used_bytes = otel.instance.meter.createUpDownSumObserver('nodejs_heap_size_used_bytes', {
                description: 'Process heap size used from Node.js in bytes'
            });
            otel.nodejs_heap_size_total_bytes = otel.instance.meter.createUpDownSumObserver('nodejs_heap_size_total_bytes', {
                description: 'Process heap size from Node.js in bytes'
            });
            if (otel.perfTimeout)
                clearInterval(otel.perfTimeout);
            otel.perfTimeout = setInterval(function () {
                var memUsage = process.memoryUsage();
                otel.nodejs_heap_size_used_bytes.bind(__assign(__assign({}, otel.instance.defaultlabels), { domain: Config_1.Config.domain })).update(memUsage.heapUsed);
                otel.nodejs_heap_size_total_bytes.bind(__assign(__assign({}, otel.instance.defaultlabels), { domain: Config_1.Config.domain })).update(memUsage.heapTotal);
            }, Config_1.Config.otel_metric_interval);
        }
        return otel.instance;
    };
    otel.prototype.startSpan = function (name) {
        if (openflow_api_1.NoderedUtil.IsNullUndefinded(otel.instance))
            return otel.fakespan;
        if (openflow_api_1.NoderedUtil.IsNullUndefinded(otel.instance.traceprovider))
            return otel.fakespan;
        var span = api_2.default.trace.getTracer('default').startSpan(name);
        span.setAttributes(this.defaultlabels);
        return span;
    };
    otel.prototype.startSubSpan = function (name, parent) {
        if (openflow_api_1.NoderedUtil.IsNullUndefinded(parent))
            return this.startSpan(name);
        var ctx = api_1.setSpan(api_2.default.context.active(), parent);
        var span = api_2.default.trace.getTracer('default').startSpan(name, undefined, ctx);
        // span.setAttributes(otel.defaultlabels);
        return span;
    };
    otel.prototype.endSpan = function (span) {
        try {
            if (!openflow_api_1.NoderedUtil.IsNullUndefinded(span))
                span.end();
        }
        catch (error) {
            console.error(error);
        }
    };
    otel.prototype.startTimer = function () {
        return core_1.hrTime();
    };
    otel.prototype.endTimer = function (startTime, recorder, labels) {
        if (openflow_api_1.NoderedUtil.IsNullUndefinded(otel.instance))
            return undefined;
        if (openflow_api_1.NoderedUtil.IsNullUndefinded(recorder))
            return undefined;
        var performanceTimeOriginms = core_1.hrTimeToMilliseconds(startTime);
        var Milliseconds = (core_1.hrTimeToMilliseconds(core_1.hrTime()) - performanceTimeOriginms);
        var Seconds = Milliseconds / 1000;
        recorder.bind(__assign(__assign({}, this.defaultlabels), labels)).record(Seconds);
        if (Config_1.Config.log_otel_times)
            Logger_1.Logger.instanse.debug(JSON.stringify(labels) + " " + Seconds);
    };
    otel.prototype.setdefaultlabels = function () {
        var hostname = (Config_1.Config.getEnv("HOSTNAME", undefined) || os.hostname()) || "unknown";
        var crypto = require('crypto');
        this.defaultlabels["ofid"] = license_file_1.LicenseFile.ofid();
        console.log("ofid=" + license_file_1.LicenseFile.ofid());
        var uniqueid = crypto.createHash('md5').update(license_file_1.LicenseFile.ofid() + hostname).digest("hex");
        console.log("id=" + uniqueid);
        this.defaultlabels[uniqueid] = uniqueid;
        if (!openflow_api_1.NoderedUtil.IsNullEmpty(hostname)) {
            this.defaultlabels["hostname"] = hostname;
        }
    };
    otel.fakespan = {
        context: function () { return undefined; },
        setAttribute: function () { return undefined; },
        setAttributes: function () { return undefined; },
        addEvent: function () { return undefined; },
        setStatus: function () { return undefined; },
        updateName: function () { return undefined; },
        end: function () { return undefined; },
        isRecording: function () { return undefined; },
        recordException: function () { return undefined; },
    };
    return otel;
}());
exports.otel = otel;
//# sourceMappingURL=otel.js.map