cord-sdk 1.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.
cord/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ """SDK de Python para la API de Cord."""
2
+ from . import types
3
+ from ._http import API_VERSION, SDK_VERSION, AppInfo, CordError, CordResponse, RawResponse
4
+ from ._version import __version__
5
+ from .async_client import AsyncCord
6
+ from .client import Cord
7
+ from .webhooks import WebhookSignatureError, construct_event, construct_workflow_delivery, sign_payload, verify_signature
8
+
9
+ __all__ = [
10
+ "Cord",
11
+ "AsyncCord",
12
+ "AppInfo",
13
+ "CordError",
14
+ "CordResponse",
15
+ "RawResponse",
16
+ "WebhookSignatureError",
17
+ "construct_event",
18
+ "construct_workflow_delivery",
19
+ "verify_signature",
20
+ "sign_payload",
21
+ "types",
22
+ "API_VERSION",
23
+ "SDK_VERSION",
24
+ "__version__",
25
+ ]
cord/_http.py ADDED
@@ -0,0 +1,489 @@
1
+ """Transporte HTTP: autenticación, Cord-Version, idempotencia, reintentos y errores tipados.
2
+
3
+ El núcleo arma la petición y decide qué hacer con cada respuesta; el cliente síncrono (urllib) y el
4
+ async (httpx) solo cambian cómo se espera y cómo se manda.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ import contextvars
10
+ import copy
11
+ import datetime
12
+ import decimal
13
+ import email.utils
14
+ import http.client
15
+ import json
16
+ import math
17
+ import random
18
+ import re
19
+ import socket
20
+ import time
21
+ import uuid
22
+ from dataclasses import dataclass
23
+ from types import MappingProxyType
24
+ from typing import Any, Awaitable, Callable, Dict, Mapping, Optional, Tuple, Type, TypedDict, TypeVar, Union
25
+ from urllib import error as urlerror
26
+ from urllib import parse, request
27
+
28
+ from ._version import __version__ as SDK_VERSION
29
+ from .types import API_VERSION
30
+
31
+ __all__ = ["API_VERSION", "SDK_VERSION", "AppInfo", "CordError", "CordResponse", "RawResponse", "MAX_WAIT"]
32
+
33
+ _RETRYABLE = {408, 425, 500, 502, 503, 504}
34
+ #: Tope de todas las esperas de una llamada, backoff y Retry-After sumados, en segundos.
35
+ MAX_WAIT = 60.0
36
+ # Los headers de Cord no se pueden cambiar desde fuera, tampoco con otras mayúsculas.
37
+ _RESERVED = {"authorization", "accept", "user-agent", "cord-version", "content-type", "idempotency-key"}
38
+ _METHODS = ("GET", "POST", "PATCH", "DELETE")
39
+
40
+ Response = Tuple[int, Mapping[str, str], bytes]
41
+ Transport = Callable[[str, str, Dict[str, str], Optional[bytes], float], Response]
42
+ AsyncTransport = Callable[[str, str, Dict[str, str], Optional[bytes], float], Awaitable[Response]]
43
+ Result = Tuple[Any, Optional[Dict[str, Any]]]
44
+
45
+ # Lo único que se reintenta sin respuesta: la red. Un error de programación sale tal cual.
46
+ NETWORK_ERRORS: Tuple[Type[BaseException], ...] = (urlerror.URLError, ConnectionError, TimeoutError, socket.timeout, http.client.HTTPException)
47
+
48
+
49
+ class _AppInfoRequired(TypedDict):
50
+ name: str
51
+
52
+
53
+ class AppInfo(_AppInfoRequired, total=False):
54
+ """Tu app en el User-Agent (`cord-python/1.1.0 mi-erp/4.2.0`), útil al pedir soporte."""
55
+
56
+ version: str
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class CordResponse:
61
+ """Lo que respondió Cord: `request_id` para buscarlo en Desarrolladores › Registros."""
62
+
63
+ status: int
64
+ #: Headers de la respuesta, con el nombre en minúsculas.
65
+ headers: Mapping[str, str]
66
+ request_id: Optional[str]
67
+ #: True si Cord devolvió la respuesta guardada de esa Idempotency-Key.
68
+ idempotent_replayed: bool
69
+ #: Versión de la API con la que respondió Cord.
70
+ api_version: Optional[str]
71
+
72
+
73
+ @dataclass(frozen=True)
74
+ class RawResponse:
75
+ """La respuesta de `raw_request`: el `data` y el `meta` del cuerpo, y lo que respondió Cord."""
76
+
77
+ data: Any
78
+ meta: Optional[Dict[str, Any]]
79
+ request_id: Optional[str]
80
+ last_response: CordResponse
81
+
82
+
83
+ class CordError(Exception):
84
+ """Error de la API. Incluye `code` estable, `request_id` para soporte y `doc_url`."""
85
+
86
+ def __init__(self, status: int, body: Any, request_id: Optional[str] = None, headers: Optional[Mapping[str, str]] = None) -> None:
87
+ body = body if isinstance(body, dict) else {}
88
+ super().__init__(body.get("error") or f"Cord API error ({status})")
89
+ self.status = status
90
+ self.code: str = body.get("code") or ("network_error" if status == 0 else "unknown")
91
+ self.request_id: Optional[str] = request_id or body.get("request_id")
92
+ self.doc_url: Optional[str] = body.get("doc_url")
93
+ self.body: Dict[str, Any] = body
94
+ #: Headers de la respuesta en minúsculas; vacío si no hubo respuesta.
95
+ self.headers: Mapping[str, str] = MappingProxyType(dict(headers or {}))
96
+ #: Segundos que pidió esperar Cord (`Retry-After`), o None.
97
+ self.retry_after: Optional[float] = _retry_after(self.headers.get("retry-after"))
98
+
99
+
100
+ class _SinRedirecciones(request.HTTPRedirectHandler):
101
+ def redirect_request(self, req: request.Request, fp: Any, code: int, msg: str, headers: Any, newurl: str) -> None:
102
+ return None
103
+
104
+
105
+ # Nunca sigue un 3xx: urllib convertiría un POST en GET y mandaría la llave a la otra dirección.
106
+ _OPENER = request.build_opener(_SinRedirecciones)
107
+
108
+
109
+ def _urllib_transport(method: str, url: str, headers: Dict[str, str], body: Optional[bytes], timeout: float) -> Response:
110
+ req = request.Request(url, data=body, method=method, headers=headers)
111
+ try:
112
+ with _OPENER.open(req, timeout=timeout) as res: # noqa: S310 (URL fija de Cord)
113
+ return res.status, {k.lower(): v for k, v in res.headers.items()}, res.read()
114
+ except urlerror.HTTPError as exc:
115
+ return exc.code, {k.lower(): v for k, v in (exc.headers or {}).items()}, exc.read() or b""
116
+
117
+
118
+ def _query_value(value: Any) -> Any:
119
+ if isinstance(value, bool):
120
+ return "true" if value else "false"
121
+ if isinstance(value, (datetime.date, datetime.datetime)):
122
+ return value.isoformat()
123
+ return value
124
+
125
+
126
+ def _json_default(value: Any) -> Any:
127
+ if isinstance(value, decimal.Decimal):
128
+ return float(value)
129
+ if isinstance(value, (datetime.date, datetime.datetime)):
130
+ return value.isoformat()
131
+ raise TypeError(f"{type(value).__name__} no se puede mandar como JSON a Cord.")
132
+
133
+
134
+ class _Attempts:
135
+ """Los reintentos y las esperas de una llamada, con el tope de MAX_WAIT."""
136
+
137
+ def __init__(self, max_retries: int) -> None:
138
+ self.max_retries = max_retries
139
+ self.attempt = 0
140
+ self.retries = 0
141
+ self.waited = 0.0
142
+
143
+ def next_wait(self, in_progress: bool, retry_after: Optional[float]) -> Optional[float]:
144
+ """Segundos antes del siguiente intento, o None si ya no se reintenta.
145
+
146
+ `409 idempotency_in_progress` no gasta reintentos: se pregunta otra vez hasta la respuesta guardada o el tope.
147
+ """
148
+ if self.max_retries == 0 or (not in_progress and self.retries >= self.max_retries):
149
+ return None
150
+ wait = retry_after if retry_after is not None else _backoff(self.attempt if in_progress else self.retries)
151
+ if self.waited + wait > MAX_WAIT:
152
+ return None
153
+ self.waited += wait
154
+ self.attempt += 1
155
+ if not in_progress:
156
+ self.retries += 1
157
+ return wait
158
+
159
+
160
+ _C = TypeVar("_C", bound="_Core")
161
+
162
+
163
+ class _Core:
164
+ def __init__(
165
+ self, api_key: str, *, base_url: str, api_version: str, timeout: float, max_retries: int, app_info: Optional[AppInfo] = None
166
+ ) -> None:
167
+ if not api_key or not isinstance(api_key, str):
168
+ raise ValueError("Falta la API key (sk_live_…, sk_test_… o una restringida rk_…).")
169
+ if api_key.startswith("pk_"):
170
+ raise ValueError("El SDK de servidor usa una secret key (sk_ o rk_). La pk_ es para el navegador.")
171
+ self._api_key = api_key
172
+ self.mode = "test" if api_key.startswith(("sk_test_", "rk_test_")) else "live"
173
+ self.api_version = api_version
174
+ self._base = base_url.rstrip("/") + "/api/v1"
175
+ self._timeout = timeout
176
+ self._max_retries = _clamp(max_retries)
177
+ self._user_agent = f"cord-python/{SDK_VERSION}" + _app_info(app_info)
178
+ # Una variable de contexto: la última respuesta es la de este hilo o esta tarea de asyncio, no la de otra.
179
+ self._last: contextvars.ContextVar[Optional[CordResponse]] = contextvars.ContextVar(f"cord_last_response_{id(self)}", default=None)
180
+
181
+ @property
182
+ def last_response(self) -> Optional[CordResponse]:
183
+ return self._last.get()
184
+
185
+ def with_options(self: _C, *, timeout: Optional[float] = None, max_retries: Optional[int] = None) -> _C:
186
+ """Una copia con otro timeout o tope de reintentos que comparte transporte y `last_response`."""
187
+ clone = copy.copy(self)
188
+ if timeout is not None:
189
+ clone._timeout = timeout
190
+ if max_retries is not None:
191
+ clone._max_retries = _clamp(max_retries)
192
+ return clone
193
+
194
+ def _prepare(
195
+ self,
196
+ method: str,
197
+ path: str,
198
+ query: Optional[Mapping[str, Any]],
199
+ body: Any,
200
+ idempotency_key: Optional[str],
201
+ extra: Optional[Mapping[str, str]] = None,
202
+ ) -> Tuple[str, Dict[str, str], Optional[bytes]]:
203
+ url = self._base + path
204
+ clean = {k: _query_value(v) for k, v in (query or {}).items() if v is not None and v != ""}
205
+ if clean:
206
+ url += ("&" if "?" in url else "?") + parse.urlencode(clean)
207
+ headers = {str(k): str(v) for k, v in (extra or {}).items() if str(k).lower() not in _RESERVED}
208
+ headers.update({
209
+ "Authorization": f"Bearer {self._api_key}",
210
+ "Accept": "application/json",
211
+ "Cord-Version": self.api_version,
212
+ "User-Agent": self._user_agent,
213
+ })
214
+ payload = None
215
+ if body is not None:
216
+ headers["Content-Type"] = "application/json"
217
+ payload = json.dumps(body, default=_json_default).encode("utf-8")
218
+ # Toda mutación lleva clave, la misma en cada reintento: nunca duplica.
219
+ if method != "GET":
220
+ headers["Idempotency-Key"] = idempotency_key or str(uuid.uuid4())
221
+ return url, headers, payload
222
+
223
+ def _network_failure(self, tries: _Attempts, exc: BaseException) -> float:
224
+ wait = tries.next_wait(False, None)
225
+ if wait is None:
226
+ raise CordError(0, {"error": f"No se pudo contactar a Cord: {exc}"}) from exc
227
+ return wait
228
+
229
+ def _interpret(self, tries: _Attempts, url: str, status: int, res_headers: Mapping[str, str], raw: bytes) -> Union[Tuple[Any, Optional[Dict[str, Any]], CordResponse], float]:
230
+ """Devuelve (data, meta, respuesta), o los segundos que hay que esperar antes de reintentar."""
231
+ try:
232
+ parsed: Any = json.loads(raw.decode("utf-8")) if raw else {}
233
+ except ValueError:
234
+ parsed = {"error": raw[:200].decode("utf-8", "replace")}
235
+ if not isinstance(parsed, dict):
236
+ parsed = {}
237
+ headers = {k.lower(): v for k, v in (res_headers or {}).items()}
238
+ request_id = headers.get("cord-request-id")
239
+ if 300 <= status < 400 and status != 304:
240
+ raise _redirect_error(status, headers, url, request_id)
241
+ if 200 <= status < 300 or status == 304:
242
+ response = CordResponse(
243
+ status=status,
244
+ headers=MappingProxyType(headers),
245
+ request_id=request_id,
246
+ idempotent_replayed=headers.get("idempotent-replayed") == "true",
247
+ api_version=headers.get("cord-version"),
248
+ )
249
+ self._last.set(response)
250
+ meta = parsed.get("meta")
251
+ return parsed.get("data"), meta if isinstance(meta, dict) else None, response
252
+ code = parsed.get("code") if isinstance(parsed.get("code"), str) else None
253
+ if _should_retry(status, code, headers.get("cord-should-retry")):
254
+ wait = tries.next_wait(status == 409 and code == "idempotency_in_progress", _retry_after(headers.get("retry-after")))
255
+ if wait is not None:
256
+ return wait
257
+ raise CordError(status, parsed, request_id, headers)
258
+
259
+
260
+ class HttpClient(_Core):
261
+ def __init__(
262
+ self,
263
+ api_key: str,
264
+ *,
265
+ base_url: str = "https://cordhq.app",
266
+ api_version: str = API_VERSION,
267
+ timeout: float = 30.0,
268
+ max_retries: int = 2,
269
+ app_info: Optional[AppInfo] = None,
270
+ transport: Optional[Transport] = None,
271
+ ) -> None:
272
+ super().__init__(api_key, base_url=base_url, api_version=api_version, timeout=timeout, max_retries=max_retries, app_info=app_info)
273
+ self._transport = transport or _urllib_transport
274
+
275
+ def _send(
276
+ self, method: str, path: str, query: Optional[Mapping[str, Any]], body: Any, idempotency_key: Optional[str], extra: Optional[Mapping[str, str]]
277
+ ) -> Tuple[Any, Optional[Dict[str, Any]], CordResponse]:
278
+ url, headers, payload = self._prepare(method, path, query, body, idempotency_key, extra)
279
+ tries = _Attempts(self._max_retries)
280
+ while True:
281
+ try:
282
+ status, res_headers, raw = self._transport(method, url, headers, payload, self._timeout)
283
+ except NETWORK_ERRORS as exc:
284
+ time.sleep(self._network_failure(tries, exc))
285
+ continue
286
+ outcome = self._interpret(tries, url, status, res_headers, raw)
287
+ if not isinstance(outcome, tuple):
288
+ time.sleep(outcome)
289
+ continue
290
+ return outcome
291
+
292
+ def request(
293
+ self,
294
+ method: str,
295
+ path: str,
296
+ *,
297
+ query: Optional[Mapping[str, Any]] = None,
298
+ body: Any = None,
299
+ idempotency_key: Optional[str] = None,
300
+ ) -> Result:
301
+ data, meta, _ = self._send(method, path, query, body, idempotency_key, None)
302
+ return data, meta
303
+
304
+ def raw(
305
+ self,
306
+ method: str,
307
+ path: str,
308
+ *,
309
+ query: Optional[Mapping[str, Any]] = None,
310
+ body: Any = None,
311
+ idempotency_key: Optional[str] = None,
312
+ headers: Optional[Mapping[str, str]] = None,
313
+ ) -> RawResponse:
314
+ data, meta, response = self._send(_raw_method(method), _raw_path(path), query, body, idempotency_key, headers)
315
+ return RawResponse(data=data, meta=meta, request_id=response.request_id, last_response=response)
316
+
317
+
318
+ class AsyncHttpClient(_Core):
319
+ def __init__(
320
+ self,
321
+ api_key: str,
322
+ *,
323
+ base_url: str = "https://cordhq.app",
324
+ api_version: str = API_VERSION,
325
+ timeout: float = 30.0,
326
+ max_retries: int = 2,
327
+ app_info: Optional[AppInfo] = None,
328
+ transport: Optional[AsyncTransport] = None,
329
+ ) -> None:
330
+ super().__init__(api_key, base_url=base_url, api_version=api_version, timeout=timeout, max_retries=max_retries, app_info=app_info)
331
+ self._own: Optional[_HttpxTransport] = None
332
+ if transport is None:
333
+ self._own = _HttpxTransport()
334
+ transport = self._own
335
+ self._transport: AsyncTransport = transport
336
+
337
+ async def _send(
338
+ self, method: str, path: str, query: Optional[Mapping[str, Any]], body: Any, idempotency_key: Optional[str], extra: Optional[Mapping[str, str]]
339
+ ) -> Tuple[Any, Optional[Dict[str, Any]], CordResponse]:
340
+ url, headers, payload = self._prepare(method, path, query, body, idempotency_key, extra)
341
+ tries = _Attempts(self._max_retries)
342
+ while True:
343
+ try:
344
+ status, res_headers, raw = await self._transport(method, url, headers, payload, self._timeout)
345
+ except NETWORK_ERRORS as exc:
346
+ await asyncio.sleep(self._network_failure(tries, exc))
347
+ continue
348
+ outcome = self._interpret(tries, url, status, res_headers, raw)
349
+ if not isinstance(outcome, tuple):
350
+ await asyncio.sleep(outcome)
351
+ continue
352
+ return outcome
353
+
354
+ async def request(
355
+ self,
356
+ method: str,
357
+ path: str,
358
+ *,
359
+ query: Optional[Mapping[str, Any]] = None,
360
+ body: Any = None,
361
+ idempotency_key: Optional[str] = None,
362
+ ) -> Result:
363
+ data, meta, _ = await self._send(method, path, query, body, idempotency_key, None)
364
+ return data, meta
365
+
366
+ async def raw(
367
+ self,
368
+ method: str,
369
+ path: str,
370
+ *,
371
+ query: Optional[Mapping[str, Any]] = None,
372
+ body: Any = None,
373
+ idempotency_key: Optional[str] = None,
374
+ headers: Optional[Mapping[str, str]] = None,
375
+ ) -> RawResponse:
376
+ data, meta, response = await self._send(_raw_method(method), _raw_path(path), query, body, idempotency_key, headers)
377
+ return RawResponse(data=data, meta=meta, request_id=response.request_id, last_response=response)
378
+
379
+ async def aclose(self) -> None:
380
+ if self._own is not None:
381
+ await self._own.aclose()
382
+
383
+
384
+ class _HttpxTransport:
385
+ def __init__(self) -> None:
386
+ try:
387
+ import httpx
388
+ except ImportError as exc:
389
+ raise ImportError("AsyncCord necesita httpx: pip install 'cord-sdk[async]', o pasa transport=.") from exc
390
+ self._httpx = httpx
391
+ self._client = httpx.AsyncClient(follow_redirects=False)
392
+
393
+ async def __call__(self, method: str, url: str, headers: Dict[str, str], body: Optional[bytes], timeout: float) -> Response:
394
+ try:
395
+ res = await self._client.request(method, url, headers=headers, content=body, timeout=timeout)
396
+ except self._httpx.TransportError as exc:
397
+ raise ConnectionError(str(exc) or type(exc).__name__) from exc
398
+ return res.status_code, {k.lower(): v for k, v in res.headers.items()}, res.content
399
+
400
+ async def aclose(self) -> None:
401
+ await self._client.aclose()
402
+
403
+
404
+ def _should_retry(status: int, code: Optional[str], header: Optional[str]) -> bool:
405
+ """Cord-Should-Retry manda siempre. Sin él: 408, 425 y 5xx; 409 solo con la misma clave en curso;
406
+ 429 solo por ritmo o sin `code` (un intermediario). Una cuota agotada no se arregla esperando."""
407
+ decision = (header or "").strip().lower()
408
+ if decision in ("true", "false"):
409
+ return decision == "true"
410
+ if status == 429:
411
+ return code is None or code == "rate_limited"
412
+ if status == 409:
413
+ return code == "idempotency_in_progress"
414
+ return status in _RETRYABLE
415
+
416
+
417
+ def _redirect_error(status: int, headers: Mapping[str, str], url: str, request_id: Optional[str]) -> CordError:
418
+ location = headers.get("location")
419
+ destino: Optional[str] = None
420
+ if location:
421
+ to = parse.urlsplit(parse.urljoin(url, location))
422
+ origin = f"{to.scheme}://{to.netloc}"
423
+ here = parse.urlsplit(url)
424
+ destino = origin if origin != f"{here.scheme}://{here.netloc}" else parse.urlunsplit(to)
425
+ error = (
426
+ f"La URL base de Cord redirige a {destino}: usa esa dirección en base_url (la de producción es https://cordhq.app)."
427
+ if destino
428
+ else f"La URL base de Cord respondió con una redirección ({status}): revisa base_url (la de producción es https://cordhq.app)."
429
+ )
430
+ return CordError(status, {"error": error, "code": "unexpected_redirect", "location": location}, request_id, headers)
431
+
432
+
433
+ def _raw_method(method: str) -> str:
434
+ upper = str(method or "").upper()
435
+ if upper not in _METHODS:
436
+ raise ValueError(f"raw_request acepta GET, POST, PATCH o DELETE, no {method}.")
437
+ return upper
438
+
439
+
440
+ def _raw_path(path: str) -> str:
441
+ """La ruta de raw_request, relativa a /api/v1. Nunca una URL: la llave no sale a otro host."""
442
+ value = path.strip() if isinstance(path, str) else ""
443
+ if not value:
444
+ raise ValueError("raw_request necesita una ruta de la API, por ejemplo /cotizaciones.")
445
+ if re.match(r"[a-zA-Z][a-zA-Z0-9+.-]*:", value) or re.match(r"[\\/]{2}", value):
446
+ raise ValueError(f"raw_request recibe una ruta de la API (/cotizaciones/…), no una URL: {value}")
447
+ rel = value if value.startswith("/") else "/" + value
448
+ if re.match(r"/api/v1(?=$|[/?#])", rel):
449
+ rel = rel[len("/api/v1"):] or "/"
450
+ if not rel.startswith("/"):
451
+ rel = "/" + rel
452
+ if any(re.fullmatch(r"(\.|%2[eE]){1,2}", s) for s in re.split(r"[\\/]", re.split(r"[?#]", rel)[0])):
453
+ raise ValueError(f"raw_request no acepta . ni .. en la ruta: {value}")
454
+ return rel
455
+
456
+
457
+ def _clamp(max_retries: int) -> int:
458
+ return max(0, min(5, int(max_retries)))
459
+
460
+
461
+ def _app_info(info: Optional[AppInfo]) -> str:
462
+ if not info:
463
+ return ""
464
+ name = str(info.get("name") or "").strip()
465
+ if not name:
466
+ raise ValueError('app_info necesita "name".')
467
+ return f" {name}/{info.get('version') or '0'}"
468
+
469
+
470
+ def _backoff(attempt: int) -> float:
471
+ base = min(10.0, 0.5 * 2.0 ** attempt)
472
+ return base / 2 + random.random() * base / 2
473
+
474
+
475
+ def _retry_after(value: Optional[str]) -> Optional[float]:
476
+ """Retry-After en segundos o como fecha HTTP; None si no se puede leer."""
477
+ if not value or not value.strip():
478
+ return None
479
+ try:
480
+ seconds = float(value)
481
+ except ValueError:
482
+ try:
483
+ when = email.utils.parsedate_to_datetime(value)
484
+ except (TypeError, ValueError, IndexError):
485
+ return None
486
+ if when.tzinfo is None:
487
+ when = when.replace(tzinfo=datetime.timezone.utc)
488
+ return max(0.0, (when - datetime.datetime.now(datetime.timezone.utc)).total_seconds())
489
+ return seconds if math.isfinite(seconds) and seconds >= 0 else None
cord/_version.py ADDED
@@ -0,0 +1,2 @@
1
+ """Versión del SDK: la única fuente, que también lee pyproject.toml."""
2
+ __version__ = "1.1.0"