Debian Codegraph @

test/lib/ansible_test/_internal/http.py

raw
1 """A simple HTTP client."""
2
3 from __future__ import annotations
4
5 import http.client
6 import json
7 import time
8 import typing as t
9 import urllib.error
10 import urllib.request
11
12 from .util import (
13 ApplicationError,
14 display,
15 )
16
17 from .util_common import (
18 CommonConfig,
19 )
20
21
22 class HttpClient:
23 """Make HTTP requests."""
24
25 def __init__(self, args: CommonConfig, always: bool = False) -> None:
26 self.args = args
27 self.always = always
28
29 def get(self, url: str) -> HttpResponse:
30 """Perform an HTTP GET and return the response."""
31 return self.request('GET', url)
32
33 def delete(self, url: str) -> HttpResponse:
34 """Perform an HTTP DELETE and return the response."""
35 return self.request('DELETE', url)
36
37 def put(self, url: str, data: t.Optional[str] = None, headers: t.Optional[dict[str, str]] = None) -> HttpResponse:
38 """Perform an HTTP PUT and return the response."""
39 return self.request('PUT', url, data, headers)
40
41 def request(self, method: str, url: str, data: t.Optional[str] = None, headers: t.Optional[dict[str, str]] = None) -> HttpResponse:
42 """Perform an HTTP request and return the response."""
43 if headers is None:
44 headers = {}
45
46 data_bytes = data.encode() if data else None
47
48 request = urllib.request.Request(method=method, url=url, data=data_bytes, headers=headers)
49 response: http.client.HTTPResponse
50
51 display.info(f'HTTP {method} {url}', verbosity=2)
52
53 attempts = 0
54 max_attempts = 3
55 sleep_seconds = 3
56
57 status_code = 200
58 reason = 'OK'
59 body_bytes = b''
60
61 while True:
62 attempts += 1
63
64 start = time.monotonic()
65
66 if self.args.explain and not self.always:
67 break
68
69 try:
70 try:
71 with urllib.request.urlopen(request) as response:
72 status_code = response.status
73 reason = response.reason
74 body_bytes = response.read()
75 except urllib.error.HTTPError as ex:
76 status_code = ex.status
77 reason = ex.reason
78 body_bytes = ex.read()
79 except Exception as ex: # pylint: disable=broad-exception-caught
80 if attempts >= max_attempts:
81 raise
82
83 # all currently implemented methods are idempotent, so retries are unconditionally supported
84 duration = time.monotonic() - start
85 display.warning(f'{type(ex).__module__}.{type(ex).__name__}: {ex} [{duration:.2f} seconds]')
86 time.sleep(sleep_seconds)
87
88 continue
89
90 break
91
92 duration = time.monotonic() - start
93 display.info(f'HTTP {method} {url} -> HTTP {status_code} ({reason}) [{len(body_bytes)} bytes, {duration:.2f} seconds]', verbosity=3)
94
95 body = body_bytes.decode()
96
97 return HttpResponse(method, url, status_code, body)
98
99
100 class HttpResponse:
101 """HTTP response."""
102
103 def __init__(self, method: str, url: str, status_code: int, response: str) -> None:
104 self.method = method
105 self.url = url
106 self.status_code = status_code
107 self.response = response
108
109 def json(self) -> t.Any:
110 """Return the response parsed as JSON, raising an exception if parsing fails."""
111 try:
112 return json.loads(self.response)
113 except ValueError:
114 raise HttpError(self.status_code, 'Cannot parse response to %s %s as JSON:\n%s' % (self.method, self.url, self.response)) from None
115
116
117 class HttpError(ApplicationError):
118 """HTTP response as an error."""
119
120 def __init__(self, status: int, message: str) -> None:
121 super().__init__('%s: %s' % (status, message))
122 self.status = status