intelligence-cloud 0.1.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.
@@ -0,0 +1,433 @@
1
+ """The Intelligence Cloud API client."""
2
+ from __future__ import annotations
3
+
4
+ import contextlib
5
+ import json
6
+ import random
7
+ import threading
8
+ import time
9
+ import uuid
10
+ from typing import Any, Callable, ContextManager, Dict, Iterator, Mapping, Optional
11
+ from urllib.parse import quote, urlsplit
12
+
13
+ import httpx
14
+
15
+ from . import _spec
16
+ from ._base import Page
17
+ from ._version import __version__
18
+ from .auth import MemoryTokenStore, Tokens, TokenStore
19
+ from .errors import (
20
+ EXTENSION_CONFLICT_MESSAGE,
21
+ ApiError,
22
+ AuthError,
23
+ ConflictError,
24
+ InvalidRequestError,
25
+ MfaRequiredError,
26
+ NotFoundError,
27
+ PasswordExpiredError,
28
+ RateLimitError,
29
+ ValidationError,
30
+ extension_conflict_numbers,
31
+ requested_numbers,
32
+ )
33
+
34
+ DEFAULT_BASE_URL = "https://app.intelligence.cloud/api/v1"
35
+
36
+ # Test endpoints whose error text is never surfaced (only success and the HTTP status).
37
+ SANITIZED_ERRORS = {"testConnector", "testFirstAlertWebhook", "testAfterCallWebhook"}
38
+ # Endpoints whose 409 is the extension-conflict check. The SDK replaces its text with a fixed message.
39
+ EXTENSION_CONFLICT_OPS = {"setUserNumberMappings", "updateUserAfterCallSettings"}
40
+ RETRY_METHODS = {"GET", "PUT", "PATCH", "DELETE"}
41
+ LOGIN_RATE_LIMIT_WAIT = 60.0
42
+ MAX_RETRY_AFTER = 60.0 # a longer Retry-After is not waited out: the request fails with RateLimitError
43
+ LOCAL_HOSTS = {"localhost", "127.0.0.1", "::1"}
44
+
45
+
46
+ def check_base_url(base_url: str) -> str:
47
+ """Refuse anything but https, except on this machine (localhost, 127.0.0.1, ::1)."""
48
+ parts = urlsplit(base_url)
49
+ host = (parts.hostname or "").lower()
50
+ if parts.scheme == "https" and host:
51
+ return base_url
52
+ if parts.scheme == "http" and host in LOCAL_HOSTS:
53
+ return base_url
54
+ raise InvalidRequestError("base_url must be an https:// URL (http:// only for localhost)")
55
+
56
+
57
+ class Client:
58
+ """Signs in with an integration user's email and password and calls the API.
59
+
60
+ One client per credential. Admin (reseller admin) and frontline logins see different data:
61
+ use one client for each.
62
+
63
+ >>> client = Client(email="integration@example.com", password="...")
64
+ >>> client.intelligence.whoami()["role"]
65
+ """
66
+
67
+ def __init__(
68
+ self,
69
+ base_url: str = DEFAULT_BASE_URL,
70
+ email: Optional[str] = None,
71
+ password: Optional[str] = None,
72
+ token_store: Optional[TokenStore] = None,
73
+ timeout: float = 30,
74
+ *,
75
+ user_agent: Optional[str] = None,
76
+ max_retries: int = 3,
77
+ transport: Optional[httpx.BaseTransport] = None,
78
+ sleep: Callable[[float], None] = time.sleep,
79
+ login_rate_limit_wait: float = LOGIN_RATE_LIMIT_WAIT,
80
+ keep_unknown_fields: bool = False,
81
+ ):
82
+ self.base_url = check_base_url(base_url).rstrip("/")
83
+ self._email = email
84
+ self._password = password
85
+ self._store: TokenStore = token_store or MemoryTokenStore()
86
+ self._auth_lock = threading.Lock()
87
+ self._max_retries = max_retries
88
+ self._sleep = sleep
89
+ self._login_wait = max(0.0, float(login_rate_limit_wait))
90
+ self.keep_unknown_fields = keep_unknown_fields
91
+ ua = f"intelligence-cloud-python/{__version__}"
92
+ if user_agent:
93
+ ua = f"{user_agent} {ua}"
94
+ self._http = httpx.Client(timeout=timeout, transport=transport, headers={"User-Agent": ua})
95
+ self._spent_refresh_tokens: set = set()
96
+
97
+ from .resources import (
98
+ AccountAPI, AfterCallSettingsAPI, AlertsAPI, CallsAPI, CompaniesAPI, ConnectorsAPI,
99
+ FirstAlertAPI, GroupsAPI, InsightsAPI, InsightsHubAPI, LocationsAPI, ProductsAPI,
100
+ ResellersAPI, SsoAPI, TasksAPI, UsersAPI, WebhooksAPI,
101
+ )
102
+ from .intelligence import Intelligence
103
+ from .workflows import Workflows
104
+
105
+ self.resellers = ResellersAPI(self)
106
+ self.companies = CompaniesAPI(self)
107
+ self.sso = SsoAPI(self)
108
+ self.products = ProductsAPI(self)
109
+ self.locations = LocationsAPI(self)
110
+ self.groups = GroupsAPI(self)
111
+ self.connectors = ConnectorsAPI(self)
112
+ self.first_alert = FirstAlertAPI(self)
113
+ self.insights_hub = InsightsHubAPI(self)
114
+ self.users = UsersAPI(self)
115
+ self.after_call_settings = AfterCallSettingsAPI(self)
116
+ self.account = AccountAPI(self)
117
+ self.calls = CallsAPI(self)
118
+ self.alerts = AlertsAPI(self)
119
+ self.tasks = TasksAPI(self)
120
+ self.insights = InsightsAPI(self)
121
+ self.webhooks = WebhooksAPI(self)
122
+ self.intelligence = Intelligence(self)
123
+ self.workflows = Workflows(self)
124
+
125
+ def __repr__(self) -> str:
126
+ return f"Client(base_url={self.base_url!r}, email={self._email!r})"
127
+
128
+ def __enter__(self) -> "Client":
129
+ return self
130
+
131
+ def __exit__(self, *exc: Any) -> None:
132
+ self.close()
133
+
134
+ def close(self) -> None:
135
+ """Close the HTTP connections. This does not sign out; tokens simply expire."""
136
+ self._http.close()
137
+
138
+ # ------------------------------------------------------------------ auth
139
+
140
+ def _store_lock(self) -> ContextManager[Any]:
141
+ """The token store's own (cross-process) lock, when it has one."""
142
+ lock = getattr(self._store, "lock", None)
143
+ return lock() if callable(lock) else contextlib.nullcontext()
144
+
145
+ def login(self) -> Dict[str, Any]:
146
+ """Sign in now and return the signed-in user. The client also signs in by itself on first use."""
147
+ with self._auth_lock, self._store_lock():
148
+ return self._login_locked()
149
+
150
+ def logout(self) -> None:
151
+ """Sign out. **This ends every session of this user**, including the web app.
152
+
153
+ The SDK never calls it by itself. Integration jobs normally let tokens expire instead.
154
+ """
155
+ tokens = self._store.get()
156
+ if tokens is None:
157
+ return
158
+ resp = self._send_raw("POST", "/auth/logout", op_id="logout", tokens=tokens)
159
+ self._store.set(None)
160
+ if resp.status_code >= 400 and resp.status_code != 401:
161
+ self._raise(resp, "logout")
162
+
163
+ def _login_locked(self) -> Dict[str, Any]:
164
+ if not self._email or not self._password:
165
+ text = "No credentials: pass email and password to Client"
166
+ raise AuthError(401, None, text, public_message=text)
167
+ body = {"email": self._email, "password": self._password}
168
+ waited = False
169
+ while True:
170
+ resp = self._send_with_retries("POST", "/auth/login", op_id="login", json_body=body,
171
+ auth=False, retry_429=False)
172
+ if resp.status_code == 429 and not waited and self._login_wait > 0:
173
+ waited = True
174
+ self._sleep(self._login_wait)
175
+ continue
176
+ break
177
+ if resp.status_code >= 400:
178
+ self._raise(resp, "login")
179
+ data = _spec.project_response("login", resp.status_code, self._json(resp))
180
+ if not isinstance(data, dict):
181
+ raise AuthError(resp.status_code, None, "Unexpected sign-in response",
182
+ public_message="Unexpected sign-in response")
183
+ if data.get("status") == "mfa_required":
184
+ raise MfaRequiredError()
185
+ if data.get("password_expired"):
186
+ text = "The password has expired. Change it in the app, then sign in again."
187
+ raise PasswordExpiredError(resp.status_code, "password_expired", text, public_message=text)
188
+ self._store.set(self._tokens_from(data))
189
+ return data.get("user") or {}
190
+
191
+ @staticmethod
192
+ def _tokens_from(data: Mapping[str, Any]) -> Tokens:
193
+ expires_in = data.get("expires_in") or 0
194
+ return Tokens(
195
+ access_token=data["access_token"],
196
+ refresh_token=data["refresh_token"],
197
+ expires_at=(time.time() + float(expires_in)) if expires_in else 0.0,
198
+ )
199
+
200
+ def _current_tokens(self) -> Tokens:
201
+ tokens = self._store.get()
202
+ if tokens is not None and not tokens.expired():
203
+ return tokens
204
+ with self._auth_lock, self._store_lock():
205
+ tokens = self._store.get() # re-read: another thread or process may have renewed already
206
+ if tokens is None:
207
+ self._login_locked()
208
+ elif tokens.expired():
209
+ self._renew_locked(tokens)
210
+ return self._store.get() # type: ignore[return-value]
211
+
212
+ def _renew(self, stale: Tokens) -> Tokens:
213
+ with self._auth_lock, self._store_lock():
214
+ current = self._store.get()
215
+ if current is not None and current.access_token != stale.access_token:
216
+ return current # another thread or process already renewed
217
+ self._renew_locked(current or stale)
218
+ return self._store.get() # type: ignore[return-value]
219
+
220
+ def _renew_locked(self, tokens: Tokens) -> None:
221
+ """Rotate the refresh token. A refresh token is used once.
222
+
223
+ A 429 means the token was not used: wait and send the same token again (it never turns into a
224
+ sign-in, which has a much lower limit). Any other failure: sign in again.
225
+ """
226
+ refresh_token = tokens.refresh_token
227
+ if refresh_token in self._spent_refresh_tokens:
228
+ self._login_locked()
229
+ return
230
+ attempt = 0
231
+ while True:
232
+ try:
233
+ resp = self._send_with_retries("POST", "/auth/refresh", op_id="refresh",
234
+ json_body={"refresh_token": refresh_token}, auth=False,
235
+ retry_429=False)
236
+ except httpx.HTTPError:
237
+ resp = None
238
+ if resp is None or resp.status_code != 429:
239
+ break
240
+ wait = self._backoff(attempt, resp.headers.get("Retry-After"))
241
+ if attempt >= self._max_retries or wait is None:
242
+ self._raise(resp, "refresh")
243
+ self._sleep(wait) # type: ignore[arg-type]
244
+ attempt += 1
245
+ self._spent_refresh_tokens.add(refresh_token)
246
+ if resp is not None and resp.status_code == 200:
247
+ data = _spec.project_response("refresh", 200, self._json(resp))
248
+ if isinstance(data, dict) and data.get("access_token") and data.get("refresh_token"):
249
+ self._store.set(self._tokens_from(data)) # store the new pair before using it
250
+ return
251
+ self._store.set(None)
252
+ self._login_locked()
253
+
254
+ # ------------------------------------------------------------------ transport
255
+
256
+ @staticmethod
257
+ def _json(resp: httpx.Response) -> Any:
258
+ if not resp.content:
259
+ return None
260
+ try:
261
+ return resp.json()
262
+ except (ValueError, json.JSONDecodeError):
263
+ return None
264
+
265
+ def _url(self, path: str) -> str:
266
+ return self.base_url + path
267
+
268
+ def _send_raw(self, method: str, path: str, *, op_id: str, tokens: Optional[Tokens] = None,
269
+ params: Optional[Mapping[str, str]] = None, json_body: Any = None,
270
+ headers: Optional[Mapping[str, str]] = None) -> httpx.Response:
271
+ h = {"Accept": "application/json", "X-Request-ID": str(uuid.uuid4())}
272
+ if headers:
273
+ h.update(headers)
274
+ if tokens is not None:
275
+ h["Authorization"] = f"Bearer {tokens.access_token}"
276
+ return self._http.request(method, self._url(path), params=params or None,
277
+ json=json_body, headers=h)
278
+
279
+ def _send_with_retries(self, method: str, path: str, *, op_id: str, params=None, json_body=None,
280
+ headers: Optional[Dict[str, str]] = None, auth: bool = True,
281
+ retry_429: bool = True) -> httpx.Response:
282
+ headers = dict(headers or {})
283
+ idempotent = method in RETRY_METHODS or "Idempotency-Key" in headers
284
+ attempt = 0
285
+ refreshed = False
286
+ while True:
287
+ if attempt > 0 and "Idempotency-Key" in headers:
288
+ headers["Accept-Encoding"] = "identity"
289
+ tokens = self._current_tokens() if auth else None
290
+ try:
291
+ resp = self._send_raw(method, path, op_id=op_id, tokens=tokens, params=params,
292
+ json_body=json_body, headers=headers)
293
+ except (httpx.TransportError,) as exc:
294
+ if idempotent and attempt < self._max_retries:
295
+ self._sleep(self._backoff(attempt, None) or 0.0)
296
+ attempt += 1
297
+ continue
298
+ raise exc
299
+ if resp.status_code == 401 and auth and not refreshed:
300
+ refreshed = True
301
+ self._renew(tokens) # type: ignore[arg-type]
302
+ continue
303
+ retryable = (resp.status_code == 429 and retry_429) or (resp.status_code >= 500 and idempotent)
304
+ if retryable and attempt < self._max_retries:
305
+ wait = self._backoff(attempt, resp.headers.get("Retry-After"))
306
+ if wait is None:
307
+ return resp # Retry-After above MAX_RETRY_AFTER: fail now rather than block
308
+ self._sleep(wait)
309
+ attempt += 1
310
+ continue
311
+ return resp
312
+
313
+ @staticmethod
314
+ def _backoff(attempt: int, retry_after: Optional[str]) -> Optional[float]:
315
+ """Seconds to wait before the next try, or None when Retry-After asks for more than
316
+ MAX_RETRY_AFTER seconds."""
317
+ if retry_after:
318
+ try:
319
+ wait = max(0.0, float(retry_after))
320
+ except ValueError:
321
+ wait = -1.0
322
+ if wait > MAX_RETRY_AFTER:
323
+ return None
324
+ if wait >= 0:
325
+ return wait
326
+ base = min(8.0, 0.5 * (2 ** attempt))
327
+ return base + random.uniform(0, base / 2)
328
+
329
+ # ------------------------------------------------------------------ errors
330
+
331
+ @staticmethod
332
+ def _request_body(resp: httpx.Response) -> Any:
333
+ try:
334
+ content = resp.request.content
335
+ return json.loads(content) if content else None
336
+ except (RuntimeError, ValueError):
337
+ return None
338
+
339
+ def _raise(self, resp: httpx.Response, op_id: str) -> None:
340
+ status = resp.status_code
341
+ body = self._json(resp)
342
+ code = message = request_id = None
343
+ if isinstance(body, dict):
344
+ err = body.get("error")
345
+ if isinstance(err, dict):
346
+ code = err.get("code") or err.get("type")
347
+ message = err.get("message")
348
+ request_id = err.get("request_id")
349
+ elif isinstance(err, str):
350
+ message = err
351
+ elif "statusCode" in body or "message" in body:
352
+ message = body.get("message")
353
+ public: Optional[str] = None # text the SDK wrote itself; the only text that goes into str(error)
354
+ if message is None:
355
+ message = "Request refused" if body is None and status == 404 else resp.reason_phrase or "Error"
356
+ if body is None and status == 404 and len(str(resp.request.url)) > 1900:
357
+ message = "Refused: the request URL is too long. Send fewer ids per request."
358
+ public = message
359
+ if op_id in SANITIZED_ERRORS:
360
+ message = public = f"Request failed (HTTP {status})."
361
+ if status == 401:
362
+ raise AuthError(status, code, message, request_id, public_message=public)
363
+ if status == 404:
364
+ raise NotFoundError(status, code, message, request_id, public_message=public)
365
+ if status == 409:
366
+ exts: list = []
367
+ requested = requested_numbers(self._request_body(resp))
368
+ if op_id in EXTENSION_CONFLICT_OPS or requested:
369
+ exts = extension_conflict_numbers(message or "", requested)
370
+ message = public = EXTENSION_CONFLICT_MESSAGE
371
+ raise ConflictError(status, code, message, request_id, extensions=exts, public_message=public)
372
+ if status in (400, 422):
373
+ raise ValidationError(status, code, message, request_id, public_message=public)
374
+ if status == 429:
375
+ ra = resp.headers.get("Retry-After")
376
+ raise RateLimitError(status, code, message, request_id,
377
+ retry_after=float(ra) if ra and ra.replace(".", "", 1).isdigit() else None,
378
+ public_message=public)
379
+ raise ApiError(status, code, message, request_id, public_message=public)
380
+
381
+ # ------------------------------------------------------------------ operations
382
+
383
+ def _build(self, op_id: str, path: Mapping[str, Any], query: Mapping[str, Any], body: Any):
384
+ op = _spec.operation(op_id)
385
+ url_path = op["path"]
386
+ for name in op["path_params"]:
387
+ value = path.get(name)
388
+ if not value or not isinstance(value, str):
389
+ from .errors import InvalidRequestError
390
+ raise InvalidRequestError(f"{op_id}: {name} is required")
391
+ url_path = url_path.replace("{" + name + "}", quote(value, safe=""))
392
+ params = _spec.encode_query(op_id, query)
393
+ if body is not None:
394
+ _spec.check_body(op_id, body)
395
+ elif op["body"] is not None and op["body"]["required"]:
396
+ from .errors import InvalidRequestError
397
+ raise InvalidRequestError(f"{op_id}: a body is required")
398
+ return op, url_path, params
399
+
400
+ def _request(self, op_id: str, path: Mapping[str, Any], query: Mapping[str, Any], body: Any,
401
+ headers: Optional[Dict[str, str]] = None) -> httpx.Response:
402
+ op, url_path, params = self._build(op_id, path, query, body)
403
+ resp = self._send_with_retries(op["method"], url_path, op_id=op_id, params=params,
404
+ json_body=dict(body) if body is not None else None, headers=headers)
405
+ if resp.status_code >= 400:
406
+ self._raise(resp, op_id)
407
+ return resp
408
+
409
+ def _call(self, op_id: str, *, path: Mapping[str, Any], query: Mapping[str, Any], body: Any,
410
+ headers: Optional[Dict[str, str]] = None) -> Any:
411
+ resp = self._request(op_id, path, query, body, headers)
412
+ if resp.status_code == 204 or not resp.content:
413
+ return None
414
+ return _spec.project_response(op_id, resp.status_code, self._json(resp),
415
+ keep_unknown=self.keep_unknown_fields)
416
+
417
+ def _page(self, op_id: str, *, path: Mapping[str, Any], query: Mapping[str, Any], body: Any = None) -> Page:
418
+ return Page.from_body(self._call(op_id, path=path, query=query, body=body))
419
+
420
+ def _iter(self, op_id: str, *, path: Mapping[str, Any], query: Mapping[str, Any]) -> Iterator[Any]:
421
+ q = dict(query)
422
+ q["limit"] = 100
423
+ cursor: Optional[str] = None
424
+ seen = set()
425
+ while True:
426
+ q["cursor"] = cursor
427
+ page = self._page(op_id, path=path, query=q)
428
+ for item in page.items:
429
+ yield item
430
+ if not page.has_more or not page.next_cursor or page.next_cursor in seen:
431
+ return
432
+ seen.add(page.next_cursor)
433
+ cursor = page.next_cursor