-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchangegraph.py
More file actions
414 lines (384 loc) · 15.1 KB
/
Copy pathchangegraph.py
File metadata and controls
414 lines (384 loc) · 15.1 KB
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
"""
ChangeGraph API client.
Zero dependencies beyond the standard library — no requests, no httpx — so it
drops into any environment without a dependency negotiation.
from changegraph import ChangeGraph
client = ChangeGraph() # reads CHANGEGRAPH_API_KEY
client = ChangeGraph("sp_live_…") # or pass it explicitly
Start free-key verification, then claim the token delivered by email:
curl -X POST https://changegraph-api.com/v1/keys \
-H 'content-type: application/json' \
-d '{"email":"you@example.com","source":{"source":"sdk","medium":"python"}}'
"""
from __future__ import annotations
import json
import os
import urllib.error
import urllib.parse
import urllib.request
__all__ = ["ChangeGraph", "ApiError", "API_TITLE", "API_VERSION", "API_BASE_URL", "ERROR_CODES", "OPERATIONS"]
DEFAULT_BASE_URL = "https://changegraph-api.com"
class ApiError(Exception):
"""
Raised for any non-2xx response.
Branch on ``code`` — it is a stable enum, unlike the message. Always quote
``request_id`` when reporting a problem; it identifies the exact request in
the service's logs.
"""
def __init__(self, status: int, code: str, message: str, request_id: str | None = None, details=None):
super().__init__(f"[{status} {code}] {message}")
self.status = status
self.code = code
self.message = message
self.request_id = request_id
self.details = details
class ChangeGraph:
def __init__(self, api_key: str | None = None, *, base_url: str = DEFAULT_BASE_URL, timeout: float = 30.0):
key = api_key or os.environ.get("CHANGEGRAPH_API_KEY")
if not key:
raise ValueError(
"No API key. Pass one to ChangeGraph(...) or set CHANGEGRAPH_API_KEY. "
"Request a free key verification email: POST {}/v1/keys with {{\"email\": \"you@example.com\"}}".format(base_url)
)
self.api_key = key
self.base_url = base_url.rstrip("/")
self.timeout = timeout
# -- transport ---------------------------------------------------------
def _request(self, method: str, path: str, *, json_body=None, json=None, params=None) -> dict:
import json as _json
body = json if json is not None else json_body
url = self.base_url + path
if params:
url += "?" + urllib.parse.urlencode({k: v for k, v in params.items() if v is not None})
data = _json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(url, data=data, method=method)
req.add_header("Authorization", f"Bearer {self.api_key}")
req.add_header("Accept", "application/json")
if data:
req.add_header("Content-Type", "application/json")
try:
with urllib.request.urlopen(req, timeout=self.timeout) as res:
return _json.loads(res.read().decode() or "{}")
except urllib.error.HTTPError as e:
raw = e.read().decode()
try:
err = _json.loads(raw).get("error", {})
except Exception:
err = {}
raise ApiError(
e.code,
err.get("code", "unknown"),
err.get("message", raw[:200]),
err.get("requestId"),
err.get("details"),
) from None
def health(self) -> dict:
"""Liveness and deployed version. Does not require a key."""
return self._request("GET", "/health")
def create_monitor(self, subject: str, kinds: list[str] | None = None) -> dict:
"""Create a monitor for a subject."""
return self._request("POST", "/v1/monitors", json={"subject": subject, "kinds": kinds or []})
def list_monitors(self) -> dict:
"""List your monitors."""
return self._request("GET", "/v1/monitors")
def submit_snapshot(self, monitor_id: str, source: str, facts: dict[str, str], observed_at: str | None = None) -> dict:
"""Submit an observation; returns any changes detected against the previous one."""
return self._request("POST", f"/v1/monitors/{monitor_id}/snapshots", json={"source": source, "facts": facts, **({"observedAt": observed_at} if observed_at else {})})
def list_events(self, monitor_id: str, limit: int = 50) -> dict:
"""Read detected change events, newest first."""
return self._request("GET", f"/v1/monitors/{monitor_id}/events", params={"limit": limit})
# Defined on the class, not bolted on afterwards: a module-level
# @staticmethod re-assigned onto the class is only callable on Python
# 3.10+, and raises TypeError on 3.8/3.9.
@staticmethod
def create_key(
email: str,
*,
base_url: str = DEFAULT_BASE_URL,
name: str | None = None,
source: dict[str, str] | None = None,
) -> dict:
"""Start free-key verification. Claim the emailed token to receive the key once."""
import json as _json
payload = {"email": email, "source": source if source is not None else {"source": "sdk", "medium": "python"}}
if name:
payload["name"] = name
req = urllib.request.Request(base_url.rstrip("/") + "/v1/keys", data=_json.dumps(payload).encode(), method="POST")
req.add_header("Content-Type", "application/json")
with urllib.request.urlopen(req, timeout=30) as res:
return _json.loads(res.read().decode())
# ---8<--- BEGIN GENERATED BY tools/gen-sdk.mjs — DO NOT EDIT BELOW ---8<---
# Everything between these markers is written from openapi.json. Change the
# service, regenerate the contract, then re-run `npm run gen:sdk`.
#: The contract this SDK was generated from.
API_TITLE = "ChangeGraph API"
API_VERSION = "1.0.0"
#: The origin the published contract names.
API_BASE_URL = "https://changegraph-api.com"
#: Every ``error.code`` the contract publishes. Branch on these, never on the message.
ERROR_CODES = ("invalid_api_key", "missing_api_key", "quota_exceeded", "rate_limited", "invalid_request", "not_found", "method_not_allowed", "payload_too_large", "conflict", "internal_error")
#: The published surface, generated. Ships with the client so an integration
#: can assert against the contract instead of against a changelog.
OPERATIONS = (
{
"operation_id": "get/",
"method": "GET",
"path": "/",
"summary": "Service index — endpoints, auth and error format",
"auth": False,
"auth_kind": "public",
"path_params": (),
"query_params": (),
"required_body_fields": (),
"success_status": 200,
"response_fields": (),
},
{
"operation_id": "postApiBillingWebhook",
"method": "POST",
"path": "/api/billing/webhook",
"summary": "Square billing events, forwarded by the shared hub",
"auth": False,
"auth_kind": "signature",
"path_params": (),
"query_params": (),
"required_body_fields": (),
"success_status": 200,
"response_fields": (),
},
{
"operation_id": "getHealth",
"method": "GET",
"path": "/health",
"summary": "Liveness and deployed version",
"auth": False,
"auth_kind": "public",
"path_params": (),
"query_params": (),
"required_body_fields": (),
"success_status": 200,
"response_fields": (),
},
{
"operation_id": "postV1Checkout",
"method": "POST",
"path": "/v1/checkout",
"summary": "Start a hosted Square checkout for a paid tier",
"auth": False,
"auth_kind": "public",
"path_params": (),
"query_params": (),
"required_body_fields": ("tier",),
"success_status": 200,
"response_fields": ("checkoutUrl", "tier", "sku", "requestId"),
},
{
"operation_id": "postV1DemoDetect",
"method": "POST",
"path": "/v1/demo/detect",
"summary": "Public demo — detect changes without a key",
"auth": False,
"auth_kind": "public",
"path_params": (),
"query_params": (),
"required_body_fields": (),
"success_status": 200,
"response_fields": (),
},
{
"operation_id": "getV1Invoices",
"method": "GET",
"path": "/v1/invoices",
"summary": "Every invoice issued against this account, newest first (dashboard session required)",
"auth": False,
"auth_kind": "session",
"path_params": (),
"query_params": (),
"required_body_fields": (),
"success_status": 200,
"response_fields": ("product", "count", "note", "invoices", "requestId"),
},
{
"operation_id": "getV1Keys",
"method": "GET",
"path": "/v1/keys",
"summary": "List your API keys for this API",
"auth": True,
"auth_kind": "api_key",
"path_params": (),
"query_params": (),
"required_body_fields": (),
"success_status": 200,
"response_fields": ("product", "accountId", "keys", "requestId"),
},
{
"operation_id": "postV1Keys",
"method": "POST",
"path": "/v1/keys",
"summary": "Request a free sandbox API key (sends a verification email)",
"auth": False,
"auth_kind": "public",
"path_params": (),
"query_params": (),
"required_body_fields": ("email",),
"success_status": 202,
"response_fields": ("status", "email", "expiresAt", "next", "message", "requestId"),
},
{
"operation_id": "postV1KeysIdRevoke",
"method": "POST",
"path": "/v1/keys/{id}/revoke",
"summary": "Revoke one of your API keys",
"auth": True,
"auth_kind": "api_key",
"path_params": ("id",),
"query_params": (),
"required_body_fields": (),
"success_status": 200,
"response_fields": ("id", "status", "message", "requestId"),
},
{
"operation_id": "postV1KeysIdRotate",
"method": "POST",
"path": "/v1/keys/{id}/rotate",
"summary": "Replace one of your API keys with a new secret",
"auth": True,
"auth_kind": "api_key",
"path_params": ("id",),
"query_params": (),
"required_body_fields": (),
"success_status": 201,
"response_fields": ("apiKey", "keyId", "replaced", "product", "quotaPerPeriod", "plan", "warning", "requestId"),
},
{
"operation_id": "postV1KeysClaim",
"method": "POST",
"path": "/v1/keys/claim",
"summary": "Exchange an emailed claim token for the API key",
"auth": False,
"auth_kind": "public",
"path_params": (),
"query_params": (),
"required_body_fields": ("token",),
"success_status": 201,
"response_fields": ("apiKey", "keyId", "product", "quotaPerPeriod", "plan", "warning", "usage", "requestId"),
},
{
"operation_id": "getV1Monitors",
"method": "GET",
"path": "/v1/monitors",
"summary": "List your monitors",
"auth": True,
"auth_kind": "api_key",
"path_params": (),
"query_params": (),
"required_body_fields": (),
"success_status": 200,
"response_fields": (),
},
{
"operation_id": "postV1Monitors",
"method": "POST",
"path": "/v1/monitors",
"summary": "Create a monitor",
"auth": True,
"auth_kind": "api_key",
"path_params": (),
"query_params": (),
"required_body_fields": ("subject",),
"success_status": 201,
"response_fields": ("id", "subject", "kinds", "createdAt"),
},
{
"operation_id": "getV1MonitorsIdEvents",
"method": "GET",
"path": "/v1/monitors/{id}/events",
"summary": "Read detected change events, newest first",
"auth": True,
"auth_kind": "api_key",
"path_params": ("id",),
"query_params": ("limit",),
"required_body_fields": (),
"success_status": 200,
"response_fields": (),
},
{
"operation_id": "postV1MonitorsIdSnapshots",
"method": "POST",
"path": "/v1/monitors/{id}/snapshots",
"summary": "Submit an observation and receive detected changes",
"auth": True,
"auth_kind": "api_key",
"path_params": ("id",),
"query_params": (),
"required_body_fields": ("source", "facts"),
"success_status": 201,
"response_fields": ("snapshotId", "monitorId", "baseline", "eventCount", "events"),
},
{
"operation_id": "getV1Payments",
"method": "GET",
"path": "/v1/payments",
"summary": "Every payment attempted against this account and how it went (dashboard session required)",
"auth": False,
"auth_kind": "session",
"path_params": (),
"query_params": (),
"required_body_fields": (),
"success_status": 200,
"response_fields": ("product", "count", "note", "payments", "requestId"),
},
{
"operation_id": "getV1Subscription",
"method": "GET",
"path": "/v1/subscription",
"summary": "Your current plan, billing window and available changes (dashboard session required)",
"auth": False,
"auth_kind": "session",
"path_params": (),
"query_params": (),
"required_body_fields": (),
"success_status": 200,
"response_fields": ("product", "subscribed", "status", "plan", "pendingPlan", "planChangesGoThrough", "baseFeeOwner", "cancellation", "tiers", "requestId"),
},
{
"operation_id": "postV1SubscriptionCancel",
"method": "POST",
"path": "/v1/subscription/cancel",
"summary": "Cancel this plan and end metered access (dashboard session required)",
"auth": False,
"auth_kind": "session",
"path_params": (),
"query_params": (),
"required_body_fields": (),
"success_status": 200,
"response_fields": ("canceled", "canceledAt", "entitlement", "money", "finalInvoice", "requestId"),
},
{
"operation_id": "postV1SubscriptionPlan",
"method": "POST",
"path": "/v1/subscription/plan",
"summary": "Upgrade or downgrade to another plan (dashboard session required)",
"auth": False,
"auth_kind": "session",
"path_params": (),
"query_params": (),
"required_body_fields": ("planId",),
"success_status": 200,
"response_fields": ("changed", "direction", "from", "to", "entitlement", "billing", "requestId"),
},
{
"operation_id": "getV1Usage",
"method": "GET",
"path": "/v1/usage",
"summary": "Your consumption and remaining allowance for this period",
"auth": True,
"auth_kind": "api_key",
"path_params": (),
"query_params": (),
"required_body_fields": (),
"success_status": 200,
"response_fields": ("product", "tier", "status", "unit", "period", "included", "used", "ceiling", "remaining", "overageSoFarMinor", "spendCapMinor", "requestId"),
},
)
# ---8<--- END GENERATED BY tools/gen-sdk.mjs ---8<---