8.2 KiB · text History 905ae26
import QtQuick

// Thin client for Vigil's Sentry-compatible /api/0 — the surface the
// Android app speaks, authenticated with an API token made under
// Settings → API tokens. Every call takes
// callback(ok, dataOrMessage, network, httpStatus, linkHeader).
QtObject {
    id: vigil

    property string baseUrl: ""
    property string accessToken: ""

    readonly property bool configured: normalizedBase() !== "" && accessToken.trim() !== ""

    function normalizedBase() {
        var url = (baseUrl || "").trim()
        while (url.length > 0 && url.charAt(url.length - 1) === "/") {
            url = url.substring(0, url.length - 1)
        }
        return url
    }

    // ── web links ───────────────────────────────────────────────────────

    function orgUrl(org) {
        return normalizedBase() + "/orgs/" + encodeURIComponent(org)
    }

    function projectUrl(org, project) {
        return orgUrl(org) + "/projects/" + encodeURIComponent(project)
    }

    function cronUrl(org, project, slug) {
        return projectUrl(org, project) + "/monitors/" + encodeURIComponent(slug)
    }

    function uptimeUrl(org, id) {
        return orgUrl(org) + "/uptime/" + encodeURIComponent(id)
    }

    // ── transport ───────────────────────────────────────────────────────

    // QML's XMLHttpRequest ignores `timeout`, and a socket open across a
    // suspend can hang without ever reaching DONE, so every request gets
    // its own watchdog Timer.
    property int timeoutMs: 20000
    property var inFlight: []

    readonly property Component watchdog: Component {
        Timer { repeat: false }
    }

    // Drops every outstanding request without calling back: the caller
    // is starting over and doesn't want stale answers.
    function abortAll() {
        var pending = inFlight
        inFlight = []
        for (var i = 0; i < pending.length; i++) pending[i].cancel()
    }

    // The reason in an error body: Sentry's `detail`, else its first
    // field error (`{"assignedTo": ["Not a member…"]}`).
    function errorMessage(text) {
        try {
            var o = JSON.parse(text)
            if (o && typeof o.detail === "string") return o.detail
            for (var k in o) {
                if (Array.isArray(o[k]) && typeof o[k][0] === "string") return o[k][0]
            }
        } catch (e) {}
        return ""
    }

    function request(method, path, body, callback) {
        if (!configured) {
            var msg = i18n("Set the Vigil address and an API token first")
            if (callback) callback(false, msg, false, 0, "")
            return
        }

        var xhr = new XMLHttpRequest()
        xhr.open(method, normalizedBase() + "/api/0" + path, true)
        xhr.setRequestHeader("Authorization", "Bearer " + accessToken.trim())
        xhr.setRequestHeader("Accept", "application/json")
        if (body !== null && body !== undefined) xhr.setRequestHeader("Content-Type", "application/json")

        var finished = false
        var timer = watchdog.createObject(vigil, { interval: timeoutMs })
        var entry = { cancel: function() { settle(); xhr.abort() } }
        inFlight = inFlight.concat([entry])

        function settle() {
            if (finished) return false
            finished = true
            timer.stop()
            timer.destroy()
            inFlight = inFlight.filter(function(e) { return e !== entry })
            return true
        }

        function fail(message, network, httpStatus) {
            if (!settle()) return
            console.log("Vigil API error:", method, path, message)
            if (callback) callback(false, message, !!network, httpStatus || 0, "")
        }

        timer.triggered.connect(function() {
            fail(i18n("Timed out talking to %1", normalizedBase()), true)
            xhr.abort()
        })
        timer.start()

        xhr.onreadystatechange = function() {
            if (xhr.readyState !== XMLHttpRequest.DONE || finished) return

            if (xhr.status >= 200 && xhr.status < 300) {
                var data = {}
                if (xhr.status !== 204 && xhr.responseText) {
                    try {
                        data = JSON.parse(xhr.responseText)
                    } catch (e) {
                        fail(i18n("Could not read the answer to %1", path), false, xhr.status)
                        return
                    }
                }
                var link = xhr.getResponseHeader("Link") || ""
                if (!settle()) return
                if (callback) callback(true, data, false, xhr.status, link)
                return
            }

            var serverMessage = errorMessage(xhr.responseText)
            if (xhr.status === 0) {
                fail(i18n("Could not reach %1", normalizedBase()), true)
            } else if (xhr.status === 401) {
                fail(i18n("The server didn't accept that token. It may have been revoked."), false, 401)
            } else if (xhr.status === 403) {
                fail(serverMessage || i18n("The token isn't allowed to do that"), false, 403)
            } else if (xhr.status === 404) {
                fail(serverMessage || i18n("Not found"), false, 404)
            } else if (xhr.status >= 500) {
                // A gateway error while the server restarts reads as offline.
                fail(serverMessage || i18n("The server said %1", xhr.status), true, xhr.status)
            } else {
                fail(serverMessage || i18n("The server said %1", xhr.status), false, xhr.status)
            }
        }

        xhr.send(body !== null && body !== undefined ? JSON.stringify(body) : null)
    }

    function q(params) {
        var parts = []
        for (var i = 0; i < params.length; i++) {
            if (params[i][1] === undefined || params[i][1] === null || params[i][1] === "") continue
            parts.push(encodeURIComponent(params[i][0]) + "=" + encodeURIComponent(params[i][1]))
        }
        return parts.length ? "?" + parts.join("&") : ""
    }

    function seg(s) {
        return encodeURIComponent(s)
    }

    // ── calls ───────────────────────────────────────────────────────────

    // {user: {id, email, name}, auth: {label, scopes}}: who the token is.
    function whoami(callback) {
        request("GET", "/", null, callback)
    }

    // [{id, slug, name}]
    function organizations(callback) {
        request("GET", "/organizations/", null, callback)
    }

    // [{id (numeric, for ?project=), slug, name, platform}]
    function projects(org, callback) {
        request("GET", "/organizations/" + seg(org) + "/projects/", null, callback)
    }

    // One page of issues across the organization, or of `projectIds`
    // (numeric ids). `query` is the web's search syntax.
    function issues(org, query, projectIds, cursor, perPage, callback) {
        var params = [["query", query], ["per_page", perPage || 100], ["cursor", cursor]]
        for (var i = 0; i < (projectIds || []).length; i++) params.push(["project", projectIds[i]])
        request("GET", "/organizations/" + seg(org) + "/issues/" + q(params), null, callback)
    }

    function latestEvent(org, project, id, callback) {
        request("GET", "/projects/" + seg(org) + "/" + seg(project) + "/issues/" + seg(id) + "/events/latest/", null, callback)
    }

    // Sentry's bulk mutate (event:write): {status} or {assignedTo}. 200
    // with what changed; 204 when none of the ids is there any more.
    function updateIssues(org, project, ids, update, callback) {
        var params = ids.map(function(id) { return ["id", id] })
        request("PUT", "/projects/" + seg(org) + "/" + seg(project) + "/issues/" + q(params), update, callback)
    }

    function monitors(org, callback) {
        request("GET", "/organizations/" + seg(org) + "/monitors/", null, callback)
    }

    function uptime(org, callback) {
        request("GET", "/organizations/" + seg(org) + "/uptime/", null, callback)
    }
}