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/types.py ADDED
@@ -0,0 +1,455 @@
1
+ """Models for DisruptAPI v1 responses and request bodies, as TypedDicts.
2
+
3
+ The OpenAPI spec (1.0.0) describes request bodies but not response bodies, so the
4
+ response types are hand-written to match the server's serialisers and the public docs.
5
+ At runtime every value is a plain ``dict``; the types are for editors and type checkers.
6
+ Field names are the API's own.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any, Dict, List, Literal, Optional, TypedDict, Union
12
+
13
+ Severity = Literal["minor", "moderate", "severe", "extreme"]
14
+ RiskLevel = Literal["none", "low", "elevated", "high", "severe"]
15
+ SignalStatus = Literal["active", "resolved"]
16
+ ItemKind = Literal["flight", "trip", "place", "carrier", "provider"]
17
+ WebhookEventName = Literal["created", "escalated", "updated", "resolved"]
18
+ # aviation, weather, natural_hazard, security, it_outage, internet, health, labor, infrastructure
19
+ SignalType = str
20
+
21
+
22
+ class PageMeta(TypedDict):
23
+ total: int
24
+ limit: int
25
+ offset: int
26
+
27
+
28
+ class Location(TypedDict, total=False):
29
+ lat: float
30
+ lon: float
31
+ basis: str # "source" or "airports"
32
+
33
+
34
+ class SignalSource(TypedDict, total=False):
35
+ url: Optional[str]
36
+ attribution: Optional[str]
37
+ last_checked_at: Optional[str]
38
+ stale: bool
39
+
40
+
41
+ class ForecastDuration(TypedDict):
42
+ p50: Optional[float]
43
+ p90: Optional[float]
44
+ n: int
45
+ analog_level: str
46
+
47
+
48
+ class ForecastOutcome(TypedDict, total=False):
49
+ outcome: str
50
+ label: str
51
+ probability: float
52
+ interval: List[float]
53
+ interval_level: float
54
+ k: int
55
+ n: int
56
+ analog_level: str
57
+ low_confidence: bool
58
+ evidence: str
59
+ base_rate: Optional[Dict[str, Any]]
60
+ lift: Optional[float]
61
+ above_base_rate: Optional[bool]
62
+
63
+
64
+ class Forecast(TypedDict, total=False):
65
+ basis: str # "analogs" or "insufficient_history"
66
+ failure_layer: Optional[str]
67
+ failure_layer_label: Optional[str]
68
+ analog_count: int
69
+ analogs: List[Any]
70
+ outcomes: List[ForecastOutcome]
71
+ expected_duration_hours: Optional[ForecastDuration]
72
+ carriers_at_elevated_risk: List[Any]
73
+ contrast: Optional[str]
74
+ recommended_actions: List[str]
75
+ notes: List[str]
76
+ airport_base_rates: Dict[str, Any]
77
+
78
+
79
+ class Place(TypedDict, total=False):
80
+ name: str
81
+ kind: str
82
+ within: Optional[str]
83
+
84
+
85
+ class AirportLocation(TypedDict, total=False):
86
+ iata: str
87
+ icao: Optional[str]
88
+ name: str
89
+ city: Optional[str]
90
+ country: str
91
+ lat: float
92
+ lon: float
93
+
94
+
95
+ class OutlookOutcome(TypedDict, total=False):
96
+ outcome: str
97
+ label: Optional[str]
98
+ probability: float
99
+ normal_probability: Optional[float]
100
+ events_measured: Optional[int]
101
+ measured_at: Optional[str]
102
+ more_likely_than_normal: Optional[bool]
103
+ low_confidence: bool
104
+ method: Optional[str]
105
+
106
+
107
+ class Outlook(TypedDict, total=False):
108
+ summary: Optional[str]
109
+ summary_lang: Optional[str]
110
+ basis: Optional[str]
111
+ outcomes: List[OutlookOutcome]
112
+ expected_duration_hours: Optional[Dict[str, Any]]
113
+
114
+
115
+ class Signal(TypedDict, total=False):
116
+ id: str # per-account id "<internal>.<tag>"
117
+ type: SignalType
118
+ subtype: Optional[str]
119
+ provider: Optional[str]
120
+ failure_layer: Optional[str]
121
+ failure_layer_label: Optional[str]
122
+ title: Optional[str]
123
+ headline: Optional[str] # AI-written in English answers when we have one, else the title
124
+ summary: Optional[str] # AI-written, English only, or None
125
+ description: Optional[str] # for travellers, ready to show customers (AI-written, English only)
126
+ outlook: Optional[Outlook] # history-based; always on get_signal, on lists with include="outlook"
127
+ headline_basis: Optional[Dict[str, Any]]
128
+ severity: Severity
129
+ status: SignalStatus
130
+ countries: List[str]
131
+ airports: List[str]
132
+ areas: List[str]
133
+ places: List[Place]
134
+ location: Optional[Location] # includes "basis": "source" or "airports"
135
+ airport_locations: List[AirportLocation]
136
+ starts_at: Optional[str]
137
+ ends_at: Optional[str]
138
+ first_seen_at: str
139
+ updated_at: str
140
+ version: int
141
+ source: SignalSource
142
+ details: Dict[str, Any]
143
+ impact_forecast: Forecast # GET /v1/signals/{id} only
144
+
145
+
146
+ class FailureLayer(TypedDict):
147
+ id: str
148
+ label: str
149
+
150
+
151
+ class Leg(TypedDict, total=False):
152
+ carrier: Optional[str]
153
+ origin: Optional[str]
154
+ destination: Optional[str]
155
+ depart_at: Optional[str]
156
+ arrive_at: Optional[str]
157
+
158
+
159
+ class Item(TypedDict, total=False):
160
+ """Anything you want checked. Set ``kind``, or the API infers it. Extra keys are allowed."""
161
+
162
+ id: Optional[str]
163
+ kind: Optional[ItemKind]
164
+ label: Optional[str]
165
+ carrier: Optional[str]
166
+ carriers: Optional[List[str]]
167
+ origin: Optional[str]
168
+ destination: Optional[str]
169
+ via: Optional[List[str]]
170
+ legs: Optional[List[Leg]]
171
+ depart_at: Optional[str]
172
+ return_at: Optional[str]
173
+ airport: Optional[str]
174
+ lat: Optional[float]
175
+ lon: Optional[float]
176
+ radius_km: Optional[float]
177
+ country: Optional[str]
178
+ countries: Optional[List[str]]
179
+ starts_at: Optional[str]
180
+ ends_at: Optional[str]
181
+ provider: Optional[str]
182
+ failure_layer: Optional[str]
183
+ expires_at: Optional[str]
184
+
185
+
186
+ ItemLike = Union[Item, Dict[str, Any]]
187
+
188
+
189
+ class ExposureForecast(TypedDict):
190
+ outcomes: List[ForecastOutcome]
191
+ recommended_actions: List[str]
192
+ expected_duration_hours: Optional[ForecastDuration]
193
+
194
+
195
+ class ExposureMatch(TypedDict, total=False):
196
+ signal: Signal
197
+ reasons: List[str]
198
+ risk_contribution: RiskLevel
199
+ forecast: Optional[ExposureForecast]
200
+ grouped_signals: int
201
+ areas_sample: List[str]
202
+
203
+
204
+ class ExposureResult(TypedDict, total=False):
205
+ item_id: Optional[str]
206
+ trip_id: Optional[str] # same as item_id
207
+ kind: ItemKind
208
+ risk_level: RiskLevel
209
+ match_count: int
210
+ matches: List[ExposureMatch] # at most 20
211
+ warnings: List[str]
212
+ watchlist_id: str # watchlist exposure only
213
+
214
+
215
+ class Watchlist(TypedDict, total=False):
216
+ id: str
217
+ org_id: str
218
+ name: str
219
+ description: Optional[str]
220
+ created_at: str
221
+ deleted_at: Optional[str]
222
+ items: Any # int (live count) in list(), List[Item] in get()
223
+ items_stored: int # create() with items
224
+
225
+
226
+ class WatchlistLimits(TypedDict):
227
+ watch_items: int # -1 = unlimited
228
+ used: int
229
+
230
+
231
+ class WatchlistList(TypedDict):
232
+ data: List[Watchlist]
233
+ limits: WatchlistLimits
234
+
235
+
236
+ class ItemsUpsertResult(TypedDict):
237
+ stored: int
238
+ new: int
239
+
240
+
241
+ class Deleted(TypedDict):
242
+ id: str
243
+ deleted: bool
244
+
245
+
246
+ class Airport(TypedDict, total=False):
247
+ iata: str
248
+ icao: Optional[str]
249
+ name: str
250
+ city: Optional[str]
251
+ country: str
252
+ lat: float
253
+ lon: float
254
+ size: Optional[str]
255
+
256
+
257
+ class Dependency(TypedDict, total=False):
258
+ provider: str
259
+ layer: str
260
+ confidence: str
261
+ seen_at: Optional[str]
262
+
263
+
264
+ class AirportProfile(TypedDict):
265
+ airport: Airport
266
+ active_signals: List[Signal]
267
+ country_signals: List[Signal]
268
+ base_rates_by_month: List[Dict[str, Any]]
269
+ website_dependencies: List[Dependency]
270
+
271
+
272
+ class CarrierProfile(TypedDict):
273
+ carrier: str
274
+ domain: Optional[str]
275
+ dependencies: List[Dependency]
276
+ providers: List[str]
277
+ active_it_outages_affecting: List[Dict[str, Any]]
278
+ past_events: List[Dict[str, Any]]
279
+
280
+
281
+ class Source(TypedDict, total=False):
282
+ id: str
283
+ name: str
284
+ publisher: str
285
+ signal_types: List[str]
286
+ coverage: str
287
+ licence: Dict[str, Any]
288
+ attribution: str
289
+ feeds: int
290
+ checked_every_s: int
291
+ last_checked_at: Optional[str]
292
+ stale_feeds: int
293
+ status: Literal["ok", "degraded", "stale"]
294
+
295
+
296
+ class Provider(TypedDict):
297
+ provider: str
298
+ status: Literal["operational", "incident"]
299
+ active_incidents: int
300
+ worst_severity: Optional[Severity]
301
+
302
+
303
+ class EventOutcome(TypedDict, total=False):
304
+ outcome: str
305
+ happened: bool
306
+ basis: str
307
+ detail: Any # GET /v1/events/{id} only
308
+
309
+
310
+ class PastEvent(TypedDict, total=False):
311
+ id: str
312
+ source: str
313
+ type: str
314
+ provider: Optional[str]
315
+ failure_layer: Optional[str]
316
+ title: str
317
+ starts_at: str
318
+ ends_at: Optional[str]
319
+ duration_h: Optional[float]
320
+ url: Optional[str]
321
+ regions: List[str]
322
+ is_anchor: bool
323
+ outcomes: List[EventOutcome]
324
+ carriers_affected: List[Dict[str, str]]
325
+
326
+
327
+ class WebhookFilters(TypedDict, total=False):
328
+ types: List[str]
329
+ min_severity: Severity
330
+ countries: List[str]
331
+ airports: List[str]
332
+ carriers: List[str]
333
+ events: List[WebhookEventName]
334
+ watchlists: List[str] # ["*"] or watchlist ids
335
+
336
+
337
+ WebhookFormat = Literal["json", "slack", "teams", "pagerduty"]
338
+
339
+
340
+ class Webhook(TypedDict, total=False):
341
+ id: str
342
+ org_id: str
343
+ url: str
344
+ secret: str # full only in the create and rotate-secret responses
345
+ filters: WebhookFilters
346
+ format: WebhookFormat
347
+ created_at: str
348
+ disabled_at: Optional[str]
349
+ failures: int
350
+
351
+
352
+ class WebhookDelivery(TypedDict, total=False):
353
+ id: str # dlv_...
354
+ webhook_id: str
355
+ event: str
356
+ signal_id: Optional[str]
357
+ signal_version: Optional[int]
358
+ status: str # pending, delivered or failed
359
+ attempts: int
360
+ last_status: Optional[int] # the receiver's last HTTP status
361
+ last_error: Optional[str]
362
+ last_attempt_at: Optional[str]
363
+ next_attempt_at: Optional[str] # only while pending
364
+ created_at: str
365
+
366
+
367
+ class Change(TypedDict, total=False):
368
+ cursor: str # opaque; pass it as ``after`` to resume
369
+ event: str # created, updated, escalated, resolved, expired, ...
370
+ version: int
371
+ recorded_at: str
372
+ signal: Signal
373
+
374
+
375
+ class ChangeMeta(TypedDict, total=False):
376
+ next_cursor: Optional[str]
377
+ has_more: bool
378
+ limit: int
379
+ lang: str
380
+
381
+
382
+ class ChangePage(TypedDict):
383
+ data: List[Change]
384
+ meta: ChangeMeta
385
+
386
+
387
+ class Incident(TypedDict, total=False):
388
+ id: str
389
+ status: str # active or resolved
390
+ hazard: Optional[str]
391
+ type: str
392
+ types: List[str]
393
+ title: Optional[str]
394
+ headline: Optional[str]
395
+ severity: Severity
396
+ member_count: int
397
+ primary_signal_id: str
398
+ countries: List[str]
399
+ airports: List[str]
400
+ starts_at: Optional[str]
401
+ ends_at: Optional[str]
402
+ first_seen_at: str
403
+ updated_at: str
404
+ resolved_at: Optional[str]
405
+ merged_into: Optional[str]
406
+ signals: List[Signal] # on GET /v1/incidents/{id}
407
+
408
+
409
+ class SeverityLevel(TypedDict):
410
+ id: Severity
411
+ rank: int
412
+ meaning: str
413
+
414
+
415
+ class ExposedItem(TypedDict):
416
+ item_id: str
417
+ kind: str
418
+ watchlist_id: str
419
+ reasons: List[str]
420
+ risk_contribution: RiskLevel
421
+
422
+
423
+ class WebhookEvent(TypedDict, total=False):
424
+ id: str # evt_..., new on every delivery attempt
425
+ type: str # signal.<event> or exposure.<event>
426
+ api_version: str # payload version, e.g. "2026-12-01" (also the Disrupt-Webhook-Version header)
427
+ created_at: str
428
+ data: Dict[str, Any] # a Signal, or {"signal": Signal, "exposed_items": [ExposedItem]}
429
+
430
+
431
+ class Plan(TypedDict, total=False):
432
+ id: str
433
+ name: str
434
+ price_usd_month: Optional[float]
435
+ monthly_requests: Optional[int]
436
+ per_minute: int
437
+ webhooks: int
438
+ exposure_check: bool
439
+ description: str
440
+ watch_items: int
441
+
442
+
443
+ class Me(TypedDict):
444
+ org: Dict[str, Any]
445
+ key: Dict[str, Any]
446
+ requests_this_month: int
447
+
448
+
449
+ class Usage(TypedDict, total=False):
450
+ month: str
451
+ requests_this_month: int
452
+ daily: List[Dict[str, Any]]
453
+ by_route_this_month: List[Dict[str, Any]]
454
+ by_key_this_month: List[Dict[str, Any]]
455
+ plan: Plan
disruptapi/webhooks.py ADDED
@@ -0,0 +1,122 @@
1
+ """Webhook signature verification.
2
+
3
+ Every delivery has ``Disrupt-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256>``. The HMAC
4
+ key is the whole secret (including ``whsec_``); the signed bytes are ``<t>.`` followed by the
5
+ raw request body. Deliveries more than 300 seconds from your clock are refused. This
6
+ matches ``sign()`` / ``verify_signature()`` in the server's disrupt/api/webhooks.py.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import hmac
13
+ import json
14
+ import time
15
+ from typing import Any, List, Optional, Tuple, Union
16
+
17
+ from ._errors import WebhookSignatureError
18
+ from .types import WebhookEvent
19
+
20
+ SIGNATURE_HEADER = "Disrupt-Signature"
21
+ DEFAULT_TOLERANCE = 300
22
+
23
+ Payload = Union[bytes, bytearray, memoryview, str]
24
+
25
+
26
+ def _bytes(payload: Payload) -> bytes:
27
+ if isinstance(payload, str):
28
+ return payload.encode("utf-8")
29
+ if isinstance(payload, (bytes, bytearray, memoryview)):
30
+ return bytes(payload)
31
+ raise TypeError("payload must be the raw request body as bytes or str")
32
+
33
+
34
+ def compute_signature(payload: Payload, secret: str, timestamp: int) -> str:
35
+ """Hex HMAC-SHA256 of ``<timestamp>.<payload>`` keyed with the secret."""
36
+ return hmac.new(secret.encode("utf-8"), f"{timestamp}.".encode() + _bytes(payload), hashlib.sha256).hexdigest()
37
+
38
+
39
+ def parse_signature_header(header: Optional[str]) -> Optional[Tuple[int, List[str]]]:
40
+ """``(t, [v1, ...])``, or None if the header is missing or malformed."""
41
+ if not header:
42
+ return None
43
+ t: Optional[int] = None
44
+ v1: List[str] = []
45
+ for part in header.split(","):
46
+ if "=" not in part:
47
+ return None # the server's parser refuses this too
48
+ k, v = part.split("=", 1)
49
+ k, v = k.strip(), v.strip()
50
+ if k == "t":
51
+ try:
52
+ t = int(v)
53
+ except ValueError:
54
+ return None
55
+ elif k == "v1":
56
+ v1.append(v)
57
+ if t is None:
58
+ return None
59
+ return t, v1
60
+
61
+
62
+ def verify_signature(payload: Payload, header: Optional[str], secret: str, *,
63
+ tolerance: int = DEFAULT_TOLERANCE, now: Optional[float] = None) -> bool:
64
+ """True when ``header`` is a valid signature of ``payload`` (the raw body, exactly as
65
+ received) with ``secret``, made within ``tolerance`` seconds."""
66
+ if not secret:
67
+ raise ValueError("secret is required")
68
+ parsed = parse_signature_header(header)
69
+ if parsed is None or not parsed[1]:
70
+ return False
71
+ t, candidates = parsed
72
+ if abs((time.time() if now is None else now) - t) > tolerance:
73
+ return False
74
+ expected = compute_signature(payload, secret, t)
75
+ ok = False
76
+ for v in candidates:
77
+ ok = hmac.compare_digest(expected, v.lower()) or ok
78
+ return ok
79
+
80
+
81
+ def construct_event(payload: Payload, header: Optional[str], secret: str, *,
82
+ tolerance: int = DEFAULT_TOLERANCE, now: Optional[float] = None) -> WebhookEvent:
83
+ """Verify, then parse the body. Raises ``WebhookSignatureError`` on failure."""
84
+ if not verify_signature(payload, header, secret, tolerance=tolerance, now=now):
85
+ parsed = parse_signature_header(header)
86
+ current = time.time() if now is None else now
87
+ if parsed is None:
88
+ reason = "missing or malformed Disrupt-Signature header"
89
+ elif abs(current - parsed[0]) > tolerance:
90
+ reason = "timestamp outside the tolerance"
91
+ else:
92
+ reason = "signature does not match"
93
+ raise WebhookSignatureError(f"webhook signature verification failed: {reason}", code="invalid_signature")
94
+ try:
95
+ event: Any = json.loads(_bytes(payload).decode("utf-8"))
96
+ except (ValueError, UnicodeDecodeError) as exc:
97
+ raise WebhookSignatureError("webhook body is not valid JSON", code="invalid_payload") from exc
98
+ return event # type: ignore[no-any-return]
99
+
100
+
101
+ def generate_test_header(payload: Payload, secret: str, timestamp: Optional[int] = None) -> str:
102
+ """A valid ``Disrupt-Signature`` header for ``payload``, to test your own handler."""
103
+ ts = int(time.time()) if timestamp is None else timestamp
104
+ return f"t={ts},v1={compute_signature(payload, secret, ts)}"
105
+
106
+
107
+ class Webhooks:
108
+ """Verification helpers, usable without a client: ``disruptapi.webhooks.verify_signature``."""
109
+
110
+ @staticmethod
111
+ def verify_signature(payload: Payload, header: Optional[str], secret: str, *,
112
+ tolerance: int = DEFAULT_TOLERANCE, now: Optional[float] = None) -> bool:
113
+ return verify_signature(payload, header, secret, tolerance=tolerance, now=now)
114
+
115
+ @staticmethod
116
+ def construct_event(payload: Payload, header: Optional[str], secret: str, *,
117
+ tolerance: int = DEFAULT_TOLERANCE, now: Optional[float] = None) -> WebhookEvent:
118
+ return construct_event(payload, header, secret, tolerance=tolerance, now=now)
119
+
120
+ @staticmethod
121
+ def generate_test_header(payload: Payload, secret: str, timestamp: Optional[int] = None) -> str:
122
+ return generate_test_header(payload, secret, timestamp)