"use strict";
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2024-2026 Gracker (Chris)
// This file is part of SmartPerfetto. See LICENSE for details.
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.executeTraceProcessorHttpRpcRaw = executeTraceProcessorHttpRpcRaw;
exports.executeTraceProcessorHttpRpcSql = executeTraceProcessorHttpRpcSql;
const http_1 = __importDefault(require("http"));
const traceProcessorProtobuf_1 = require("./traceProcessorProtobuf");
async function executeTraceProcessorHttpRpcRaw(request) {
    const hostname = request.hostname || '127.0.0.1';
    const path = request.path || '/query';
    return new Promise((resolve, reject) => {
        let settled = false;
        let req = null;
        let wallClockTimer;
        const finish = (error, body) => {
            if (settled)
                return;
            settled = true;
            clearTimeout(wallClockTimer);
            if (error) {
                reject(error);
            }
            else {
                resolve(body || Buffer.alloc(0));
            }
        };
        wallClockTimer = setTimeout(() => {
            req?.destroy();
            finish(new Error('Query timeout'));
        }, request.timeoutMs);
        if (typeof wallClockTimer.unref === 'function') {
            wallClockTimer.unref();
        }
        req = http_1.default.request({
            hostname,
            port: request.port,
            path,
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-protobuf',
                'Content-Length': request.body.length,
            },
            timeout: request.timeoutMs,
        }, (res) => {
            const chunks = [];
            res.on('data', chunk => chunks.push(Buffer.from(chunk)));
            res.on('end', () => {
                const responseBody = Buffer.concat(chunks);
                if (res.statusCode !== 200) {
                    finish(new Error(`HTTP ${res.statusCode}: ${responseBody.toString('utf8')}`));
                    return;
                }
                finish(null, responseBody);
            });
        });
        req.on('error', error => {
            finish(error);
        });
        req.on('timeout', () => {
            req?.destroy();
            finish(new Error('Query timeout'));
        });
        req.write(request.body);
        req.end();
    });
}
async function executeTraceProcessorHttpRpcSql(request) {
    const startTime = Date.now();
    const response = await executeTraceProcessorHttpRpcRaw({
        hostname: request.hostname,
        port: request.port,
        path: '/query',
        body: (0, traceProcessorProtobuf_1.encodeQueryArgs)(request.sql),
        timeoutMs: request.timeoutMs,
    });
    const parsed = (0, traceProcessorProtobuf_1.decodeQueryResult)(response);
    return {
        columns: parsed.columnNames,
        rows: parsed.rows,
        durationMs: Date.now() - startTime,
        ...(parsed.error ? { error: parsed.error } : {}),
    };
}
//# sourceMappingURL=traceProcessorHttpRpcClient.js.map