"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const tape_1 = __importDefault(require("tape-promise/tape"));
const uuid_1 = require("uuid");
const jose_1 = require("jose");
const cactus_common_1 = require("@hyperledger/cactus-common");
const cactus_core_api_1 = require("@hyperledger/cactus-core-api");
const public_api_1 = require("../../../main/typescript/public-api");
const public_api_2 = require("../../../main/typescript/public-api");
const log = cactus_common_1.LoggerProvider.getOrCreate({
    level: "INFO",
    label: "logger-test",
});
const util_1 = require("util");
const fs_1 = require("fs");
const child_process_1 = require("child_process");
const shell_exec = util_1.promisify(child_process_1.exec);
const artilleryScriptLocation = "./packages/cactus-cmd-api-server/src/test/resources/artillery/benchmark-script.yaml";
const logLevel = "INFO";
tape_1.default("Start API server, and run Artillery benchmark test.", async (t) => {
    const keyPair = await jose_1.JWK.generate("EC", "secp256k1", { use: "sig" }, true);
    const keyPairPem = keyPair.toPEM(true);
    const db = {
        cactusNode: [],
        consortium: [],
        consortiumMember: [],
        ledger: [],
        pluginInstance: [],
    };
    log.info("Generating Config...");
    const configService = new public_api_1.ConfigService();
    const apiServerOptions = configService.newExampleConfig();
    apiServerOptions.authorizationProtocol = public_api_1.AuthorizationProtocol.NONE;
    apiServerOptions.configFile = "";
    apiServerOptions.apiCorsDomainCsv = "*";
    apiServerOptions.apiPort = 4000;
    apiServerOptions.cockpitPort = 0;
    apiServerOptions.apiTlsEnabled = false;
    apiServerOptions.logLevel = "info";
    apiServerOptions.plugins = [
        {
            packageName: "@hyperledger/cactus-plugin-keychain-memory",
            type: cactus_core_api_1.PluginImportType.Local,
            options: {
                instanceId: uuid_1.v4(),
                keychainId: uuid_1.v4(),
                logLevel,
            },
        },
        {
            packageName: "@hyperledger/cactus-plugin-consortium-manual",
            type: cactus_core_api_1.PluginImportType.Local,
            options: {
                instanceId: uuid_1.v4(),
                keyPairPem: keyPairPem,
                consortiumDatabase: db,
            },
        },
    ];
    const config = configService.newExampleConfigConvict(apiServerOptions);
    log.info("Creating API Server...");
    const apiServer = new public_api_1.ApiServer({
        config: config.getProperties(),
    });
    log.info("Starting API Server...");
    const startResponse = apiServer.start();
    tape_1.default.onFinish(() => {
        apiServer.shutdown();
    });
    await t.doesNotReject(startResponse, "failed to start API server with dynamic plugin imports configured for it...");
    t.ok(startResponse, "startResponse truthy OK");
    const addressInfoApi = (await startResponse).addressInfoApi;
    const protocol = apiServerOptions.apiTlsEnabled ? "https" : "http";
    const { address, port } = addressInfoApi;
    const apiHost = `${protocol}://${address}:${port}`;
    const clientConfig = new public_api_1.Configuration({ basePath: apiHost });
    const apiClient = new public_api_2.DefaultApi(clientConfig);
    const res = await apiClient.getPrometheusExporterMetricsV1();
    t.equal(res.status, 200);
    // Sets apihost in process env variables to artillery script can read it.
    process.env.apiHost = apiHost;
    await fireArtilleryCommand(t);
    // Reading in Artillery JSON output
    let report = null;
    try {
        const jsonString = fs_1.readFileSync("./report.json");
        report = JSON.parse(jsonString.toString());
        log.debug(report);
    }
    catch (err) {
        log.error(`Could not parse the artillery report JSON from the file system`, err);
    }
    if (report == null) {
        t.fail("Test failed, cannot find Artillery report.");
    }
    else {
        const avgLatency = report.aggregate.latency.median;
        log.info(`Average Latency: ${avgLatency}`);
        t.assert(avgLatency < 5, "Average latency should be less than 10");
        // Removing report after processing.
        try {
            fs_1.unlinkSync("./report.json");
        }
        catch (err) {
            log.error(`Could not remove report.json from filesystem.`, err);
        }
    }
});
async function fireArtilleryCommand(t) {
    try {
        const artilleryCommand = `artillery run ${artilleryScriptLocation} --output report.json`;
        await shell_exec(artilleryCommand);
    }
    catch (err) {
        log.error(`Failed to run artillery execution.`, err);
        t.fail(`Test failed. Err: ${err}`);
    }
}
//# sourceMappingURL=data:application/json;base64, 