Skip to content

FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.

13.2 KB
Raw Blame
// QuantLibClient.cpp — Shared QuantLib API HTTP client.

#include "services/quantlib/QuantLibClient.h"

#include "auth/AuthManager.h"
#include "core/config/AppConfig.h"
#include "core/logging/Logger.h"
#include "storage/cache/CacheManager.h"

#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QPointer>
#include <QThread>
#include <QUrl>

static constexpr int kRefDataTtlSec = 60 * 60; // 1 hour — static reference data

namespace fincept::services {

static constexpr const char* kQuantLibClientTag = "QuantLibClient";

// A hung connection otherwise leaves the screen's EXECUTE button on
// "COMPUTING..." forever (Qt has no default transfer timeout).
static constexpr int kQuantLibTransferTimeoutMs = 60 * 1000;

// Endpoints that use GET (no request body).
static const QStringList GET_ENDPOINTS = {
    "core/types/currencies",           "core/types/frequencies",        "scheduling/calendar/list",
    "scheduling/daycount/conventions", "scheduling/adjustment/methods",
};

// Endpoints that take body fields as URL query params (POST with empty body).
static const QStringList QUERY_PARAM_ENDPOINTS = {
    "core/types/spread/from-bps",
    // Declared in the OpenAPI spec as `parameters: in: query` with no request body — a JSON body is
    // ignored by the server and every call 422'd on the missing `pd` / `pre_money`.
    "analysis/valuation/credit/expected-loss",
    "analysis/valuation/credit/rating-pd",
    "analysis/valuation/startup/dilution",
};

bool QuantLibClient::is_get_endpoint(const QString& endpoint) {
    return GET_ENDPOINTS.contains(endpoint);
}

bool QuantLibClient::is_query_param_endpoint(const QString& endpoint) {
    return QUERY_PARAM_ENDPOINTS.contains(endpoint);
}

// ── Singleton ────────────────────────────────────────────────────────────────

QuantLibClient::QuantLibClient(QObject* parent) : QObject(parent) {}

QuantLibClient& QuantLibClient::instance() {
    static QuantLibClient inst;
    return inst;
}

QNetworkAccessManager* QuantLibClient::network() {
    // Created lazily on this object's thread (call() guarantees that), owned via
    // parent. Replaces one QNAM per request — each of which had its own HTTP
    // thread and paid a full TCP + TLS handshake to the API host every call.
    if (!nam_)
        nam_ = new QNetworkAccessManager(this);
    return nam_;
}

// ── Request builder ──────────────────────────────────────────────────────────

static QNetworkRequest build_request(const QString& endpoint, const QJsonObject& query_params = {}) {
    QString url = fincept::AppConfig::instance().api_base_url() + "/quantlib/" + endpoint;

    if (!query_params.isEmpty()) {
        QStringList parts;
        for (auto it = query_params.begin(); it != query_params.end(); ++it)
            parts << (QString::fromLatin1(QUrl::toPercentEncoding(it.key())) + "=" +
                      QString::fromLatin1(QUrl::toPercentEncoding(it.value().toVariant().toString())));
        url += "?" + parts.join("&");
    }

    QNetworkRequest req{QUrl(url)};
    req.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    req.setRawHeader("Accept", "application/json");
    req.setRawHeader("User-Agent", "FinceptTerminal/4.0.0");
    req.setTransferTimeout(kQuantLibTransferTimeoutMs);
    // The QNAM is shared across calls now; keep its cookie jar out of the
    // exchange, exactly as with the per-request QNAM it replaced.
    req.setAttribute(QNetworkRequest::CookieLoadControlAttribute, QNetworkRequest::Manual);
    req.setAttribute(QNetworkRequest::CookieSaveControlAttribute, QNetworkRequest::Manual);

    auto& auth_mgr = auth::AuthManager::instance();
    if (auth_mgr.is_authenticated())
        req.setRawHeader("X-API-Key", auth_mgr.session().api_key.toUtf8());

    return req;
}

// ── HTTP error text ──────────────────────────────────────────────────────────

// Qt reports every 4xx/5xx as a transport error, so parse_response() (and its
// 422 handling) never saw the body and users got "Error transferring ...:
// server replied: Unprocessable Entity" instead of the FastAPI message naming
// the offending field. Prefer the server's own explanation, fall back to Qt's.
static QString quantlib_http_error_text(const QByteArray& raw, const QString& transport_error) {
    const QJsonDocument doc = QJsonDocument::fromJson(raw);
    if (!doc.isObject())
        return transport_error;
    const QJsonObject obj = doc.object();

    const QJsonValue detail = obj.value("detail");
    if (detail.isArray()) {
        QStringList lines;
        for (const auto& item : detail.toArray()) {
            const QJsonObject d = item.toObject();
            const QJsonArray loc = d.value("loc").toArray();
            const QString field = loc.isEmpty() ? QString() : loc.last().toVariant().toString();
            const QString msg = d.value("msg").toString();
            if (!msg.isEmpty())
                lines << (field.isEmpty() ? msg : field + ": " + msg);
        }
        if (!lines.isEmpty())
            return "Validation error: " + lines.join('\n');
    } else if (detail.isString() && !detail.toString().isEmpty()) {
        return detail.toString();
    }

    // Billing/auth failures (401/402) arrive as {"message": {"message": "...", ...}}.
    const QJsonValue mv = obj.value("message");
    const QString message = mv.isObject() ? mv.toObject().value("message").toString() : mv.toString();
    return message.isEmpty() ? transport_error : message;
}

// ── Response parser ──────────────────────────────────────────────────────────

mcp::ToolResult QuantLibClient::parse_response(int http_status, const QByteArray& raw) {
    QJsonParseError parse_err;
    auto doc = QJsonDocument::fromJson(raw, &parse_err);

    if (parse_err.error != QJsonParseError::NoError) {
        return mcp::ToolResult::fail(
            QString("JSON parse error (HTTP %1): %2").arg(http_status).arg(parse_err.errorString()));
    }

    // FastAPI 422 validation error: {"detail": [...]}
    if (http_status == 422 && doc.isObject()) {
        auto obj = doc.object();
        if (obj.contains("detail")) {
            QString msg;
            auto detail = obj["detail"];
            if (detail.isArray()) {
                for (const auto& item : detail.toArray()) {
                    auto d = item.toObject();
                    QString loc = d["loc"].toArray().last().toString();
                    msg += loc + ": " + d["msg"].toString() + "\n";
                }
            } else {
                msg = detail.toString();
            }
            return mcp::ToolResult::fail("Validation error: " + msg.trimmed());
        }
    }

    if (!doc.isObject()) {
        // Top-level array or scalar — return as-is in data
        if (doc.isArray())
            return mcp::ToolResult::ok_data(doc.array());
        return mcp::ToolResult::fail(QString("Unexpected response (HTTP %1)").arg(http_status));
    }

    auto obj = doc.object();

    // API envelope: {"success": bool, "message": "...", "data": <payload>}
    if (obj.contains("success")) {
        if (!obj["success"].toBool()) {
            QString msg = obj["message"].toString();
            if (msg.isEmpty())
                msg = QString("API error (HTTP %1)").arg(http_status);
            return mcp::ToolResult::fail(msg);
        }
        // Unwrap data payload
        auto payload = obj.value("data");
        QString message = obj.value("message").toString();
        return mcp::ToolResult::ok(message, payload);
    }

    // No envelope — return raw object
    return mcp::ToolResult::ok_data(obj);
}

// ── Async call ───────────────────────────────────────────────────────────────

void QuantLibClient::call(const QString& endpoint, const QJsonObject& body, QuantLibCallback callback) {
    // The shared QNAM lives on this object's thread and must only be used there.
    if (QThread::currentThread() != thread()) {
        QMetaObject::invokeMethod(
            this, [this, endpoint, body, callback]() { call(endpoint, body, callback); }, Qt::QueuedConnection);
        return;
    }

    // Cache GET endpoints (static reference data) and query-param endpoints
    const bool cacheable = is_get_endpoint(endpoint) || is_query_param_endpoint(endpoint);
    if (cacheable) {
        QString cache_key = "quantlib:" + endpoint;
        if (!body.isEmpty())
            cache_key += ":" + QString::fromUtf8(QJsonDocument(body).toJson(QJsonDocument::Compact));

        const QVariant cached = fincept::CacheManager::instance().get(cache_key);
        if (!cached.isNull()) {
            auto doc = QJsonDocument::fromJson(cached.toString().toUtf8());
            mcp::ToolResult result =
                doc.isObject() ? mcp::ToolResult::ok_data(doc.object()) : mcp::ToolResult::ok_data(doc.array());
            callback(result);
            return;
        }

        QNetworkAccessManager* nam = network();
        QNetworkReply* reply = nullptr;
        if (is_get_endpoint(endpoint)) {
            reply = nam->get(build_request(endpoint));
        } else {
            reply = nam->post(build_request(endpoint, body), QByteArray("{}"));
        }

        QPointer<QuantLibClient> self = this;
        connect(reply, &QNetworkReply::finished, this, [self, reply, endpoint, cache_key, callback]() {
            reply->deleteLater();
            if (!self)
                return;
            if (reply->error() != QNetworkReply::NoError) {
                const QString err = quantlib_http_error_text(reply->readAll(), reply->errorString());
                LOG_ERROR(kQuantLibClientTag, "Network error on " + endpoint + ": " + err);
                auto fail = mcp::ToolResult::fail(err);
                // Status lets the screen tell 401/402/403 apart (sign in / out of
                // credits / needs Pro) instead of a generic service error.
                fail.data = QJsonObject{
                    {"http_status", reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()}};
                callback(fail);
                return;
            }
            int http_status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
            auto raw = reply->readAll();
            auto result = parse_response(http_status, raw);
            if (result.success) {
                // Serialize the data payload for caching
                QString to_cache;
                if (result.data.isObject())
                    to_cache = QString::fromUtf8(QJsonDocument(result.data.toObject()).toJson(QJsonDocument::Compact));
                else if (result.data.isArray())
                    to_cache = QString::fromUtf8(QJsonDocument(result.data.toArray()).toJson(QJsonDocument::Compact));
                if (!to_cache.isEmpty())
                    fincept::CacheManager::instance().put(cache_key, QVariant(to_cache), kRefDataTtlSec, "quantlib");
            }
            LOG_DEBUG(
                kQuantLibClientTag,
                QString("HTTP %1 — %2 — %3").arg(http_status).arg(endpoint).arg(result.success ? "OK" : result.error));
            callback(result);
        });
        return;
    }

    // Non-cacheable POST endpoints
    auto req = build_request(endpoint);
    QByteArray data = QJsonDocument(body).toJson(QJsonDocument::Compact);
    auto* reply = network()->post(req, data);

    QPointer<QuantLibClient> self = this;
    connect(reply, &QNetworkReply::finished, this, [self, reply, endpoint, callback]() {
        reply->deleteLater();

        if (!self)
            return;

        if (reply->error() != QNetworkReply::NoError) {
            const QString err = quantlib_http_error_text(reply->readAll(), reply->errorString());
            LOG_ERROR(kQuantLibClientTag, "Network error on " + endpoint + ": " + err);
            auto fail = mcp::ToolResult::fail(err);
            fail.data = QJsonObject{{"http_status", reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()}};
            callback(fail);
            return;
        }

        int http_status = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
        auto raw = reply->readAll();
        auto result = parse_response(http_status, raw);

        LOG_DEBUG(
            kQuantLibClientTag,
            QString("HTTP %1 — %2 — %3").arg(http_status).arg(endpoint).arg(result.success ? "OK" : result.error));

        callback(result);
    });
}

// NOTE: call_sync() used to live here. It had zero call sites and parked the
// calling thread in an unbounded `loop.exec()` with no timeout — a permanent
// UI-freeze hazard for whoever reached for it next. Deleted; use the
// callback-based call() above. Its declaration in QuantLibClient.h can go too.

} // namespace fincept::services