disruptapi 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- disruptapi/__init__.py +63 -0
- disruptapi/__main__.py +6 -0
- disruptapi/_base_client.py +288 -0
- disruptapi/_client.py +117 -0
- disruptapi/_errors.py +154 -0
- disruptapi/_rate_limit.py +98 -0
- disruptapi/_version.py +1 -0
- disruptapi/cli.py +529 -0
- disruptapi/pagination.py +166 -0
- disruptapi/py.typed +0 -0
- disruptapi/resources/__init__.py +1 -0
- disruptapi/resources/_specs.py +236 -0
- disruptapi/resources/async_.py +315 -0
- disruptapi/resources/sync.py +307 -0
- disruptapi/types.py +455 -0
- disruptapi/webhooks.py +122 -0
- disruptapi-0.2.0.dist-info/METADATA +342 -0
- disruptapi-0.2.0.dist-info/RECORD +21 -0
- disruptapi-0.2.0.dist-info/WHEEL +4 -0
- disruptapi-0.2.0.dist-info/entry_points.txt +2 -0
- disruptapi-0.2.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import email.utils
|
|
4
|
+
import re
|
|
5
|
+
import time
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Dict, Mapping, Optional
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class RateLimitInfo:
|
|
12
|
+
"""Rate-limit and quota state from the response headers. Missing headers are None.
|
|
13
|
+
|
|
14
|
+
The ``X-RateLimit-*`` headers are read first. When they are absent, the IETF fields
|
|
15
|
+
(draft-ietf-httpapi-ratelimit-headers) are used instead: ``RateLimit-Limit``,
|
|
16
|
+
``RateLimit-Remaining`` and ``RateLimit-Reset``, then the structured
|
|
17
|
+
``RateLimit: "<policy>";r=<remaining>;t=<seconds>``. IETF reset values are
|
|
18
|
+
delta-seconds; ``reset`` is always converted to Unix seconds.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
limit: Optional[int] = None #: requests per minute (X-RateLimit-Limit / RateLimit-Limit)
|
|
22
|
+
remaining: Optional[int] = None #: X-RateLimit-Remaining / RateLimit-Remaining
|
|
23
|
+
reset: Optional[int] = None #: Unix seconds when the window ends (X-RateLimit-Reset, or now + RateLimit-Reset)
|
|
24
|
+
quota_limit: Optional[int] = None #: X-Quota-Limit, requests per month
|
|
25
|
+
quota_remaining: Optional[int] = None #: X-Quota-Remaining
|
|
26
|
+
data_records_remaining_today: Optional[int] = None #: X-Data-Records-Remaining-Today
|
|
27
|
+
retry_after: Optional[float] = None #: Retry-After, seconds
|
|
28
|
+
limit_reason: Optional[str] = None #: X-Limit-Reason: "rate" or "quota" (429 only)
|
|
29
|
+
policy: Optional[str] = None #: RateLimit-Policy, raw, e.g. '"minute";q=60;w=60'
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _int(v: Optional[str]) -> Optional[int]:
|
|
33
|
+
if v is None or not v.strip():
|
|
34
|
+
return None
|
|
35
|
+
try:
|
|
36
|
+
return int(float(v))
|
|
37
|
+
except ValueError:
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def parse_retry_after(v: Optional[str], now: Optional[float] = None) -> Optional[float]:
|
|
42
|
+
"""Retry-After as seconds: delta-seconds or an HTTP date."""
|
|
43
|
+
if v is None or not v.strip():
|
|
44
|
+
return None
|
|
45
|
+
try:
|
|
46
|
+
return max(0.0, float(v))
|
|
47
|
+
except ValueError:
|
|
48
|
+
pass
|
|
49
|
+
try:
|
|
50
|
+
dt = email.utils.parsedate_to_datetime(v)
|
|
51
|
+
except (TypeError, ValueError):
|
|
52
|
+
return None
|
|
53
|
+
if dt is None:
|
|
54
|
+
return None
|
|
55
|
+
return max(0.0, dt.timestamp() - (now if now is not None else time.time()))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _structured(v: Optional[str]) -> Dict[str, str]:
|
|
59
|
+
"""Parameters of the first item of a structured RateLimit field: '"minute";r=5;t=30'."""
|
|
60
|
+
if not v:
|
|
61
|
+
return {}
|
|
62
|
+
first = v.split(",")[0]
|
|
63
|
+
return {m.group(1): m.group(2) for m in re.finditer(r";\s*([a-z]+)=([^;,\s]+)", first)}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def parse_rate_limit(headers: Mapping[str, str], now: Optional[float] = None) -> RateLimitInfo:
|
|
67
|
+
h = {k.lower(): v for k, v in headers.items()}
|
|
68
|
+
current = time.time() if now is None else now
|
|
69
|
+
limit = _int(h.get("x-ratelimit-limit"))
|
|
70
|
+
remaining = _int(h.get("x-ratelimit-remaining"))
|
|
71
|
+
reset = _int(h.get("x-ratelimit-reset"))
|
|
72
|
+
# IETF fallbacks, used only when the X- header is absent.
|
|
73
|
+
if limit is None:
|
|
74
|
+
limit = _int(h.get("ratelimit-limit"))
|
|
75
|
+
if limit is None:
|
|
76
|
+
limit = _int(_structured(h.get("ratelimit-policy")).get("q"))
|
|
77
|
+
st = _structured(h.get("ratelimit"))
|
|
78
|
+
if remaining is None:
|
|
79
|
+
remaining = _int(h.get("ratelimit-remaining"))
|
|
80
|
+
if remaining is None:
|
|
81
|
+
remaining = _int(st.get("r"))
|
|
82
|
+
if reset is None:
|
|
83
|
+
delta = _int(h.get("ratelimit-reset"))
|
|
84
|
+
if delta is None:
|
|
85
|
+
delta = _int(st.get("t"))
|
|
86
|
+
if delta is not None:
|
|
87
|
+
reset = int(current) + max(0, delta)
|
|
88
|
+
return RateLimitInfo(
|
|
89
|
+
limit=limit,
|
|
90
|
+
remaining=remaining,
|
|
91
|
+
reset=reset,
|
|
92
|
+
quota_limit=_int(h.get("x-quota-limit")),
|
|
93
|
+
quota_remaining=_int(h.get("x-quota-remaining")),
|
|
94
|
+
data_records_remaining_today=_int(h.get("x-data-records-remaining-today")),
|
|
95
|
+
retry_after=parse_retry_after(h.get("retry-after"), now),
|
|
96
|
+
limit_reason=h.get("x-limit-reason"),
|
|
97
|
+
policy=h.get("ratelimit-policy"),
|
|
98
|
+
)
|
disruptapi/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.2.0"
|
disruptapi/cli.py
ADDED
|
@@ -0,0 +1,529 @@
|
|
|
1
|
+
"""The ``disruptapi`` command-line tool.
|
|
2
|
+
|
|
3
|
+
disruptapi signals list --type aviation,weather --country US --format table
|
|
4
|
+
disruptapi exposure check --file items.json
|
|
5
|
+
echo '[{"id": "x", "airport": "SEA"}]' | disruptapi exposure check --file -
|
|
6
|
+
|
|
7
|
+
Output is JSON unless ``--format table`` is given (on commands that have a table view).
|
|
8
|
+
Exit codes: 0 ok, 1 API error, 2 usage error, 3 authentication or permission error.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import sys
|
|
17
|
+
import time
|
|
18
|
+
from typing import IO, Any, Callable, Dict, List, Optional, Sequence
|
|
19
|
+
|
|
20
|
+
import httpx
|
|
21
|
+
|
|
22
|
+
from ._client import DisruptAPI
|
|
23
|
+
from ._errors import AuthenticationError, DisruptError, PermissionDeniedError
|
|
24
|
+
from ._version import __version__
|
|
25
|
+
from .webhooks import parse_signature_header, verify_signature
|
|
26
|
+
|
|
27
|
+
EXIT_OK, EXIT_API, EXIT_USAGE, EXIT_AUTH = 0, 1, 2, 3
|
|
28
|
+
SEVERITIES = ["minor", "moderate", "severe", "extreme"]
|
|
29
|
+
KEY_ENV_VARS = ("DISRUPT_API_KEY", "DISRUPT_KEY")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class UsageError(Exception):
|
|
33
|
+
"""Bad input found after parsing (unreadable file, invalid JSON, ...): exit 2."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
# --- output -------------------------------------------------------------------------------
|
|
37
|
+
|
|
38
|
+
def _cell(v: Any, width: int = 60) -> str:
|
|
39
|
+
if v is None:
|
|
40
|
+
s = ""
|
|
41
|
+
elif isinstance(v, bool):
|
|
42
|
+
s = "yes" if v else "no"
|
|
43
|
+
elif isinstance(v, (list, tuple)):
|
|
44
|
+
s = ",".join(_cell(x, width) for x in v)
|
|
45
|
+
elif isinstance(v, dict):
|
|
46
|
+
s = json.dumps(v, ensure_ascii=False, separators=(",", ":"))
|
|
47
|
+
else:
|
|
48
|
+
s = str(v)
|
|
49
|
+
s = s.replace("\n", " ")
|
|
50
|
+
return s if len(s) <= width else s[: width - 1] + "…"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def render_table(rows: Sequence[Dict[str, Any]], columns: Sequence[str]) -> str:
|
|
54
|
+
"""Plain-text table: a header, a rule and one line per row. Dotted columns read nested keys."""
|
|
55
|
+
def get(row: Dict[str, Any], col: str) -> Any:
|
|
56
|
+
v: Any = row
|
|
57
|
+
for part in col.split("."):
|
|
58
|
+
v = v.get(part) if isinstance(v, dict) else None
|
|
59
|
+
return v
|
|
60
|
+
|
|
61
|
+
cells = [[_cell(get(r, c)) for c in columns] for r in rows]
|
|
62
|
+
widths = [max([len(c)] + [len(row[i]) for row in cells]) for i, c in enumerate(columns)]
|
|
63
|
+
lines = [" ".join(c.upper().ljust(w) for c, w in zip(columns, widths)).rstrip(),
|
|
64
|
+
" ".join("-" * w for w in widths)]
|
|
65
|
+
lines += [" ".join(v.ljust(w) for v, w in zip(row, widths)).rstrip() for row in cells]
|
|
66
|
+
return "\n".join(lines)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
TABLES: Dict[str, List[str]] = {
|
|
70
|
+
"signals": ["id", "type", "severity", "status", "title", "countries", "airports", "updated_at"],
|
|
71
|
+
"exposure": ["item_id", "kind", "risk_level", "match_count"],
|
|
72
|
+
"providers": ["provider", "status", "active_incidents", "worst_severity"],
|
|
73
|
+
"watchlists": ["id", "name", "items", "created_at"],
|
|
74
|
+
"items": ["id", "kind", "label", "carrier", "origin", "destination", "airport", "provider", "depart_at"],
|
|
75
|
+
"webhooks": ["id", "url", "filters", "created_at", "disabled_at", "failures"],
|
|
76
|
+
"plans": ["id", "name", "price_usd_month", "monthly_requests", "per_minute", "webhooks", "watch_items"],
|
|
77
|
+
"usage": ["day", "requests", "errors", "avg_latency_ms"],
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class Output:
|
|
82
|
+
def __init__(self, out: IO[str]) -> None:
|
|
83
|
+
self.out = out
|
|
84
|
+
|
|
85
|
+
def json(self, value: Any) -> None:
|
|
86
|
+
self.out.write(json.dumps(value, ensure_ascii=False, indent=2) + "\n")
|
|
87
|
+
|
|
88
|
+
def table(self, rows: Sequence[Dict[str, Any]], table: str, footer: Optional[str] = None) -> None:
|
|
89
|
+
self.out.write(render_table(rows, TABLES[table]) + "\n")
|
|
90
|
+
if footer:
|
|
91
|
+
self.out.write(footer + "\n")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
# --- input --------------------------------------------------------------------------------
|
|
95
|
+
|
|
96
|
+
def _read_text(path: str, stdin: IO[str]) -> str:
|
|
97
|
+
if path == "-":
|
|
98
|
+
return stdin.read()
|
|
99
|
+
try:
|
|
100
|
+
with open(path, encoding="utf-8") as f:
|
|
101
|
+
return f.read()
|
|
102
|
+
except OSError as exc:
|
|
103
|
+
raise UsageError(f"cannot read {path}: {exc.strerror or exc}") from exc
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _read_bytes(path: str, stdin: IO[str]) -> bytes:
|
|
107
|
+
if path == "-":
|
|
108
|
+
buf = getattr(stdin, "buffer", None)
|
|
109
|
+
return buf.read() if buf is not None else stdin.read().encode("utf-8")
|
|
110
|
+
try:
|
|
111
|
+
with open(path, "rb") as f:
|
|
112
|
+
return f.read()
|
|
113
|
+
except OSError as exc:
|
|
114
|
+
raise UsageError(f"cannot read {path}: {exc.strerror or exc}") from exc
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _read_json(path: str, stdin: IO[str]) -> Any:
|
|
118
|
+
text = _read_text(path, stdin)
|
|
119
|
+
try:
|
|
120
|
+
return json.loads(text)
|
|
121
|
+
except ValueError as exc:
|
|
122
|
+
raise UsageError(f"{'stdin' if path == '-' else path} is not valid JSON: {exc}") from exc
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _read_items(path: str, stdin: IO[str]) -> Dict[str, Any]:
|
|
126
|
+
"""A JSON list of items, or an object with ``items`` (and optionally ``min_severity``)."""
|
|
127
|
+
data = _read_json(path, stdin)
|
|
128
|
+
if isinstance(data, list):
|
|
129
|
+
data = {"items": data}
|
|
130
|
+
if not isinstance(data, dict) or not isinstance(data.get("items", data.get("trips")), list):
|
|
131
|
+
raise UsageError("the items file must hold a JSON list of items, or an object with an \"items\" list")
|
|
132
|
+
if not all(isinstance(i, dict) for i in data.get("items") or []):
|
|
133
|
+
raise UsageError("every item must be a JSON object")
|
|
134
|
+
return data
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _csv(values: Optional[List[str]]) -> Optional[List[str]]:
|
|
138
|
+
"""Repeatable, comma-separated option values -> one list."""
|
|
139
|
+
if not values:
|
|
140
|
+
return None
|
|
141
|
+
out = [v.strip() for chunk in values for v in chunk.split(",") if v.strip()]
|
|
142
|
+
return out or None
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
# --- commands -----------------------------------------------------------------------------
|
|
146
|
+
|
|
147
|
+
Handler = Callable[[argparse.Namespace, "Context"], Optional[int]]
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class Context:
|
|
151
|
+
def __init__(self, args: argparse.Namespace, transport: Optional[httpx.BaseTransport],
|
|
152
|
+
out: IO[str], err: IO[str], stdin: IO[str], env: Dict[str, str]) -> None:
|
|
153
|
+
self.args, self.transport, self.err, self.stdin, self.env = args, transport, err, stdin, env
|
|
154
|
+
self.out = Output(out)
|
|
155
|
+
self._client: Optional[DisruptAPI] = None
|
|
156
|
+
|
|
157
|
+
def api_key(self) -> Optional[str]:
|
|
158
|
+
if getattr(self.args, "api_key", None):
|
|
159
|
+
return str(self.args.api_key)
|
|
160
|
+
for name in KEY_ENV_VARS:
|
|
161
|
+
if self.env.get(name):
|
|
162
|
+
return self.env[name]
|
|
163
|
+
return None
|
|
164
|
+
|
|
165
|
+
def client(self, need_key: bool = True) -> DisruptAPI:
|
|
166
|
+
if self._client is None:
|
|
167
|
+
key = self.api_key()
|
|
168
|
+
if need_key and not key:
|
|
169
|
+
raise AuthenticationError(
|
|
170
|
+
"no API key: set DISRUPT_API_KEY (or DISRUPT_KEY), or pass --api-key",
|
|
171
|
+
code="missing_api_key")
|
|
172
|
+
kwargs: Dict[str, Any] = {"transport": self.transport}
|
|
173
|
+
if getattr(self.args, "base_url", None) or self.env.get("DISRUPT_BASE_URL"):
|
|
174
|
+
kwargs["base_url"] = getattr(self.args, "base_url", None) or self.env["DISRUPT_BASE_URL"]
|
|
175
|
+
if getattr(self.args, "timeout", None) is not None:
|
|
176
|
+
kwargs["timeout"] = self.args.timeout
|
|
177
|
+
if getattr(self.args, "max_retries", None) is not None:
|
|
178
|
+
kwargs["max_retries"] = self.args.max_retries
|
|
179
|
+
# An empty string (not None) stops the client reading DISRUPT_API_KEY by itself.
|
|
180
|
+
self._client = DisruptAPI(key or "", **kwargs)
|
|
181
|
+
return self._client
|
|
182
|
+
|
|
183
|
+
@property
|
|
184
|
+
def table(self) -> bool:
|
|
185
|
+
return getattr(self.args, "format", "json") == "table"
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def cmd_signals_list(a: argparse.Namespace, ctx: Context) -> None:
|
|
189
|
+
params = dict(status=a.status, type=_csv(a.type), min_severity=a.min_severity, country=a.country,
|
|
190
|
+
airport=a.airport, provider=a.provider, since=a.since, limit=a.limit, offset=a.offset)
|
|
191
|
+
page = ctx.client().signals.list(**params)
|
|
192
|
+
if a.all:
|
|
193
|
+
rows = list(page)
|
|
194
|
+
meta: Dict[str, Any] = {"total": page.meta["total"], "returned": len(rows)}
|
|
195
|
+
else:
|
|
196
|
+
rows, meta = page.data, dict(page.meta)
|
|
197
|
+
if ctx.table:
|
|
198
|
+
ctx.out.table(rows, "signals", f"{len(rows)} shown, {meta['total']} matching") # type: ignore[arg-type]
|
|
199
|
+
else:
|
|
200
|
+
ctx.out.json({"data": rows, "meta": meta})
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def cmd_signals_get(a: argparse.Namespace, ctx: Context) -> None:
|
|
204
|
+
ctx.out.json(ctx.client().signals.get(a.signal_id))
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def cmd_exposure_check(a: argparse.Namespace, ctx: Context) -> None:
|
|
208
|
+
body = _read_items(a.file, ctx.stdin)
|
|
209
|
+
res = ctx.client().exposure.check(body.get("items"), trips=body.get("trips"),
|
|
210
|
+
min_severity=a.min_severity or body.get("min_severity"))
|
|
211
|
+
if ctx.table:
|
|
212
|
+
ctx.out.table(res, "exposure") # type: ignore[arg-type]
|
|
213
|
+
else:
|
|
214
|
+
ctx.out.json(res)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def cmd_forecast(a: argparse.Namespace, ctx: Context) -> None:
|
|
218
|
+
ctx.out.json(ctx.client().forecast.get(failure_layer=a.failure_layer, provider=a.provider))
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def cmd_airports_get(a: argparse.Namespace, ctx: Context) -> None:
|
|
222
|
+
ctx.out.json(ctx.client().airports.get(a.iata))
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def cmd_carriers_get(a: argparse.Namespace, ctx: Context) -> None:
|
|
226
|
+
ctx.out.json(ctx.client().carriers.get(a.code))
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def cmd_providers_list(a: argparse.Namespace, ctx: Context) -> None:
|
|
230
|
+
res = ctx.client().providers.list()
|
|
231
|
+
if ctx.table:
|
|
232
|
+
ctx.out.table(res, "providers") # type: ignore[arg-type]
|
|
233
|
+
else:
|
|
234
|
+
ctx.out.json(res)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def cmd_watchlists_list(a: argparse.Namespace, ctx: Context) -> None:
|
|
238
|
+
res = ctx.client().watchlists.list()
|
|
239
|
+
if ctx.table:
|
|
240
|
+
lim = res.get("limits") or {}
|
|
241
|
+
cap = lim.get("watch_items")
|
|
242
|
+
ctx.out.table(res["data"], "watchlists", # type: ignore[arg-type]
|
|
243
|
+
f"{lim.get('used', 0)} of {'unlimited' if cap == -1 else cap} watched items used")
|
|
244
|
+
else:
|
|
245
|
+
ctx.out.json(res)
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def cmd_watchlists_get(a: argparse.Namespace, ctx: Context) -> None:
|
|
249
|
+
res = ctx.client().watchlists.get(a.wl_id, limit=a.limit)
|
|
250
|
+
if ctx.table:
|
|
251
|
+
ctx.out.out.write(f"{res.get('id')} {res.get('name')}\n")
|
|
252
|
+
ctx.out.table(res.get("items") or [], "items")
|
|
253
|
+
else:
|
|
254
|
+
ctx.out.json(res)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def cmd_watchlists_create(a: argparse.Namespace, ctx: Context) -> None:
|
|
258
|
+
items = _read_items(a.file, ctx.stdin)["items"] if a.file else None
|
|
259
|
+
ctx.out.json(ctx.client().watchlists.create(name=a.name, description=a.description, items=items))
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def cmd_watchlists_add_items(a: argparse.Namespace, ctx: Context) -> None:
|
|
263
|
+
items = _read_items(a.file, ctx.stdin)["items"]
|
|
264
|
+
missing = [i for i, it in enumerate(items) if it.get("id") in (None, "")]
|
|
265
|
+
if missing:
|
|
266
|
+
raise UsageError(f"every watchlist item needs an \"id\"; missing at index {', '.join(map(str, missing[:10]))}")
|
|
267
|
+
ctx.out.json(ctx.client().watchlists.items.upsert(a.wl_id, items))
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def cmd_watchlists_remove_item(a: argparse.Namespace, ctx: Context) -> None:
|
|
271
|
+
ctx.out.json(ctx.client().watchlists.items.remove(a.wl_id, a.ref))
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def cmd_watchlists_delete(a: argparse.Namespace, ctx: Context) -> None:
|
|
275
|
+
ctx.out.json(ctx.client().watchlists.delete(a.wl_id))
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def cmd_watchlists_exposure(a: argparse.Namespace, ctx: Context) -> None:
|
|
279
|
+
res = ctx.client().watchlists.exposure(a.wl_id, min_severity=a.min_severity)
|
|
280
|
+
if ctx.table:
|
|
281
|
+
ctx.out.table(res, "exposure") # type: ignore[arg-type]
|
|
282
|
+
else:
|
|
283
|
+
ctx.out.json(res)
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def cmd_webhooks_list(a: argparse.Namespace, ctx: Context) -> None:
|
|
287
|
+
res = ctx.client().webhooks.list()
|
|
288
|
+
if ctx.table:
|
|
289
|
+
ctx.out.table(res, "webhooks") # type: ignore[arg-type]
|
|
290
|
+
else:
|
|
291
|
+
ctx.out.json(res)
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def cmd_webhooks_create(a: argparse.Namespace, ctx: Context) -> None:
|
|
295
|
+
filters: Dict[str, Any] = {}
|
|
296
|
+
if a.filters:
|
|
297
|
+
try:
|
|
298
|
+
parsed = json.loads(a.filters)
|
|
299
|
+
except ValueError as exc:
|
|
300
|
+
raise UsageError(f"--filters is not valid JSON: {exc}") from exc
|
|
301
|
+
if not isinstance(parsed, dict):
|
|
302
|
+
raise UsageError("--filters must be a JSON object")
|
|
303
|
+
filters.update(parsed)
|
|
304
|
+
for name in ("types", "countries", "airports", "carriers", "events", "watchlists"):
|
|
305
|
+
v = _csv(getattr(a, name))
|
|
306
|
+
if v:
|
|
307
|
+
filters[name] = v
|
|
308
|
+
if a.min_severity:
|
|
309
|
+
filters["min_severity"] = a.min_severity
|
|
310
|
+
hook = ctx.client().webhooks.create(url=a.url, filters=filters or None) # type: ignore[arg-type]
|
|
311
|
+
ctx.out.json(hook)
|
|
312
|
+
ctx.err.write("Store the secret now: it is shown only once.\n")
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def cmd_webhooks_delete(a: argparse.Namespace, ctx: Context) -> None:
|
|
316
|
+
ctx.out.json(ctx.client().webhooks.delete(a.hook_id))
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def cmd_webhooks_verify(a: argparse.Namespace, ctx: Context) -> int:
|
|
320
|
+
secret = a.secret or ctx.env.get("DISRUPT_WEBHOOK_SECRET")
|
|
321
|
+
if not secret:
|
|
322
|
+
raise UsageError("pass --secret or set DISRUPT_WEBHOOK_SECRET")
|
|
323
|
+
sig = a.signature.strip()
|
|
324
|
+
if parse_signature_header(sig) is None:
|
|
325
|
+
# A bare v1 hex digest: build the header from --timestamp.
|
|
326
|
+
if a.timestamp is None:
|
|
327
|
+
raise UsageError("--signature is not a 't=...,v1=...' header; pass --timestamp with a bare v1 digest")
|
|
328
|
+
sig = f"t={a.timestamp},v1={sig.split('v1=')[-1]}"
|
|
329
|
+
elif a.timestamp is not None and parse_signature_header(sig)[0] != a.timestamp: # type: ignore[index]
|
|
330
|
+
raise UsageError("--timestamp does not match the t= value in --signature")
|
|
331
|
+
t = parse_signature_header(sig)[0] # type: ignore[index]
|
|
332
|
+
body = _read_bytes(a.body_file, ctx.stdin)
|
|
333
|
+
now = float(t) if a.ignore_age else time.time()
|
|
334
|
+
valid = verify_signature(body, sig, secret, tolerance=a.tolerance, now=now)
|
|
335
|
+
age = int(time.time()) - t
|
|
336
|
+
ctx.out.json({"valid": valid, "timestamp": t, "age_s": age, "tolerance_s": None if a.ignore_age else a.tolerance})
|
|
337
|
+
if not valid:
|
|
338
|
+
reason = ("timestamp outside the tolerance (use --ignore-age for old deliveries)"
|
|
339
|
+
if not a.ignore_age and abs(age) > a.tolerance else "signature does not match")
|
|
340
|
+
ctx.err.write(f"invalid_signature: {reason}\n")
|
|
341
|
+
return EXIT_API
|
|
342
|
+
return EXIT_OK
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def cmd_usage(a: argparse.Namespace, ctx: Context) -> None:
|
|
346
|
+
res = ctx.client().usage(days=a.days)
|
|
347
|
+
if ctx.table:
|
|
348
|
+
ctx.out.table(res.get("daily") or [], "usage", f"{res.get('requests_this_month', 0)} requests this month")
|
|
349
|
+
else:
|
|
350
|
+
ctx.out.json(res)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def cmd_me(a: argparse.Namespace, ctx: Context) -> None:
|
|
354
|
+
ctx.out.json(ctx.client().me())
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def cmd_plans(a: argparse.Namespace, ctx: Context) -> None:
|
|
358
|
+
res = ctx.client(need_key=False).plans()
|
|
359
|
+
if ctx.table:
|
|
360
|
+
ctx.out.table(res, "plans") # type: ignore[arg-type]
|
|
361
|
+
else:
|
|
362
|
+
ctx.out.json(res)
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
# --- parser -------------------------------------------------------------------------------
|
|
366
|
+
|
|
367
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
368
|
+
# Connection options work before or after the command; SUPPRESS keeps a value given
|
|
369
|
+
# before the command from being reset by the subparser's default.
|
|
370
|
+
conn = argparse.ArgumentParser(add_help=False)
|
|
371
|
+
g = conn.add_argument_group("connection")
|
|
372
|
+
g.add_argument("--api-key", default=argparse.SUPPRESS,
|
|
373
|
+
help="API key (default: $DISRUPT_API_KEY, then $DISRUPT_KEY)")
|
|
374
|
+
g.add_argument("--base-url", default=argparse.SUPPRESS, help="API base URL (default: https://app.disruptapi.com)")
|
|
375
|
+
g.add_argument("--timeout", type=float, default=argparse.SUPPRESS, help="seconds per attempt (default 30)")
|
|
376
|
+
g.add_argument("--max-retries", type=int, default=argparse.SUPPRESS, help="retries (default 3)")
|
|
377
|
+
|
|
378
|
+
fmt = argparse.ArgumentParser(add_help=False)
|
|
379
|
+
fmt.add_argument("--format", choices=["json", "table"], default="json", help="output format (default json)")
|
|
380
|
+
|
|
381
|
+
p = argparse.ArgumentParser(
|
|
382
|
+
prog="disruptapi", parents=[conn],
|
|
383
|
+
description="Command-line client for DisruptAPI, the travel disruption intelligence API.",
|
|
384
|
+
epilog="Exit codes: 0 ok, 1 API error, 2 usage error, 3 authentication or permission error.")
|
|
385
|
+
p.add_argument("--version", action="version", version=f"disruptapi {__version__}")
|
|
386
|
+
sub = p.add_subparsers(dest="command", metavar="<command>")
|
|
387
|
+
sub.required = True
|
|
388
|
+
|
|
389
|
+
def leaf(parent: Any, name: str, handler: Handler, help: str, table: bool = False) -> argparse.ArgumentParser:
|
|
390
|
+
sp: argparse.ArgumentParser = parent.add_parser(name, help=help, description=help,
|
|
391
|
+
parents=[conn] + ([fmt] if table else []))
|
|
392
|
+
sp.set_defaults(handler=handler)
|
|
393
|
+
return sp
|
|
394
|
+
|
|
395
|
+
def group(name: str, help: str) -> Any:
|
|
396
|
+
gp = sub.add_parser(name, help=help, description=help)
|
|
397
|
+
s = gp.add_subparsers(dest="action", metavar="<action>")
|
|
398
|
+
s.required = True
|
|
399
|
+
return s
|
|
400
|
+
|
|
401
|
+
# signals
|
|
402
|
+
sig = group("signals", "live and resolved disruptions")
|
|
403
|
+
sp = leaf(sig, "list", cmd_signals_list, "list signals (GET /v1/signals)", table=True)
|
|
404
|
+
sp.add_argument("--type", action="append", metavar="TYPE",
|
|
405
|
+
help="signal type; repeat or comma-separate (aviation, weather, it_outage, ...)")
|
|
406
|
+
sp.add_argument("--min-severity", choices=SEVERITIES)
|
|
407
|
+
sp.add_argument("--country", help="ISO 3166-1 alpha-2 code")
|
|
408
|
+
sp.add_argument("--airport", help="IATA airport code")
|
|
409
|
+
sp.add_argument("--provider", help="provider id, e.g. aws, cloudflare, faa")
|
|
410
|
+
sp.add_argument("--status", choices=["active", "resolved", "all"])
|
|
411
|
+
sp.add_argument("--since", help="only signals updated at or after this UTC time, e.g. 2026-11-18T06:00:00Z")
|
|
412
|
+
sp.add_argument("--limit", type=int, help="page size, 1 to your plan's maximum (default 50)")
|
|
413
|
+
sp.add_argument("--offset", type=int, default=0)
|
|
414
|
+
sp.add_argument("--all", action="store_true", help="follow every page (counts against the daily record budget)")
|
|
415
|
+
sp = leaf(sig, "get", cmd_signals_get, "get one signal with its impact forecast")
|
|
416
|
+
sp.add_argument("signal_id")
|
|
417
|
+
|
|
418
|
+
# exposure
|
|
419
|
+
exp = group("exposure", "match items against active disruptions")
|
|
420
|
+
sp = leaf(exp, "check", cmd_exposure_check, "check items (POST /v1/exposure/check)", table=True)
|
|
421
|
+
sp.add_argument("--file", required=True, metavar="PATH",
|
|
422
|
+
help="JSON list of items, or {\"items\": [...]}; '-' reads stdin")
|
|
423
|
+
sp.add_argument("--min-severity", choices=SEVERITIES)
|
|
424
|
+
|
|
425
|
+
# forecast
|
|
426
|
+
sp = leaf(sub, "forecast", cmd_forecast, "what history says an IT outage does (GET /v1/forecast)")
|
|
427
|
+
sp.add_argument("failure_layer", help="a failure layer id, e.g. identity, edge_cdn_dns")
|
|
428
|
+
sp.add_argument("--provider", help="e.g. aws, azure, gcp, cloudflare")
|
|
429
|
+
|
|
430
|
+
# reference
|
|
431
|
+
ap = group("airports", "airport profiles")
|
|
432
|
+
leaf(ap, "get", cmd_airports_get, "get an airport profile").add_argument("iata")
|
|
433
|
+
ca = group("carriers", "airline profiles")
|
|
434
|
+
leaf(ca, "get", cmd_carriers_get, "get an airline profile").add_argument("code")
|
|
435
|
+
pr = group("providers", "watched IT providers")
|
|
436
|
+
leaf(pr, "list", cmd_providers_list, "list providers and their incident status", table=True)
|
|
437
|
+
|
|
438
|
+
# watchlists
|
|
439
|
+
wl = group("watchlists", "saved items matched against every new signal")
|
|
440
|
+
leaf(wl, "list", cmd_watchlists_list, "list watchlists", table=True)
|
|
441
|
+
sp = leaf(wl, "get", cmd_watchlists_get, "get a watchlist and its items", table=True)
|
|
442
|
+
sp.add_argument("wl_id")
|
|
443
|
+
sp.add_argument("--limit", type=int, help="items to return, 1 to 1000 (default 100)")
|
|
444
|
+
sp = leaf(wl, "create", cmd_watchlists_create, "create a watchlist")
|
|
445
|
+
sp.add_argument("--name", required=True)
|
|
446
|
+
sp.add_argument("--description")
|
|
447
|
+
sp.add_argument("--file", metavar="PATH", help="initial items as JSON; '-' reads stdin")
|
|
448
|
+
sp = leaf(wl, "add-items", cmd_watchlists_add_items, "add or replace items, keyed by their id")
|
|
449
|
+
sp.add_argument("wl_id")
|
|
450
|
+
sp.add_argument("--file", required=True, metavar="PATH", help="items as JSON; '-' reads stdin")
|
|
451
|
+
sp = leaf(wl, "remove-item", cmd_watchlists_remove_item, "remove one item by its id")
|
|
452
|
+
sp.add_argument("wl_id")
|
|
453
|
+
sp.add_argument("ref", help="the item's id")
|
|
454
|
+
sp = leaf(wl, "delete", cmd_watchlists_delete, "delete a watchlist and its items")
|
|
455
|
+
sp.add_argument("wl_id")
|
|
456
|
+
sp = leaf(wl, "exposure", cmd_watchlists_exposure, "items that active signals touch now", table=True)
|
|
457
|
+
sp.add_argument("wl_id")
|
|
458
|
+
sp.add_argument("--min-severity", choices=SEVERITIES)
|
|
459
|
+
|
|
460
|
+
# webhooks
|
|
461
|
+
wh = group("webhooks", "signed push notifications")
|
|
462
|
+
leaf(wh, "list", cmd_webhooks_list, "list webhooks", table=True)
|
|
463
|
+
sp = leaf(wh, "create", cmd_webhooks_create, "create a webhook; prints the secret once")
|
|
464
|
+
sp.add_argument("--url", required=True, help="public https URL on port 443 or 8443")
|
|
465
|
+
for name, help_ in (("types", "signal types"), ("countries", "ISO alpha-2 codes"), ("airports", "IATA codes"),
|
|
466
|
+
("carriers", "IATA airline codes"), ("events", "created, escalated, updated, resolved"),
|
|
467
|
+
("watchlists", "watchlist ids, or '*' for all")):
|
|
468
|
+
sp.add_argument(f"--{name}", action="append", metavar="LIST", help=f"{help_}; repeat or comma-separate")
|
|
469
|
+
sp.add_argument("--min-severity", choices=SEVERITIES)
|
|
470
|
+
sp.add_argument("--filters", metavar="JSON", help="filters as a JSON object (merged with the options above)")
|
|
471
|
+
sp = leaf(wh, "delete", cmd_webhooks_delete, "disable a webhook")
|
|
472
|
+
sp.add_argument("hook_id")
|
|
473
|
+
sp = leaf(wh, "verify", cmd_webhooks_verify, "verify a delivery's Disrupt-Signature locally (no API call)")
|
|
474
|
+
sp.add_argument("--secret", help="the webhook secret, whsec_... (default: $DISRUPT_WEBHOOK_SECRET)")
|
|
475
|
+
sp.add_argument("--signature", required=True,
|
|
476
|
+
help="the Disrupt-Signature header (t=...,v1=...), or just the v1 hex digest")
|
|
477
|
+
sp.add_argument("--timestamp", type=int, help="the t= value; required with a bare v1 digest")
|
|
478
|
+
sp.add_argument("--body-file", required=True, metavar="PATH", help="the raw request body; '-' reads stdin")
|
|
479
|
+
sp.add_argument("--tolerance", type=int, default=300, help="max age in seconds (default 300)")
|
|
480
|
+
sp.add_argument("--ignore-age", action="store_true", help="check only the HMAC, not the timestamp age")
|
|
481
|
+
|
|
482
|
+
# account
|
|
483
|
+
sp = leaf(sub, "usage", cmd_usage, "requests per day, by route and by key", table=True)
|
|
484
|
+
sp.add_argument("--days", type=int, help="1 to 365 (default 30)")
|
|
485
|
+
leaf(sub, "me", cmd_me, "the organisation, plan and key behind your key")
|
|
486
|
+
leaf(sub, "plans", cmd_plans, "every plan and its limits (no key needed)", table=True)
|
|
487
|
+
return p
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def main(argv: Optional[Sequence[str]] = None, *, transport: Optional[httpx.BaseTransport] = None,
|
|
491
|
+
stdout: Optional[IO[str]] = None, stderr: Optional[IO[str]] = None, stdin: Optional[IO[str]] = None,
|
|
492
|
+
env: Optional[Dict[str, str]] = None) -> int:
|
|
493
|
+
out, err = stdout or sys.stdout, stderr or sys.stderr
|
|
494
|
+
parser = build_parser()
|
|
495
|
+
try:
|
|
496
|
+
args = parser.parse_args(argv)
|
|
497
|
+
except SystemExit as exc: # --help, --version (0) and usage errors (2)
|
|
498
|
+
return int(exc.code) if isinstance(exc.code, int) else EXIT_USAGE
|
|
499
|
+
ctx = Context(args, transport, out, err, stdin or sys.stdin, dict(os.environ) if env is None else env)
|
|
500
|
+
try:
|
|
501
|
+
code = args.handler(args, ctx)
|
|
502
|
+
return EXIT_OK if code is None else int(code)
|
|
503
|
+
except UsageError as exc:
|
|
504
|
+
err.write(f"disruptapi: error: {exc}\n")
|
|
505
|
+
return EXIT_USAGE
|
|
506
|
+
except (AuthenticationError, PermissionDeniedError) as exc:
|
|
507
|
+
err.write(f"{exc.code}: {exc.message}\n")
|
|
508
|
+
return EXIT_AUTH
|
|
509
|
+
except DisruptError as exc:
|
|
510
|
+
err.write(f"{exc.code}: {exc.message}\n")
|
|
511
|
+
if isinstance(exc.details, list):
|
|
512
|
+
for d in exc.details[:20]:
|
|
513
|
+
if isinstance(d, dict):
|
|
514
|
+
err.write(f" {'.'.join(str(x) for x in d.get('loc', []))}: {d.get('msg', '')}\n")
|
|
515
|
+
return EXIT_API
|
|
516
|
+
except KeyboardInterrupt:
|
|
517
|
+
err.write("interrupted\n")
|
|
518
|
+
return 130
|
|
519
|
+
except BrokenPipeError:
|
|
520
|
+
return EXIT_OK
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def run() -> None:
|
|
524
|
+
"""Console-script entry point."""
|
|
525
|
+
sys.exit(main())
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
if __name__ == "__main__":
|
|
529
|
+
run()
|