#!/usr/bin/env qore
# -*- mode: qore; indent-tabs-mode: nil -*-

# @file rest example program for the RestClientIo module

/*  Copyright 2013 - 2026 Qore Technologies, s.r.o.

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
*/

%modern

%requires RestClientIo
%requires Swagger
%requires Util
%requires Mime
%requires ConnectionProvider
%requires Logger

%try-module yaml >= 0.5
%define NoYaml
%endtry

%try-module xml >= 1.3
%define NoXml
%endtry

%requires json

%exec-class RestCmd

class RestCmd {
    public {
        hash<auto> opt;
        static Util::TerminalColor color;

        #! program options
        const Opts = {
            "httpver":       "A,http-version=s",
            "conn":          "c,connection=s",
            "nocolor":       "C,no-color",
            "fullex":        "E,full-exception",
            "sendenc":       "e,send-encoding:s",
            "ping":          "g,ping=s",
            "poll_ping":     "G,poll-ping=s",
            "header":        "H,header=s@",
            "output":        "o,output=s",
            "ignoreerr":     "i,ignore-errors",
            "lit":           "l,literal:i+",
            "list":          "L,list",
            "proxy":         "P,proxy-url=s",
            "basepath":      "p,base-path=s",
            "reformat":      "R,reformat",
            "data":          "S,serialization=s",
            "swagger":       "s,swagger=s",
            "to":            "T,timeout=i",
            "token":         "t,token=s",
            "userpass":      "u,userpass=s",
            "verbose":       "v,verbose:i+",
            "verify_cert":   "V,verify-cert",
            "lax":           "X,lax-parsing",
            "example":       "x,example:s",
            "tokentype":     "y,token-type=s",
            "grant_type":    "grant-type=s",
            "client_id":     "client-id=s",
            "client_secret": "client-secret=s",
            "token_url":     "token-url=s",

            "help":          "h,help",
        };

        #! HTTP version to protocol mapping
        const HttpVersionMap = {
            "auto": "auto",
            "1.1": "h1",
            "2.0": "h2",
            "3.0": "h3",
        };

        #! recognized HTTP methods
        const Methods = {
            "GET": True,
            "PUT": True,
            "POST": True,
            "DELETE": True,
            "PATCH": True,
            "OPTIONS": True,
            "HEAD": True,
        };

        #! HTTP method aliases accepted on the command line
        const MethodAliases = {
            "DEL": "DELETE",
        };
    }

    constructor() {
        GetOpt g(Opts);
        opt = g.parse3(\ARGV);

        color = new Util::TerminalColor(!opt.nocolor);

        if (opt.help || (!ARGV[0] && !opt."list" && !opt.ping && !opt.poll_ping)) {
            usage();
        }

        hash<auto> opts;

        if (opt.ping) {
            doPing(opt.ping);
            thread_exit;
        }

        if (opt.poll_ping) {
            doPollPing(opt.poll_ping);
            thread_exit;
        }

        hash<auto> swagger_opts;
        if (opt.lax) {
            swagger_opts = {"parse_flags": LM_ALL};
        }

        if (opt.swagger) {
            opts.validator = SwaggerLoader::fromFile(opt.swagger, swagger_opts);
            if (opt.basepath.val()) {
                opts.validator.setBasePath(opt.basepath);
            }
        } else if (opt.example) {
            error("option -x|--example requires -s|--swagger to provide the schema for generating the example");
        } else if (opt."list") {
            error("option -L|--list requires -s|--swagger to provide the schema for returning the list");
        }

        if (opt."list") {
            printf("URL: %s\n",  opts.validator.getTargetUrl());
            foreach hash h in (opts.validator.getPathOperationHash().pairIterator()) {
                map printf("%s /%s\n", $1.upr(), h.key), h.value;
            }
            thread_exit;
        }

        if (opt.ignoreerr) {
            opts.error_passthru = True;
        }

        *string meth = shift ARGV;
        if (!exists meth) {
            usage();
        }

        *string url = shift ARGV;
        auto body;
        string umeth = MethodAliases{meth.upr()} ?? meth.upr();
        if (!Methods{umeth}) {
            body = url;
            url = meth;
            meth = "GET";
        } else {
            meth = umeth;
            body = shift ARGV;
        }

        if (!url) {
            printf("%s missing URL for REST server\n", color.error("ERROR:"));
            usage();
        }

        if (!opt.conn) {
            string orig_url = url;
            url = get_connection_url(url);
            if (url != orig_url) {
                printf("%s %y url: %y\n", color.info("using connection:"), orig_url, url);
                opt.conn = orig_url;
            }
        }

        if (opts.validator && url !~ /^[a-z]+:\/\//) {
            url = opts.validator.getTargetUrl() + (url !~ /^\// ? "/" : "") + url;
        }

        # get URI path
        hash<UrlInfo> url_info = parse_url(url);

        if (opt.example) {
            doExample(opts, meth, url_info);
            thread_exit;
        }

        # Validate --http-version option
        if (opt.httpver && !HttpVersionMap{opt.httpver}) {
            error("invalid HTTP version %y; valid options: auto, 1.1, 2.0, 3.0", opt.httpver);
        }

        string request_path;
        string rest_url;
        RestClientIo::RestClientIo rest;

        if (opt.conn) {
            try {
                AbstractConnection conn = get_connection(opt.conn);
                if (!(conn instanceof RestConnection)) {
                    stderr.printf("%s connection %y is a %y object; expecting \"RestClient\"; exiting\n",
                        color.error("ERROR:"), opt.conn, conn.className());
                    exit(1);
                }
                if (!exists body) {
                    stderr.printf("%s missing request path\n", color.error("ERROR:"));
                    exit(1);
                }
                request_path = body;
                body = shift ARGV;
                rest = conn.getAsync(False);
                rest_url = conn.url;
            } catch (hash<ExceptionInfo> ex) {
                if (opt.fullex) {
                    stderr.printf("%s\n", get_exception_string(ex));
                } else {
                    stderr.printf("connection %y: %s: %s: %s\n", opt.conn, get_ex_pos(ex), ex.err,
                        ex.desc);
                }
                exit(1);
            }
        } else {
            request_path = url_info.path ?? "";

            opts.url = sprintf("%s://", url_info.protocol);
            if (url_info.username && url_info.password) {
                opts.url += sprintf("%s:%s@", url_info.username, url_info.password);
            }
            opts.url += url_info.host;
            if (url_info.port
                    && ((url_info.port != 80 && url_info.protocol == "http")
                        || (url_info.port != 443 && url_info.protocol == "https"))) {
                opts.url += sprintf(":%d", url_info.port);
            }
            opts.url += "/";

            if (opt.proxy) {
                opts.proxy = opt.proxy;
            }

            if (opt.to) {
                int to = opt.to * 1000;
                opts += {
                    "timeout": to,
                    "connect_timeout": to,
                };
            }

            if (opt.verify_cert) {
                opts.ssl_verify_mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
            }

            # Protocol selection
            if (opt.httpver) {
                opts.protocol = HttpVersionMap{opt.httpver};
            }

            # OAuth2 options
            if (opt.grant_type) {
                opts.oauth2_grant_type = opt.grant_type;
            }
            if (opt.client_id) {
                opts.oauth2_client_id = opt.client_id;
            }
            if (opt.client_secret) {
                opts.oauth2_client_secret = opt.client_secret;
            }
            if (opt.token_url) {
                opts.oauth2_token_url = opt.token_url;
            }

            rest_url = opts.url;
            rest = new RestClientIo::RestClientIo(opts);
        }

        if (opt.token) {
            rest.setToken(opt.tokentype ?? "Bearer", opt.token);
        } else if (opt.userpass) {
            (*string user, *string pass) = (opt.userpass =~ x/^([^:]+)(?::(.*))?$/);
            rest.setUserPassword(user, pass ?? "");
        }

        if (opt.header) {
            hash<string, bool> nh;
            foreach string h in (opt.header) {
                (*string k, auto v) = (h =~ x/([^:]+):(.*)$/);
                trim k;
                trim v;
                if (!k.val()) {
                    stderr.printf("invalid header %y; expecting \"key: value\" format\n", h);
                    exit(1);
                }
                if (nh{k} && v.val() && (exists (auto v0 = rest.getDefaultHeaders(){k}))) {
                    if (v0.typeCode() != NT_LIST) {
                        v0 = (v0,);
                    }
                    v0 += v;
                    v = v0;
                } else {
                    nh{k} = True;
                }
                rest.addDefaultHeaders((k: v));
            }
        }

        if (exists body) {
            try {
                body = parse_to_qore_value_with_yaml(body);
            } catch (hash<ExceptionInfo> ex) {
                error("invalid request body: %s", ex.desc);
            }
        }

        if (opt."data") {
            if (!RestClient::DataSerializationOptions{opt."data"}) {
                error("data serialization option %y is unknown; valid options: %y", opt."data",
                    RestClient::DataSerializationOptions.keys());
            }
            rest.setSerialization(opt."data");
        }

        if (opt.sendenc) {
            if (opt.sendenc === True) {
                opt.sendenc = "deflate";
            } else if (!RestClient::EncodingSupport{opt.sendenc}) {
                error("send encoding option %y is unknown; valid options: %y", opt.sendenc,
                    RestClient::EncodingSupport.keys());
            }
            rest.setSendEncoding(opt.sendenc);
        }

        doRequest(rest, meth, request_path, body, rest_url);
    }

    #! Idempotently percent-encodes characters illegal as-is in a URI request
    /** Preserves existing \c %XX escapes and URI structure (\c '?', \c '&',
        \c '=', \c '/', \c '#', …); re-running on an already-encoded URI is a
        no-op (no double-encoding).  HTTP/2 and HTTP/3 mandate percent-encoded
        URIs at the protocol level and RestClientIo sends the path verbatim,
        so a human-typed path/query (with e.g. spaces or a literal \c '%')
        must be normalized here or it produces a malformed request that the
        server rejects as an opaque \c HTTP3-PEER-CLOSE / connection reset.
    */
    private static string encodeUriRequestSafe(string s) {
        # turn only a lone '%' (not part of a valid %XX escape) into %25 so
        # already-encoded input passes through unchanged
        s = regex_subst(s, "%(?![0-9A-Fa-f]{2})", "%25", RE_Global);
        string out = "";
        int n = s.strlen();
        for (int i = 0; i < n; ++i) {
            int b = s.getByte(i);
            # keep printable ASCII that is legal as-is (incl. structure and
            # the '%' of preserved escapes); percent-encode space, '"', the
            # RFC 3986 "unwise" set, controls/DEL, and all non-ASCII bytes
            if (b >= 0x21 && b <= 0x7e
                && b != 0x22 && b != 0x3c && b != 0x3e && b != 0x5c
                && b != 0x5e && b != 0x60 && b != 0x7b && b != 0x7d
                && b != 0x7c) {
                out += chr(b);
            } else {
                out += sprintf("%%%02X", b);
            }
        }
        return out;
    }

    #! Performs a REST request using RestClientIo (fully async)
    private doRequest(RestClientIo::RestClientIo rest, string meth, string request_path,
            auto body, string rest_url) {
        # HTTP/2 and HTTP/3 mandate percent-encoded URIs at the protocol level
        # (RestClientIo sends the path verbatim); idempotently encode the
        # user-supplied request path/query (no-op if already encoded).
        request_path = RestCmd::encodeUriRequestSafe(request_path);

        hash<RestClient::RestResponseInfo> h;
        try {
            on_error rethrow $1.err, sprintf("%s (using url: %y request path: %y)", $1.desc,
                rest_url, request_path ?? "");
            h = rest.restDoRequest(meth, request_path ?? "", body);

            # Show literal request/response if -l flag set
            if (opt.lit) {
                showRestRequest(h, opt);
                showRestResponse(h, opt);
            }

            if (!opt.lit && !exists opt.output) {
                printf("%Y\n", h.body);
            }
            if (opt.output) {
                auto output_data = h.response_body_raw ?? h.body;
                if (exists output_data) {
                    File f();
                    f.open2(opt.output, O_CREAT | O_TRUNC | O_WRONLY);
                    if (output_data.typeCode() == NT_STRING) {
                        f.write(output_data);
                    } else if (output_data.typeCode() == NT_BINARY) {
                        f.write(output_data);
                    } else {
                        f.write(make_json(output_data));
                    }
                    printf("%s %y; %d byte%s\n", color.success("Saved output to"),
                        opt.output, output_data.size(), output_data.size() == 1 ? "" : "s");
                } else {
                    stderr.printf("%s\n", color.warning("No output to save"));
                }
            }
        } catch (hash<ExceptionInfo> ex) {
            if (opt.fullex) {
                stderr.printf("%s\n", get_exception_string(ex));
            } else if (ex.err == "DESERIALIZATION-ERROR"
                    && h.headers."content-type" == "text/html"
                    && h.response_body_raw) {
                stderr.printf("%s %s\n%s\n", rest_url, request_path,
                    html_decode(h.response_body_raw));
            } else {
                stderr.printf("%s: %s: %s", rest_url, ex.err, ex.desc);
                if (ex.arg) {
                    stderr.print(": ");
                    if (ex.arg.body.typeCode() == NT_STRING) {
                        trim ex.arg.body;
                        stderr.print(ex.arg.body);
                    } else if (ex.arg.typeCode() == NT_STRING) {
                        trim ex.arg;
                        stderr.printf("%y", ex.arg);
                    } else {
                        stderr.printf("%y", ex.arg);
                    }
                }
                stderr.print("\n");
            }
        }
    }

    #! Formats the protocol label ("h1"/"h2"/"h3") as an HTTP version string
    private static string formatProtocol(*string protocol) {
        switch (protocol) {
            case "h1": return "HTTP/1.1";
            case "h2": return "HTTP/2";
            case "h3": return "HTTP/3";
        }
        return protocol ?? "HTTP/1.1";
    }

    private showRestRequest(hash<RestClient::RestResponseInfo> info, *hash<auto> opt) {
        printf("%s %s %s %s\n", color.green(">"), info.request_method ?? "?",
            info.request_path ?? "", formatProtocol(info.protocol));
        if (opt.lit > 1 && info.request_headers) {
            printf("%s %Y\n", color.green(">"), info.request_headers);
        }
        if (exists info.request_body) {
            *string str;
            if (opt.reformat) {
                str = reformatBody(info.request_body, info.request_headers."Content-Type");
            }
            printf("%s %s\n", color.green(">"), str ?? sprintf("%y", info.request_body));
        }
    }

    private showRestResponse(hash<RestClient::RestResponseInfo> info, *hash<auto> opt) {
        printf("%s %s %d\n", color.yellow("<"), formatProtocol(info.protocol), info.status_code);
        if (opt.lit > 1 && info.headers) {
            printf("%s %Y\n", color.yellow("<"), info.headers);
        }
        if (exists info.body || exists info.response_body_raw) {
            *string str;
            if (opt.reformat && info.content_type) {
                str = reformatBody(info.body, info.content_type);
            }
            if (!exists str) {
                if (info.body.typeCode() == NT_STRING) {
                    str = trim(info.body);
                } else if (info.body.typeCode() == NT_BINARY) {
                    str = "<" + info.body.toHex() + ">";
                } else if (exists info.body) {
                    str = make_json(info.body, JGF_ADD_FORMATTING);
                } else if (info.response_body_raw.typeCode() == NT_STRING) {
                    str = trim(info.response_body_raw);
                } else if (info.response_body_raw.typeCode() == NT_BINARY) {
                    str = "<" + info.response_body_raw.toHex() + ">";
                }
            }
            if (exists str) {
                printf("%s %s\n", color.yellow("<"), str);
            }
        }
    }

    #! Reformats body based on content type for readability
    private *string reformatBody(auto body, *string content_type) {
        if (!content_type) {
            return NOTHING;
        }
        if (content_type =~ /json/) {
            return make_json(body.typeCode() == NT_STRING ? parse_json(body) : body,
                JGF_ADD_FORMATTING);
        }
%ifndef NoXml
        if (content_type =~ /xml/) {
            if (content_type =~ /xmlrpc/) {
                return make_xmlrpc_value(body, XGF_ADD_FORMATTING);
            }
            return make_xml(body.typeCode() == NT_STRING ? parse_xml(body) : body,
                XGF_ADD_FORMATTING);
        }
%endif
%ifndef NoYaml
        if (content_type =~ /yaml/) {
            return trim(make_yaml(body, YAML::BlockStyle));
        }
%endif
        return NOTHING;
    }

    private doExample(hash<auto> opts, string meth, hash<UrlInfo> url_info) {
        bool msg = True;
        bool request = True;
        int code = 200;
        for (int i = 0; i < opt.example.size(); ++i) {
            switch (opt.example[i]) {
                case "q":
                    msg = False;
                    break;

                case "r":
                    request = False;
                    if (opt.example.size() > i + 1) {
                        code = opt.example.substr(i + 1).toInt();
                    }
                    i = opt.example.size();
                    break;

                default:
                    error("unknown character %y found in example string %y; expected \"qr\"",
                        opt.example[i]);
            }
        }

        if (msg) {
            if (request) {
                hash<RestExampleRequestInfo> rex = opts.validator.getExampleRequest(meth,
                    url_info.path);
                printf("%s\n", rex.request_uri);
                map printf("%s: %s\n", $1.key, $1.value), rex.hdr.pairIterator();
                if (rex.body) {
                    if (rex.hdr) {
                        print("\n");
                    }
                    print(rex.body + "\n");
                }
            } else {
                hash<RestExampleResponseInfo> res = opts.validator.getExampleResponse(meth,
                    url_info.path, code);
                printf("%s\n", res.response_uri);
                map printf("%s: %s\n", $1.key, $1.value), res.hdr.pairIterator();
                if (res.body) {
                    if (res.hdr) {
                        print("\n");
                    }
                    print(res.body + "\n");
                }
            }
        } else {
            hash<RestQoreExampleCodeInfo> qex = request
                ? opts.validator.getQoreExampleRequest(meth, url_info.path)
                : opts.validator.getQoreExampleResponse(meth, url_info.path, code);
            map printf("%s\n", $1), qex.hashdecls.iterator();
            printf("%s\n", qex.example);
        }
    }

    private doPing(string ping) {
        try {
            AbstractConnection conn = get_connection(ping);
            conn.setLogger(getLogger());
            hash<auto> info = conn.ping();
            if (!info.ok && !opt.fullex && !opt.verbose && info.info.length() > 200) {
                printf("ping result: %y... (%d bytes truncated; use -E or -v for full output)\n",
                    info.info[0..199], info.info.length() - 200);
            } else {
                printf("ping result: %y\n", info.info);
            }
            if (info.ex && (opt.fullex || opt.verbose)) {
                printf("%s\n", get_exception_string(info.ex));
            }
            thread_exit;
        } catch (hash<ExceptionInfo> ex) {
            if (ex.err == "CONNECTION-ERROR") {
                if (opt.fullex) {
                    stderr.printf("%s\n", get_exception_string(ex));
                } else {
                    stderr.printf("%s: %s\n", ex.err, ex.desc);
                }
                exit(1);
            }
            rethrow;
        }
    }

    private doPollPing(string ping) {
        try {
            AbstractConnection conn = get_connection(ping);
            Logger logger = getLogger();
            conn.setLogger(logger);

            TestPollingConnectionMonitor monitor(logger);
            # Stop the monitor before destruction to ensure I/O callbacks complete
            # and release the monitor's lock before its Mutex is destroyed
            on_exit monitor.stop();

            monitor.add(conn);

            hash<auto> info = monitor.waitForResult(opt.to ?? 20s);
            printf("ping result: %y\n", info.result);
            if (info.ex && (opt.fullex || opt.verbose)) {
                printf("%s\n", get_exception_string(info.ex));
            }
            thread_exit;
        } catch (hash<ExceptionInfo> ex) {
            if (ex.err == "CONNECTION-ERROR") {
                if (opt.fullex) {
                    stderr.printf("%s\n", get_exception_string(ex));
                } else {
                    stderr.printf("%s: %s\n", ex.err, ex.desc);
                }
                exit(1);
            }
            rethrow;
        }
    }

    private Logger getLogger() {
        LoggerLevel level;
        if (opt.verbose > 1) {
            level = LoggerLevel::getLevelDebug();
        } else if (opt.verbose) {
            level = LoggerLevel::getLevelInfo();
        } else {
            level = LoggerLevel::getLevelError();
        }
        Logger logger("stdout", level);
        logger.addAppender(new StdoutAppender());
        return logger;
    }

    static usage() {
        printf("%s - Qore REST client\n\n", color.bold("rest"));
        printf("%s %s [options] get|put|post|delete|del URL ['YAML/Qore body']\n\n", color.bold("Usage:"),
            get_script_name());

        printf("%s\n", color.bold("Options:"));
        printf("  %s  set HTTP version: auto, 1.0, 1.1, 2.0, 3.0\n",
            color.key("-A, --http-version=ARG    "));
        printf("  %s  use the given connection name\n",
            color.key("-c, --connection=ARG      "));
        printf("  %s  disable color output\n",
            color.key("-C, --no-color            "));
        printf("  %s  show full exception output\n",
            color.key("-E, --full-exception      "));
        printf("  %s  set compression: gzip,deflate,bzip2,identity\n",
            color.key("-e, --send-encoding[=ARG] "));
        printf("  %s  ping the given connection with I/O polling and exit\n",
            color.key("-G, --poll-ping=ARG       "));
        printf("  %s  ping the given connection and exit\n",
            color.key("-g, --ping=ARG            "));
        printf("  %s  send header with request\n",
            color.key("-H, --header=ARG          "));
        printf("  %s  ignore HTTP errors and show the literal response\n",
            color.key("-i, --ignore-errors       "));
        printf("  %s  list URI paths and methods supported by the schema\n",
            color.key("-L, --list                "));
        printf("  %s  show literal API calls (more l's, more info)\n",
            color.key("-l, --literal             "));
        printf("  %s  save output with the given file name\n",
            color.key("-o, --output=ARG          "));
        printf("  %s  set the proxy URL (ex: http://proxy:port)\n",
            color.key("-P, --proxy-url=ARG       "));
        printf("  %s  override the base path for Swagger schemas\n",
            color.key("-p, --base-path=ARG       "));
        printf("  %s  reformat data with -l+ for better readability\n",
            color.key("-R, --reformat            "));
        printf("  %s  set REST data serialization type:\n",
            color.key("-S, --serialization=ARG   "));
        printf("                              auto, json, yaml, xml, rawxml, url\n");
        printf("  %s  use the given Swagger 2.0 schema for validation\n",
            color.key("-s, --swagger=ARG         "));
        printf("  %s  set HTTP timeout in seconds\n",
            color.key("-T, --timeout=ARG         "));
        printf("  %s  an authorization token to use\n",
            color.key("-t, --token=ARG           "));
        printf("  %s  set user:password for the connection\n",
            color.key("-u, --userpass=ARG        "));
        printf("  %s  require and verify X.509 certificates\n",
            color.key("-V, --verify-cert         "));
        printf("  %s  lax parsing of Swagger schemas\n",
            color.key("-X, --lax-parsing         "));
        printf("  %s  generate an example message (q=Qore, r<code>=response)\n",
            color.key("-x, --example[=ARG]       "));
        printf("  %s  the type of token (default: Bearer)\n",
            color.key("-y, --token-type=ARG      "));
        printf("  %s  OAuth2 grant type (e.g., client_credentials)\n",
            color.key("    --grant-type=ARG      "));
        printf("  %s  OAuth2 client ID\n",
            color.key("    --client-id=ARG       "));
        printf("  %s  OAuth2 client secret\n",
            color.key("    --client-secret=ARG   "));
        printf("  %s  OAuth2 token endpoint URL\n",
            color.key("    --token-url=ARG       "));
        printf("  %s  show verbose output (repeat for more detail)\n",
            color.key("-v, --verbose             "));
        printf("  %s  this help text\n",
            color.key("-h, --help                "));

        printf("\n%s uses RestClientIo for async HTTP/1.1, HTTP/2, and HTTP/3\n",
            color.dim("Note:"));
        printf("connections with automatic protocol selection and connection multiplexing\n");
        printf("on HTTP/2 and HTTP/3. Use -l (--literal) for verbose HTTP request/response\n");
        printf("output.\n\n");
        printf("%s Request bodies accept YAML / JSON-compatible YAML, legacy Qore values,\n",
            color.dim("Body:"));
        printf("%s, and file references such as %s.\n",
            color.key("%STR=literal strings"), color.key("$yaml<body.yaml>"));
        exit(1);
    }

    static error(string fmt) {
        stderr.printf("%s: %s %s\n", get_script_name(), color.error("ERROR:"), vsprintf(fmt, argv));
        exit(1);
    }
}

class TestPollingConnectionMonitor inherits PollingConnectionMonitor {
    private {
        Queue msgq();
    }

    constructor(*Logger logger) : PollingConnectionMonitor(logger) {
    }

    hash<auto> waitForResult(timeout to) {
        try {
            return msgq.get(to);
        } catch (hash<ExceptionInfo> ex) {
            if (ex.err == "QUEUE-TIMEOUT") {
                rethrow "PING-TIMEOUT", sprintf("no ping result received within the %y timeout; "
                    "the connection may be unreachable or the async I/O operation stalled", to);
            }
            rethrow;
        }
    }

    private failedToStartPing(string name, hash<ExceptionInfo> ex) {
        PollingConnectionMonitor::failedToStartPing(name, ex);
        msgq.push({"name": name, "result": "error", "ex": ex});
    }

    private handlePingSuccess(string name, date delta, *bool oldok) {
        PollingConnectionMonitor::handlePingSuccess(name, delta, oldok);
        msgq.push({"name": name, "result": "OK"});
    }

    private handlePingFailed(string name, date delta, hash<ExceptionInfo> ex) {
        PollingConnectionMonitor::handlePingFailed(name, delta, ex);
        msgq.push({"name": name, "result": "error", "ex": ex});
    }

    private handlePingTimeout(string name, date delta) {
        PollingConnectionMonitor::handlePingTimeout(name, delta);
        msgq.push({"name": name, "result": "timeout"});
    }
}
