#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const node_crypto_1 = require("node:crypto");
const env_1 = require("../env");
const logger_1 = require("../services/logger");
const mysql_session_manager_1 = require("./mysql-session-manager");
async function main() {
    installStderrLogSink();
    const token = (0, node_crypto_1.randomBytes)(24).toString('hex');
    const manager = new mysql_session_manager_1.MySQLSessionManager({
        token,
        testRunTs: env_1.Env.TEST_RUN_TS,
        poolSize: env_1.Env.TSF_TEST_MYSQL_SESSION_POOL_SIZE ? Number(env_1.Env.TSF_TEST_MYSQL_SESSION_POOL_SIZE) : undefined,
        mysql: {
            host: env_1.Env.MYSQL_HOST,
            port: env_1.Env.MYSQL_PORT ? Number(env_1.Env.MYSQL_PORT) : 3306,
            user: env_1.Env.MYSQL_USER,
            password: env_1.Env.MYSQL_PASSWORD_SECRET
        }
    });
    await manager.start();
    console.log(`TSF_MYSQL_SESSION_MANAGER_READY ${JSON.stringify({ port: manager.port, token })}`);
    let stopping = false;
    const stop = async () => {
        if (stopping)
            return;
        stopping = true;
        await manager.stop();
        process.exit(0);
    };
    process.once('SIGINT', () => void stop());
    process.once('SIGTERM', () => void stop());
}
main().catch(error => {
    console.error(error);
    process.exit(1);
});
function installStderrLogSink() {
    (0, logger_1.setLogSink)(entry => {
        console.error(formatLogEntry(entry));
    });
}
function formatLogEntry(entry) {
    const error = formatLogError(entry.error);
    return `tsf-test mysql: [${entry.message}]${formatLogData(entry.data)}${error}`;
}
function formatLogData(data) {
    if (!data || Object.keys(data).length === 0)
        return '';
    const entries = Object.entries(data)
        .filter(([, value]) => value !== undefined)
        .map(([key, value]) => `${key}=${formatLogValue(value)}`);
    return entries.length ? ` ${entries.join(' ')}` : '';
}
function formatLogError(error) {
    if (!error)
        return '';
    if (error instanceof Error)
        return ` error=${formatLogValue(error.stack ?? error.message)}`;
    return ` error=${formatLogValue(error)}`;
}
function formatLogValue(value) {
    if (typeof value === 'string') {
        return /^[A-Za-z0-9_.:/@+-]+$/.test(value) ? value : JSON.stringify(value);
    }
    if (typeof value === 'number' || typeof value === 'boolean' || value === null)
        return String(value);
    try {
        const formatted = JSON.stringify(value);
        return formatted === undefined ? String(value) : formatted;
    }
    catch {
        return String(value);
    }
}
//# sourceMappingURL=mysql-session-manager-process.js.map