-
Notifications
You must be signed in to change notification settings - Fork 33
/
helpers.py
196 lines (154 loc) · 5.3 KB
/
helpers.py
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
import json
import datetime
import random
import os
import requests
import string
from typing import Any
def check_response(r: requests.Response) -> None:
"""
Raise a helpful exception if the HTTP response was not 200.
"""
if r.status_code != 200:
raise Exception(f"{r.url} returned HTTP {r.status_code} {r.text}")
def check_var(val: str) -> bool:
"""
Return true if the value is ok.
"""
if val is None or val == "":
return False
if invalid(val):
return False
return True
def check_url(url: str) -> bool:
"""
Return true if the URL is ok.
"""
if not check_var(url):
return False
if not any(url.startswith(prefix) for prefix in ["http://", "https://"]):
return False
return True
def get_from_env(var_name: str) -> str:
"""
Get a value from an environment variable. Used in CI for testing.
"""
val = os.getenv(var_name, "")
if val == "":
print(f"Error: Missing environment variable {var_name}.")
exit(1)
return val
def invalid(val: str) -> bool:
"""
Return true if none of the invalid strings are found in the value.
"""
bzzt = [">>", "e.g.", "example"]
return any(x in val for x in bzzt)
def random_string(length: int = 20) -> str:
"""
Generate a random string, made of letters and digits.
"""
choices = string.ascii_letters + string.digits
return "".join(random.choice(choices) for i in range(length))
def fix_wallet_server_url(url: str) -> str:
"""
Help guide users against including api version suffix in wallet server URL.
"""
for suffix in ["/api/v1/", "/api/v1", "/api/", "/api", "/"]:
if not url.endswith(suffix):
continue
print(
f'There\'s no need to add "{suffix}" to the wallet server URL. '
"Removing it and continuing..."
)
url = url[: -len(suffix)]
return url
def enum_to_str(e: Any, val: int) -> str:
return e.keys()[e.values().index(val)]
def ts_now():
return datetime.datetime.now()
def get_nano_ts(dt: datetime.datetime, seconds_delta: int):
new_dt = dt - datetime.timedelta(seconds=seconds_delta)
return str(int(new_dt.replace(tzinfo=datetime.timezone.utc).timestamp())*1000000000)
def nano_ts_to_human_date(nanos):
dt = datetime.datetime.fromtimestamp(nanos / 1e9)
return '{}{:03.0f}'.format(dt.strftime('%Y-%m-%dT%H:%M:%S.%f'), nanos % 1e3)
def env_market_id() -> str:
"""
Get env var for a custom MARKET_ID, will not forcibly reload from API
"""
return env_market_id_from_api(False)
def env_market_id_from_api(reload: bool) -> str:
"""
Get env var for a custom MARKET_ID, will find one from API if not specified
"""
market_id = os.getenv("MARKET_ID", "")
perform_reload = False
if len(market_id) > 0:
if reload:
perform_reload = True
else:
perform_reload = True
if perform_reload:
# Request a list of markets and select the first one
data_node_url_rest = get_from_env("DATA_NODE_URL_REST")
url = f"{data_node_url_rest}/markets"
response = requests.get(url)
check_response(response)
if len(get_nested_response(response, "markets")) == 0:
print(f"No markets found on {url}")
print("Please check and try again...")
exit(1)
else:
market_id = get_nested_response(response, "markets")[0]["node"]["id"]
assert market_id != ""
print(f"MARKET_ID set: {market_id}")
os.environ["MARKET_ID"] = market_id
return market_id
def env_party_id() -> str:
"""
Get env var for a custom PARTY_ID, will not forcibly reload from API
"""
return env_party_id_from_api(False)
def env_party_id_from_api(reload: bool) -> str:
"""
Get env var for a custom PARTY_ID, will find one from API if not specified
"""
party_id = os.getenv("PARTY_ID", "")
perform_reload = False
if len(party_id) > 0:
if reload:
perform_reload = True
else:
perform_reload = True
if perform_reload:
# Request a list of parties and select the first one
data_node_url_rest = get_from_env("DATA_NODE_URL_REST")
url = f"{data_node_url_rest}/parties"
response = requests.get(url)
check_response(response)
if len(get_nested_response(response, "parties")) <= 1:
print(f"No (non network) parties found on {url}")
print("Please check and try again...")
exit(1)
else:
party_id = get_nested_response(response, "parties")[1]["node"]["id"]
assert party_id != ""
print(f"PARTY_ID set: {party_id}")
os.environ["PARTY_ID"] = party_id
return party_id
def get_nested_response(response: json, key: str) -> json:
"""
Get json back from a response string given v2 nesting with edges
"""
return response.json()[key]["edges"]
def check_nested_response(response: json, key: str) -> bool:
"""
Check if len > 0 from a response string given v2 nesting with edges
"""
return len(get_nested_response(response, key)) > 0
def generate_id(n :int) -> str:
"""
Generate a semi-random identifier string of length n
"""
return ''.join(random.choices(string.ascii_lowercase + (2 * string.digits), k=n))