summaryrefslogtreecommitdiff
path: root/Biz/Que/Client.py
blob: 90e560fadaa2e84182564d6d470bfed1a8adc224 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
#!/usr/bin/env python3
# : out que
"""
simple client for que.run
"""

import argparse
import configparser
import functools
import http.client
import logging
import os
import subprocess
import sys
import textwrap
import time
import urllib.parse
import urllib.request as request
import typing

MAX_TIMEOUT = 9999999
RETRIES = 10
DELAY = 3
BACKOFF = 1


def auth(args: argparse.Namespace) -> typing.Union[str, None]:
    "Returns the auth key for the given ns from ~/.config/que.conf"
    logging.debug("auth")
    namespace = args.target.split("/")[0]
    if namespace == "pub":
        return None
    conf_file = os.path.expanduser("~/.config/que.conf")
    if not os.path.exists(conf_file):
        sys.exit("you need a ~/.config/que.conf")
    cfg = configparser.ConfigParser()
    cfg.read(conf_file)
    return cfg[namespace]["key"]


def autodecode(bytestring: bytes) -> typing.Any:
    """Attempt to decode bytes into common codecs, preferably utf-8. If no
    decoding is available, just return the raw bytes.

    For all available codecs, see:
    <https://docs.python.org/3/library/codecs.html#standard-encodings>

    """
    logging.debug("autodecode")
    codecs = ["utf-8", "ascii"]
    for codec in codecs:
        try:
            return bytestring.decode(codec)
        except UnicodeDecodeError:
            pass
    return bytestring


@typing.no_type_check
def retry(
    exception: str,
    tries: typing.Any = RETRIES,
    delay: typing.Any = DELAY,
    backoff: typing.Any = BACKOFF,
) -> typing.Any:
    "Decorator for retrying an action."

    def decorator(func: typing.Any) -> typing.Any:
        @functools.wraps(func)
        def func_retry(*args: typing.Any, **kwargs: typing.Any) -> typing.Any:
            mtries, mdelay = tries, delay
            while mtries > 1:
                try:
                    return func(*args, **kwargs)
                except exception as ex:
                    logging.debug(ex)
                    logging.debug("retrying...")
                    time.sleep(mdelay)
                    mtries -= 1
                    mdelay *= backoff
            return func(*args, **kwargs)

        return func_retry

    return decorator


@typing.no_type_check
@retry(urllib.error.URLError)
@retry(http.client.IncompleteRead)
@retry(http.client.RemoteDisconnected)
def send(args: argparse.Namespace) -> None:
    "Send a message to the que."
    logging.debug("send")
    key = auth(args)
    data = args.infile
    req = request.Request(f"{args.host}/{args.target}")
    req.add_header("User-Agent", "Que/Client")
    req.add_header("Content-Type", "text/plain;charset=utf-8")
    if key:
        req.add_header("Authorization", key)
    if args.serve:
        logging.debug("serve")
        while not time.sleep(1):
            # pylint: disable=consider-using-with
            request.urlopen(req, data=data, timeout=MAX_TIMEOUT)
    else:
        # pylint: disable=consider-using-with
        request.urlopen(req, data=data, timeout=MAX_TIMEOUT)


def then(args: argparse.Namespace, msg: str) -> None:
    "Perform an action when passed `--then`."
    if args.then:
        logging.debug("then")
        subprocess.run(
            args.then.format(msg=msg, que=args.target),
            check=False,
            shell=True,
        )


@typing.no_type_check
@retry(urllib.error.URLError)
@retry(http.client.IncompleteRead)
@retry(http.client.RemoteDisconnected)
def recv(args: argparse.Namespace) -> None:
    "Receive a message from the que."
    logging.debug("recv on: %s", args.target)
    if args.poll:
        req = request.Request(f"{args.host}/{args.target}/stream")
    else:
        req = request.Request(f"{args.host}/{args.target}")
    req.add_header("User-Agent", "Que/Client")
    key = auth(args)
    if key:
        req.add_header("Authorization", key)
    with request.urlopen(req) as _req:
        if args.poll:
            logging.debug("polling")
            while not time.sleep(1):
                reply = _req.readline()
                if reply:
                    msg = autodecode(reply)
                    logging.debug("read")
                    print(msg, end="")
                    then(args, msg)
                else:
                    continue
        else:
            msg = autodecode(_req.readline())
            print(msg)
            then(args, msg)


def get_args() -> argparse.Namespace:
    "Command line parser"
    cli = argparse.ArgumentParser(
        description=__doc__,
        epilog=textwrap.dedent(
            f"""Requests will retry up to {RETRIES} times, with {DELAY} seconds
        between attempts."""
        ),
    )
    cli.add_argument("test", action="store_true", help="run tests")
    cli.add_argument("--debug", action="store_true", help="log to stderr")
    cli.add_argument(
        "--host", default="http://que.run", help="where que-server is running"
    )
    cli.add_argument(
        "--poll",
        default=False,
        action="store_true",
        help=textwrap.dedent(
            """keep the connection open to stream data from the que. without
            this flag, the program will exit after receiving a message"""
        ),
    )
    cli.add_argument(
        "--then",
        help=textwrap.dedent(
            """when polling, run this shell command after each response,
            presumably for side effects, replacing '{que}' with the target and
            '{msg}' with the body of the response"""
        ),
    )
    cli.add_argument(
        "--serve",
        default=False,
        action="store_true",
        help=textwrap.dedent(
            """when posting to the que, do so continuously in a loop. this can
            be used for serving a webpage or other file continuously"""
        ),
    )
    cli.add_argument("target", help="namespace and path of the que, like 'ns/path'")
    cli.add_argument(
        "infile",
        nargs="?",
        type=argparse.FileType("rb"),
        help="data to put on the que. use '-' for stdin, otherwise should be a readable file",
    )
    return cli.parse_args()


if __name__ == "__main__":
    ARGV = get_args()
    if ARGV.test:
        print("ok")
        sys.exit()
    if ARGV.debug:
        logging.basicConfig(
            format="%(asctime)s:  %(levelname)s:  %(message)s",
            level=logging.DEBUG,
            datefmt="%Y.%m.%d..%H.%M.%S",
        )
    try:
        if ARGV.infile:
            send(ARGV)
        else:
            recv(ARGV)
    except KeyboardInterrupt:
        sys.exit(0)