apprendo 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.
apprendo/__init__.py ADDED
@@ -0,0 +1,52 @@
1
+ """Python client for the Apprendo API, version 1, with webhook verification.
2
+
3
+ https://docs.apprendo.co/sdks/
4
+ """
5
+
6
+ from . import types
7
+ from ._client import (
8
+ DEFAULT_BASE_URL,
9
+ DEFAULT_MAX_RETRIES,
10
+ DEFAULT_MAX_RETRY_AFTER,
11
+ DEFAULT_TIMEOUT,
12
+ Apprendo,
13
+ HttpResponse,
14
+ Transport,
15
+ is_secret_already_shown,
16
+ parse_retry_after,
17
+ urllib_transport,
18
+ )
19
+ from ._errors import ApprendoConnectionError, ApprendoError, ApprendoTimeoutError
20
+ from ._version import __version__
21
+ from .webhooks import (
22
+ DEFAULT_TOLERANCE_SECONDS,
23
+ WebhookEvent,
24
+ WebhookVerificationError,
25
+ is_ping,
26
+ is_trigger_result,
27
+ verify_webhook,
28
+ )
29
+
30
+ __all__ = [
31
+ "DEFAULT_BASE_URL",
32
+ "DEFAULT_MAX_RETRIES",
33
+ "DEFAULT_MAX_RETRY_AFTER",
34
+ "DEFAULT_TIMEOUT",
35
+ "DEFAULT_TOLERANCE_SECONDS",
36
+ "Apprendo",
37
+ "ApprendoConnectionError",
38
+ "ApprendoError",
39
+ "ApprendoTimeoutError",
40
+ "HttpResponse",
41
+ "Transport",
42
+ "WebhookEvent",
43
+ "WebhookVerificationError",
44
+ "__version__",
45
+ "is_ping",
46
+ "is_secret_already_shown",
47
+ "is_trigger_result",
48
+ "parse_retry_after",
49
+ "types",
50
+ "urllib_transport",
51
+ "verify_webhook",
52
+ ]
apprendo/_client.py ADDED
@@ -0,0 +1,463 @@
1
+ from __future__ import annotations
2
+
3
+ import http.client
4
+ import json
5
+ import math
6
+ import os
7
+ import random
8
+ import re
9
+ import socket
10
+ import time
11
+ import urllib.error
12
+ import urllib.parse
13
+ import urllib.request
14
+ import uuid
15
+ from dataclasses import dataclass
16
+ from email.utils import parsedate_to_datetime
17
+ from datetime import timezone
18
+ from typing import Any, Callable, Iterator, Mapping, Optional, Sequence, Union
19
+
20
+ from ._errors import ApprendoConnectionError, ApprendoError, ApprendoTimeoutError
21
+ from ._version import __version__
22
+ from .types import (
23
+ OPERATIONS,
24
+ AnswerNotKept,
25
+ DeliveryList,
26
+ Delivery,
27
+ Event,
28
+ EventAccepted,
29
+ EventCreate,
30
+ Execution,
31
+ ExecutionList,
32
+ FactInput,
33
+ FactsWritten,
34
+ Me,
35
+ Member,
36
+ MemberList,
37
+ Ping,
38
+ Replay,
39
+ RotatedSecret,
40
+ Routine,
41
+ RoutineList,
42
+ SecretAlreadyShown,
43
+ Subscription,
44
+ SubscriptionCreate,
45
+ SubscriptionCreated,
46
+ SubscriptionList,
47
+ TestEventAccepted,
48
+ Trigger,
49
+ TriggerCreate,
50
+ TriggerEdit,
51
+ TriggerList,
52
+ TriggerTemplate,
53
+ TriggerTemplateList,
54
+ )
55
+
56
+ DEFAULT_BASE_URL = "https://api.apprendo.co"
57
+ DEFAULT_TIMEOUT = 30.0
58
+ DEFAULT_MAX_RETRIES = 2
59
+ DEFAULT_MAX_RETRY_AFTER = 60.0
60
+ USER_AGENT = f"apprendo-python/{__version__}"
61
+
62
+ _DELAY_SECONDS = re.compile(r"[0-9]{1,10}", re.ASCII)
63
+ _PATH_PARAM = re.compile(r"\{([^}]+)\}")
64
+ _KEY_SHAPE = re.compile(r"[\x21-\x7e]+")
65
+ _IDEMPOTENCY_KEY_SHAPE = re.compile(r"[\x21-\x7e]{1,255}")
66
+ _LOCAL_HOSTS = ("localhost", "127.0.0.1", "::1")
67
+
68
+
69
+ @dataclass(frozen=True)
70
+ class HttpResponse:
71
+ """What a transport returns: the status, the headers and the raw body."""
72
+
73
+ status: int
74
+ headers: Mapping[str, str]
75
+ body: bytes
76
+
77
+
78
+ Transport = Callable[[str, str, Mapping[str, str], Optional[bytes], float], HttpResponse]
79
+ """``transport(method, url, headers, body, timeout)``. Raises ``TimeoutError`` when no answer came in
80
+ time and ``ConnectionError`` (or another ``OSError``) when the connection failed; any HTTP status,
81
+ an error included, is an ``HttpResponse``."""
82
+
83
+
84
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
85
+ def redirect_request(self, req, fp, code, msg, headers, newurl): # type: ignore[no-untyped-def]
86
+ return None
87
+
88
+
89
+ _OPENER = urllib.request.build_opener(_NoRedirect)
90
+
91
+
92
+ def urllib_transport(method: str, url: str, headers: Mapping[str, str], body: Optional[bytes], timeout: float) -> HttpResponse:
93
+ """The default transport: the standard library, certificates verified, no redirect followed."""
94
+ request = urllib.request.Request(url, data=body, method=method, headers=dict(headers))
95
+ try:
96
+ with _OPENER.open(request, timeout=timeout) as response:
97
+ return HttpResponse(response.status, {k.lower(): v for k, v in response.headers.items()}, response.read())
98
+ except urllib.error.HTTPError as err:
99
+ try:
100
+ data = err.read()
101
+ except (OSError, http.client.HTTPException):
102
+ data = b""
103
+ found = err.headers.items() if err.headers is not None else []
104
+ return HttpResponse(err.code, {k.lower(): v for k, v in found}, data)
105
+ except urllib.error.URLError as err:
106
+ if isinstance(err.reason, (socket.timeout, TimeoutError)):
107
+ raise TimeoutError(str(err.reason)) from None
108
+ raise ConnectionError(str(err.reason)) from None
109
+ except (socket.timeout, TimeoutError) as err:
110
+ raise TimeoutError(str(err)) from None
111
+ except (http.client.HTTPException, OSError) as err:
112
+ raise ConnectionError(str(err)) from None
113
+
114
+
115
+ def parse_retry_after(value: Optional[str], now: Optional[float] = None) -> Optional[float]:
116
+ """``Retry-After`` as seconds from now: delay-seconds or an HTTP date; None when absent or unreadable."""
117
+ if value is None:
118
+ return None
119
+ raw = value.strip()
120
+ if not raw:
121
+ return None
122
+ if _DELAY_SECONDS.fullmatch(raw):
123
+ return float(int(raw))
124
+ try:
125
+ at = parsedate_to_datetime(raw)
126
+ except (TypeError, ValueError, IndexError):
127
+ return None
128
+ if at is None:
129
+ return None
130
+ if at.tzinfo is None:
131
+ at = at.replace(tzinfo=timezone.utc)
132
+ current = time.time() if now is None else now
133
+ return float(max(0, math.ceil(at.timestamp() - current)))
134
+
135
+
136
+ def _checked_base_url(raw: str) -> str:
137
+ """https, or plain http only to this machine (localhost, 127.0.0.1, ::1, *.localhost), so the key never crosses a network in clear."""
138
+ base = raw.strip().rstrip("/")
139
+ if base.endswith("/v1"):
140
+ base = base[: -len("/v1")]
141
+ try:
142
+ parts = urllib.parse.urlsplit(base)
143
+ host = (parts.hostname or "").lower()
144
+ except ValueError:
145
+ raise ValueError("base_url must be an https URL, such as https://api.apprendo.co.") from None
146
+ if parts.query or parts.fragment:
147
+ raise ValueError("base_url takes no query string or fragment.")
148
+ if parts.scheme == "https" and host:
149
+ return base
150
+ if parts.scheme == "http" and (host in _LOCAL_HOSTS or host.endswith(".localhost")):
151
+ return base
152
+ raise ValueError("base_url must be https; plain http is allowed only for localhost, 127.0.0.1, ::1 and *.localhost.")
153
+
154
+
155
+ def is_secret_already_shown(value: Any) -> bool:
156
+ """True when a write's answer replays one that carried a signing secret, which is never kept
157
+ (``{"id", "secret_already_shown": true}``): the secret is not in it, so rotate the subscription."""
158
+ return isinstance(value, Mapping) and value.get("secret_already_shown") is True
159
+
160
+
161
+ def _backoff(attempt: int) -> float:
162
+ return min(8.0, 0.5 * 2**attempt) * (0.5 + random.random() / 2)
163
+
164
+
165
+ def _error_from(response: HttpResponse, headers: Mapping[str, str]) -> ApprendoError:
166
+ header_request_id = headers.get("x-request-id")
167
+ retry_after = parse_retry_after(headers.get("retry-after"))
168
+ envelope: Any = None
169
+ try:
170
+ parsed = json.loads(response.body.decode("utf-8"))
171
+ if isinstance(parsed, dict) and isinstance(parsed.get("error"), dict):
172
+ envelope = parsed["error"]
173
+ except (UnicodeDecodeError, ValueError):
174
+ envelope = None
175
+ if envelope is not None and isinstance(envelope.get("code"), str) and isinstance(envelope.get("message"), str):
176
+ request_id = envelope.get("request_id")
177
+ field = envelope.get("field")
178
+ return ApprendoError(
179
+ envelope["code"],
180
+ envelope["message"],
181
+ status=response.status,
182
+ request_id=request_id if isinstance(request_id, str) else header_request_id,
183
+ field=field if isinstance(field, str) else None,
184
+ retry_after=retry_after,
185
+ )
186
+ return ApprendoError(
187
+ "http_error",
188
+ f"HTTP {response.status} without the API's error envelope.",
189
+ status=response.status,
190
+ request_id=header_request_id,
191
+ retry_after=retry_after,
192
+ )
193
+
194
+
195
+ class Apprendo:
196
+ """The Apprendo API, version 1.
197
+
198
+ Every method is one endpoint of the spec (docs/platform/api/openapi.yaml). Answers are the
199
+ spec's objects as dicts, snake_case as on the wire; unknown fields and values pass through.
200
+ """
201
+
202
+ def __init__(
203
+ self,
204
+ api_key: Optional[str] = None,
205
+ *,
206
+ base_url: str = DEFAULT_BASE_URL,
207
+ timeout: float = DEFAULT_TIMEOUT,
208
+ max_retries: int = DEFAULT_MAX_RETRIES,
209
+ max_retry_after: float = DEFAULT_MAX_RETRY_AFTER,
210
+ transport: Optional[Transport] = None,
211
+ sleep: Optional[Callable[[float], None]] = None,
212
+ ) -> None:
213
+ key = api_key if api_key is not None else os.environ.get("APPRENDO_API_KEY")
214
+ if not isinstance(key, str) or not key.strip():
215
+ raise ValueError("An API key is required: pass api_key, or set APPRENDO_API_KEY.")
216
+ if not _KEY_SHAPE.fullmatch(key.strip()):
217
+ raise ValueError("The API key is malformed: only visible ASCII characters, with no spaces or line breaks inside. Copy it again.")
218
+ self.__api_key = key.strip()
219
+ self.base_url = _checked_base_url(base_url)
220
+ self.timeout = timeout
221
+ self.max_retries = max(0, int(max_retries))
222
+ self.max_retry_after = max_retry_after
223
+ self._transport: Transport = transport or urllib_transport
224
+ self._sleep: Callable[[float], None] = sleep or time.sleep
225
+
226
+ self.members = _Members(self)
227
+ self.routines = _Routines(self)
228
+ self.trigger_templates = _TriggerTemplates(self)
229
+ self.triggers = _Triggers(self)
230
+ self.events = _Events(self)
231
+ self.facts = _Facts(self)
232
+ self.subscriptions = _Subscriptions(self)
233
+ self.deliveries = _Deliveries(self)
234
+
235
+ def __repr__(self) -> str:
236
+ return f"Apprendo(base_url={self.base_url!r})"
237
+
238
+ def me(self, *, timeout: Optional[float] = None) -> Me:
239
+ """What this key is: live or test, its scopes, workspace, connection and limits."""
240
+ return self.request("getMe", timeout=timeout)
241
+
242
+ def _url(self, template: str, path: Mapping[str, Any], query: Mapping[str, Any]) -> str:
243
+ def substitute(match: "re.Match[str]") -> str:
244
+ value = path.get(match.group(1))
245
+ if not isinstance(value, str) or not value:
246
+ raise ValueError(f"{match.group(1)} is required.")
247
+ return urllib.parse.quote(value, safe="")
248
+
249
+ resolved = _PATH_PARAM.sub(substitute, template)
250
+ qs = urllib.parse.urlencode([(k, str(v)) for k, v in query.items() if v is not None])
251
+ return f"{self.base_url}{resolved}{'?' + qs if qs else ''}"
252
+
253
+ def request(
254
+ self,
255
+ operation: str,
256
+ *,
257
+ path: Optional[Mapping[str, Any]] = None,
258
+ query: Optional[Mapping[str, Any]] = None,
259
+ body: Any = None,
260
+ idempotency_key: Optional[str] = None,
261
+ timeout: Optional[float] = None,
262
+ ) -> Any:
263
+ """Calls one operation of the spec by its operationId, with the client's retries."""
264
+ method, template, _ = OPERATIONS[operation]
265
+ url = self._url(template, path or {}, query or {})
266
+ data = None if body is None else json.dumps(body, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
267
+ headers = {
268
+ "Authorization": f"Bearer {self.__api_key}",
269
+ "Accept": "application/json",
270
+ "User-Agent": USER_AGENT,
271
+ }
272
+ if data is not None:
273
+ headers["Content-Type"] = "application/json"
274
+ if method == "POST":
275
+ key = idempotency_key or str(uuid.uuid4())
276
+ if not _IDEMPOTENCY_KEY_SHAPE.fullmatch(key):
277
+ raise ValueError("idempotency_key must be 1 to 255 visible ASCII characters.")
278
+ headers["Idempotency-Key"] = key
279
+ attempt_timeout = self.timeout if timeout is None else timeout
280
+
281
+ attempt = 0
282
+ while True:
283
+ failure: Optional[ApprendoConnectionError] = None
284
+ try:
285
+ response = self._transport(method, url, headers, data, attempt_timeout)
286
+ except TimeoutError:
287
+ failure = ApprendoTimeoutError(attempt_timeout)
288
+ except OSError as err:
289
+ failure = ApprendoConnectionError(f"The request did not complete: {err}")
290
+ if failure is not None:
291
+ if attempt < self.max_retries:
292
+ self._sleep(_backoff(attempt))
293
+ attempt += 1
294
+ continue
295
+ raise failure
296
+
297
+ answer_headers = {k.lower(): v for k, v in response.headers.items()}
298
+ if 200 <= response.status < 300:
299
+ if not response.body:
300
+ return None
301
+ try:
302
+ return json.loads(response.body.decode("utf-8"))
303
+ except (UnicodeDecodeError, ValueError):
304
+ raise ApprendoError(
305
+ "invalid_response",
306
+ f"HTTP {response.status} with a body that is not JSON.",
307
+ status=response.status,
308
+ request_id=answer_headers.get("x-request-id"),
309
+ ) from None
310
+ error = _error_from(response, answer_headers)
311
+ retryable = response.status in (429, 503) or (response.status == 409 and error.code == "idempotency_key_in_progress")
312
+ if retryable and attempt < self.max_retries:
313
+ if error.retry_after is None:
314
+ self._sleep(_backoff(attempt))
315
+ attempt += 1
316
+ continue
317
+ if error.retry_after <= self.max_retry_after:
318
+ self._sleep(error.retry_after)
319
+ attempt += 1
320
+ continue
321
+ raise error
322
+
323
+ def _paginate(
324
+ self,
325
+ operation: str,
326
+ *,
327
+ path: Optional[Mapping[str, Any]] = None,
328
+ query: Optional[Mapping[str, Any]] = None,
329
+ timeout: Optional[float] = None,
330
+ ) -> Iterator[Any]:
331
+ current = {k: v for k, v in (query or {}).items() if v is not None}
332
+ seen = set()
333
+ while True:
334
+ page = self.request(operation, path=path, query=current, timeout=timeout)
335
+ for item in page.get("data") or []:
336
+ yield item
337
+ following = page.get("next_cursor")
338
+ if not isinstance(following, str) or not following or following in seen:
339
+ return
340
+ seen.add(following)
341
+ current = {**current, "cursor": following}
342
+
343
+
344
+ class _Resource:
345
+ def __init__(self, client: Apprendo) -> None:
346
+ self._client = client
347
+
348
+
349
+ class _Members(_Resource):
350
+ def list(self, *, limit: Optional[int] = None, cursor: Optional[str] = None, timeout: Optional[float] = None) -> MemberList:
351
+ """One page of the workspace's members, by opaque id."""
352
+ return self._client.request("listMembers", query={"limit": limit, "cursor": cursor}, timeout=timeout)
353
+
354
+ def iterate(self, *, limit: Optional[int] = None, timeout: Optional[float] = None) -> Iterator[Member]:
355
+ """Every member, page after page."""
356
+ return self._client._paginate("listMembers", query={"limit": limit}, timeout=timeout)
357
+
358
+
359
+ class _Routines(_Resource):
360
+ def list(self, *, limit: Optional[int] = None, cursor: Optional[str] = None, timeout: Optional[float] = None) -> RoutineList:
361
+ """One page of the check-ins a trigger may use."""
362
+ return self._client.request("listRoutines", query={"limit": limit, "cursor": cursor}, timeout=timeout)
363
+
364
+ def iterate(self, *, limit: Optional[int] = None, timeout: Optional[float] = None) -> Iterator[Routine]:
365
+ return self._client._paginate("listRoutines", query={"limit": limit}, timeout=timeout)
366
+
367
+
368
+ class _TriggerTemplates(_Resource):
369
+ def list(self, *, limit: Optional[int] = None, cursor: Optional[str] = None, timeout: Optional[float] = None) -> TriggerTemplateList:
370
+ """One page of the templates a trigger is made from."""
371
+ return self._client.request("listTriggerTemplates", query={"limit": limit, "cursor": cursor}, timeout=timeout)
372
+
373
+ def iterate(self, *, limit: Optional[int] = None, timeout: Optional[float] = None) -> Iterator[TriggerTemplate]:
374
+ return self._client._paginate("listTriggerTemplates", query={"limit": limit}, timeout=timeout)
375
+
376
+
377
+ class _Triggers(_Resource):
378
+ def list(self, *, limit: Optional[int] = None, cursor: Optional[str] = None, timeout: Optional[float] = None) -> TriggerList:
379
+ return self._client.request("listTriggers", query={"limit": limit, "cursor": cursor}, timeout=timeout)
380
+
381
+ def iterate(self, *, limit: Optional[int] = None, timeout: Optional[float] = None) -> Iterator[Trigger]:
382
+ return self._client._paginate("listTriggers", query={"limit": limit}, timeout=timeout)
383
+
384
+ def get(self, trigger_id: str, *, timeout: Optional[float] = None) -> Trigger:
385
+ return self._client.request("getTrigger", path={"id": trigger_id}, timeout=timeout)
386
+
387
+ def create(
388
+ self, body: TriggerCreate, *, idempotency_key: Optional[str] = None, timeout: Optional[float] = None
389
+ ) -> Union[Trigger, AnswerNotKept]:
390
+ """Drafts a trigger from a template. It is born in ``shadow`` and contacts nobody until an owner turns it on in Apprendo."""
391
+ return self._client.request("createTrigger", body=body, idempotency_key=idempotency_key, timeout=timeout)
392
+
393
+ def update(self, trigger_id: str, body: TriggerEdit, *, timeout: Optional[float] = None) -> Trigger:
394
+ """Edits a trigger on the key's connection. An edit that makes it louder puts it back in ``shadow``."""
395
+ return self._client.request("updateTrigger", path={"id": trigger_id}, body=body, timeout=timeout)
396
+
397
+ def pause(self, trigger_id: str, *, timeout: Optional[float] = None) -> Trigger:
398
+ return self._client.request("updateTrigger", path={"id": trigger_id}, body={"state": "paused"}, timeout=timeout)
399
+
400
+ def list_executions(
401
+ self, trigger_id: str, *, limit: Optional[int] = None, cursor: Optional[str] = None, timeout: Optional[float] = None
402
+ ) -> ExecutionList:
403
+ return self._client.request("listTriggerExecutions", path={"id": trigger_id}, query={"limit": limit, "cursor": cursor}, timeout=timeout)
404
+
405
+ def iterate_executions(self, trigger_id: str, *, limit: Optional[int] = None, timeout: Optional[float] = None) -> Iterator[Execution]:
406
+ return self._client._paginate("listTriggerExecutions", path={"id": trigger_id}, query={"limit": limit}, timeout=timeout)
407
+
408
+
409
+ class _Events(_Resource):
410
+ def send(
411
+ self, body: EventCreate, *, idempotency_key: Optional[str] = None, timeout: Optional[float] = None
412
+ ) -> Union[EventAccepted, TestEventAccepted, AnswerNotKept]:
413
+ """Sends an event. Its Idempotency-Key is the event's own key: ``idempotency_key``, else the body's, else a new one."""
414
+ key = idempotency_key or body.get("idempotency_key")
415
+ return self._client.request("sendEvent", body=body, idempotency_key=key, timeout=timeout)
416
+
417
+ def get(self, event_id: str, *, timeout: Optional[float] = None) -> Event:
418
+ return self._client.request("getEvent", path={"id": event_id}, timeout=timeout)
419
+
420
+
421
+ class _Facts(_Resource):
422
+ def put(self, facts: Sequence[FactInput], *, timeout: Optional[float] = None) -> FactsWritten:
423
+ """Writes 1 to 100 facts, each answered on its own. The same member and key again replaces a fact, so a resend is safe."""
424
+ return self._client.request("putFacts", body={"facts": list(facts)}, timeout=timeout)
425
+
426
+
427
+ class _Subscriptions(_Resource):
428
+ def list(self, *, limit: Optional[int] = None, cursor: Optional[str] = None, timeout: Optional[float] = None) -> SubscriptionList:
429
+ return self._client.request("listSubscriptions", query={"limit": limit, "cursor": cursor}, timeout=timeout)
430
+
431
+ def iterate(self, *, limit: Optional[int] = None, timeout: Optional[float] = None) -> Iterator[Subscription]:
432
+ return self._client._paginate("listSubscriptions", query={"limit": limit}, timeout=timeout)
433
+
434
+ def create(
435
+ self, body: SubscriptionCreate, *, idempotency_key: Optional[str] = None, timeout: Optional[float] = None
436
+ ) -> Union[SubscriptionCreated, SecretAlreadyShown]:
437
+ """The signing secret is in this answer only. A replay of the call answers ``secret_already_shown``: rotate it then."""
438
+ return self._client.request("createSubscription", body=body, idempotency_key=idempotency_key, timeout=timeout)
439
+
440
+ def disable(self, subscription_id: str, *, timeout: Optional[float] = None) -> Subscription:
441
+ """Disables it, one way."""
442
+ return self._client.request("disableSubscription", path={"id": subscription_id}, timeout=timeout)
443
+
444
+ def ping(self, subscription_id: str, *, idempotency_key: Optional[str] = None, timeout: Optional[float] = None) -> Union[Ping, AnswerNotKept]:
445
+ return self._client.request("pingSubscription", path={"id": subscription_id}, idempotency_key=idempotency_key, timeout=timeout)
446
+
447
+ def rotate(
448
+ self, subscription_id: str, *, idempotency_key: Optional[str] = None, timeout: Optional[float] = None
449
+ ) -> Union[RotatedSecret, SecretAlreadyShown]:
450
+ return self._client.request("rotateSubscriptionSecret", path={"id": subscription_id}, idempotency_key=idempotency_key, timeout=timeout)
451
+
452
+
453
+ class _Deliveries(_Resource):
454
+ def list(
455
+ self, *, status: Optional[str] = None, limit: Optional[int] = None, cursor: Optional[str] = None, timeout: Optional[float] = None
456
+ ) -> DeliveryList:
457
+ return self._client.request("listDeliveries", query={"status": status, "limit": limit, "cursor": cursor}, timeout=timeout)
458
+
459
+ def iterate(self, *, status: Optional[str] = None, limit: Optional[int] = None, timeout: Optional[float] = None) -> Iterator[Delivery]:
460
+ return self._client._paginate("listDeliveries", query={"status": status, "limit": limit}, timeout=timeout)
461
+
462
+ def replay(self, delivery_id: str, *, idempotency_key: Optional[str] = None, timeout: Optional[float] = None) -> Union[Replay, AnswerNotKept]:
463
+ return self._client.request("replayDelivery", path={"id": delivery_id}, idempotency_key=idempotency_key, timeout=timeout)
apprendo/_errors.py ADDED
@@ -0,0 +1,50 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import Optional
4
+
5
+
6
+ class ApprendoError(Exception):
7
+ """A refusal from the API, in its one envelope.
8
+
9
+ Branch on ``code`` (the spec's ``ErrorCode``; a code this version does not know yet still
10
+ arrives here) and quote ``request_id`` when you ask about it. ``status`` is the HTTP status,
11
+ 0 when no answer came back.
12
+ """
13
+
14
+ def __init__(
15
+ self,
16
+ code: str,
17
+ message: str,
18
+ *,
19
+ status: int,
20
+ request_id: Optional[str],
21
+ field: Optional[str] = None,
22
+ retry_after: Optional[float] = None,
23
+ ) -> None:
24
+ super().__init__(message)
25
+ self.code = code
26
+ self.message = message
27
+ self.status = status
28
+ self.request_id = request_id
29
+ self.field = field
30
+ self.retry_after = retry_after
31
+
32
+ def __str__(self) -> str:
33
+ return f"{self.message} (code: {self.code}, status: {self.status}, request_id: {self.request_id})"
34
+
35
+ def __repr__(self) -> str:
36
+ return f"{type(self).__name__}(code={self.code!r}, status={self.status!r}, request_id={self.request_id!r})"
37
+
38
+
39
+ class ApprendoConnectionError(ApprendoError):
40
+ """No answer: the connection failed or broke. Retried with the same Idempotency-Key before it is raised."""
41
+
42
+ def __init__(self, message: str, *, code: str = "connection_error") -> None:
43
+ super().__init__(code, message, status=0, request_id=None)
44
+
45
+
46
+ class ApprendoTimeoutError(ApprendoConnectionError):
47
+ """No answer within the timeout. Retried like a connection error."""
48
+
49
+ def __init__(self, timeout: float) -> None:
50
+ super().__init__(f"No answer within {timeout} seconds.", code="timeout")
apprendo/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
apprendo/py.typed ADDED
File without changes
apprendo/types.py ADDED
@@ -0,0 +1,428 @@
1
+ # Generated from docs/platform/api/openapi.yaml by scripts/sdks/generate.ts (pnpm sdks:generate). Do not edit.
2
+ # flake8: noqa
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict, List, Literal, Optional, Tuple, TypedDict, Union
6
+
7
+
8
+ ErrorCode = Union[Literal["invalid_json", "invalid_api_key", "insufficient_scope", "test_key_not_allowed", "not_found", "method_not_allowed", "arming_is_in_app_only", "conflict", "trigger_limit", "subscription_limit", "idempotency_key_reuse", "idempotency_key_in_progress", "payload_too_large", "unsupported_media_type", "invalid_input", "connection_paused", "rate_limited", "quota_exceeded", "unavailable"], str]
9
+ """Every code a version 1 endpoint can answer with, and its HTTP status (`x-error-statuses`)."""
10
+
11
+ ERROR_STATUSES: Dict[str, int] = {
12
+ "invalid_json": 400,
13
+ "invalid_api_key": 401,
14
+ "insufficient_scope": 403,
15
+ "test_key_not_allowed": 403,
16
+ "not_found": 404,
17
+ "method_not_allowed": 405,
18
+ "arming_is_in_app_only": 409,
19
+ "conflict": 409,
20
+ "trigger_limit": 409,
21
+ "subscription_limit": 409,
22
+ "idempotency_key_reuse": 409,
23
+ "idempotency_key_in_progress": 409,
24
+ "payload_too_large": 413,
25
+ "unsupported_media_type": 415,
26
+ "invalid_input": 422,
27
+ "connection_paused": 423,
28
+ "rate_limited": 429,
29
+ "quota_exceeded": 429,
30
+ "unavailable": 503,
31
+ }
32
+ """Every error code version 1 documents, with its HTTP status."""
33
+
34
+
35
+ class ErrorResponse(TypedDict):
36
+ error: ErrorDetail
37
+
38
+
39
+ class _ErrorDetailRequired(TypedDict):
40
+ code: ErrorCode
41
+ message: str
42
+ request_id: str
43
+
44
+
45
+ class ErrorDetail(_ErrorDetailRequired, total=False):
46
+ field: str
47
+
48
+
49
+ class Me(TypedDict):
50
+ key_id: str
51
+ mode: Union[Literal["live", "test"], str]
52
+ scopes: List[str]
53
+ workspace_id: str
54
+ connection_id: str
55
+ limits: MeLimits
56
+
57
+
58
+ class MeLimits(TypedDict):
59
+ """The key's rate limits."""
60
+ requests_per_minute: int
61
+ workspace_requests_per_minute: int
62
+
63
+
64
+ class Member(TypedDict):
65
+ id: str
66
+
67
+
68
+ class MemberList(TypedDict):
69
+ data: List[Member]
70
+ next_cursor: Optional[str]
71
+
72
+
73
+ class Routine(TypedDict):
74
+ id: str
75
+ name: str
76
+
77
+
78
+ class RoutineList(TypedDict):
79
+ data: List[Routine]
80
+ next_cursor: Optional[str]
81
+
82
+
83
+ class AnswerNotKept(TypedDict):
84
+ """A replay of a write whose first answer was not kept (too large, or its full copy could not be written): the resource's id, when the answer named one. Read the resource to see it."""
85
+ id: Optional[str]
86
+ answer_not_kept: Literal[True]
87
+
88
+
89
+ class TriggerTemplateField(TypedDict):
90
+ name: str
91
+ required: bool
92
+ description: str
93
+
94
+
95
+ class EventExample(TypedDict):
96
+ """An event body that would match the template's example values, as your system sends it. Its `data` is what conditions and placeholders read under `payload.`."""
97
+ event_type: str
98
+ occurred_at: str
99
+ subject: Any
100
+ data: Any
101
+
102
+
103
+ class TriggerTemplate(TypedDict):
104
+ slug: str
105
+ name: str
106
+ summary: str
107
+ listens_to: Union[Literal["apprendo", "connection"], str]
108
+ event_type: Optional[str]
109
+ fields: List[TriggerTemplateField]
110
+ payload_fields: List[str]
111
+ example_event: Optional[EventExample]
112
+
113
+
114
+ class TriggerTemplateList(TypedDict):
115
+ data: List[TriggerTemplate]
116
+ next_cursor: Optional[str]
117
+
118
+
119
+ class TriggerLimits(TypedDict):
120
+ max_per_hour: int
121
+ per_member_per_day: Optional[int]
122
+ dedupe_window_seconds: int
123
+
124
+
125
+ class Trigger(TypedDict):
126
+ id: str
127
+ name: str
128
+ state: Union[Literal["shadow", "on", "paused"], str]
129
+ template: Optional[str]
130
+ sentence: str
131
+ routine_id: str
132
+ event_type: str
133
+ ask: str
134
+ limits: TriggerLimits
135
+ created_at: str
136
+ updated_at: str
137
+ armed_at: Optional[str]
138
+
139
+
140
+ class TriggerList(TypedDict):
141
+ data: List[Trigger]
142
+ next_cursor: Optional[str]
143
+
144
+
145
+ class Wait(TypedDict):
146
+ """When Tessa asks, from a time in the event, up to 30 days either way."""
147
+ field: str
148
+ offset_seconds: int
149
+
150
+
151
+ class _TriggerCreateRequired(TypedDict):
152
+ template: str
153
+ routine_id: str
154
+ max_per_hour: int
155
+
156
+
157
+ class TriggerCreate(_TriggerCreateRequired, total=False):
158
+ """A template and its fields; `GET /v1/trigger_templates` says which fields each template takes, and a field it does not take is `422 invalid_input`. Never a state."""
159
+ name: str
160
+ event_type: str
161
+ subject_path: str
162
+ ask: str
163
+ occurrence_path: str
164
+ cancel_occurrence_path: str
165
+ cancel_on: List[str]
166
+ evaluate_at: Wait
167
+
168
+
169
+ class TriggerEdit(TypedDict, total=False):
170
+ """`{"state": "paused"}` on its own, or the fields to change. null clears `occurrence_path`, `cancel_occurrence_path`, `evaluate_at`, `condition` and `per_member_per_day`."""
171
+ state: Literal["paused"]
172
+ name: str
173
+ routine_id: str
174
+ ask: str
175
+ event_type: str
176
+ subject_path: str
177
+ occurrence_path: Optional[str]
178
+ cancel_occurrence_path: Optional[str]
179
+ cancel_on: List[str]
180
+ evaluate_at: Optional[Wait]
181
+ condition: Optional[TriggerEditCondition]
182
+ max_per_hour: int
183
+ dedupe_window_seconds: int
184
+ per_member_per_day: Optional[int]
185
+
186
+
187
+ class TriggerEditCondition(TypedDict, total=False):
188
+ """Rules the event must meet, such as `{"all": [{"path": "payload.ready", "op": "eq", "value": false}]}`; `any` instead of `all` for one of them."""
189
+ v: Literal[1]
190
+ all: List[Any]
191
+ any: List[Any]
192
+
193
+
194
+ class Execution(TypedDict):
195
+ id: str
196
+ event_id: Optional[str]
197
+ created_at: str
198
+ member_id: Optional[str]
199
+ outcome: Union[Literal["pending", "would_contact", "contacted", "not_reached", "stopped"], str]
200
+ test_mode: bool
201
+
202
+
203
+ class ExecutionList(TypedDict):
204
+ data: List[Execution]
205
+ next_cursor: Optional[str]
206
+
207
+
208
+ class _EventCreateRequired(TypedDict):
209
+ event_type: str
210
+ occurred_at: str
211
+ subject: Any
212
+
213
+
214
+ class EventCreate(_EventCreateRequired, total=False):
215
+ """The envelope the webhook intake takes, with its idempotency key in the `Idempotency-Key` header. At most 64 KB."""
216
+ data: Any
217
+ idempotency_key: str
218
+ sandbox: EventCreateSandbox
219
+
220
+
221
+ class EventCreateSandbox(TypedDict, total=False):
222
+ """For a test key only (a live key's is `422 invalid_input`)."""
223
+ status: Literal["answered", "partial", "no_answer", "not_reached"]
224
+
225
+
226
+ class _EventAcceptedRequired(TypedDict):
227
+ test: Literal[False]
228
+ event_id: str
229
+ subject_status: Union[Literal["matched", "unconfirmed"], str]
230
+ duplicate: bool
231
+
232
+
233
+ class EventAccepted(_EventAcceptedRequired, total=False):
234
+ """A live key's event, stored."""
235
+ stripped: List[str]
236
+ stripped_truncated: Literal[True]
237
+
238
+
239
+ class _TestEventAcceptedRequired(TypedDict):
240
+ test: Literal[True]
241
+ event_id: str
242
+ verdict: Union[Literal["condition_holds", "condition_false", "no_trigger"], str]
243
+ triggers: List[TestEventTrigger]
244
+ sends: List[TestEventSend]
245
+
246
+
247
+ class TestEventAccepted(_TestEventAcceptedRequired, total=False):
248
+ """A test key's event, checked and never stored."""
249
+ stripped: List[str]
250
+ stripped_truncated: Literal[True]
251
+
252
+
253
+ class TestEventTrigger(TypedDict):
254
+ id: str
255
+ verdict: Union[Literal["condition_holds", "condition_false"], str]
256
+
257
+
258
+ class TestEventSend(TypedDict):
259
+ subscription_id: str
260
+ trigger_id: str
261
+ result_id: str
262
+ status_code: Optional[int]
263
+ error: Optional[str]
264
+
265
+
266
+ class EventTrigger(TypedDict):
267
+ trigger_id: str
268
+ outcome: Union[Literal["pending", "would_contact", "contacted", "not_reached", "stopped", "no_action"], str]
269
+ execution_id: Optional[str]
270
+ member_id: Optional[str]
271
+
272
+
273
+ class Event(TypedDict):
274
+ id: str
275
+ event_type: str
276
+ idempotency_key: str
277
+ occurred_at: str
278
+ received_at: str
279
+ subject_status: Union[Literal["matched", "unconfirmed"], str]
280
+ triggers: List[EventTrigger]
281
+
282
+
283
+ class FactsPut(TypedDict):
284
+ """1 to 100 facts. At most 64 KB."""
285
+ facts: List[FactInput]
286
+
287
+
288
+ class _FactInputRequired(TypedDict):
289
+ subject: str
290
+ key: str
291
+ sentence: str
292
+
293
+
294
+ class FactInput(_FactInputRequired, total=False):
295
+ """One fact about one member."""
296
+ value: Optional[Dict[str, Any]]
297
+ observed_at: Optional[str]
298
+ expires_at: Optional[str]
299
+ source_ref: Optional[str]
300
+
301
+
302
+ class FactsWritten(TypedDict):
303
+ test: bool
304
+ written: int
305
+ results: List[FactResult]
306
+
307
+
308
+ class _FactResultRequired(TypedDict):
309
+ index: int
310
+ ok: bool
311
+
312
+
313
+ class FactResult(_FactResultRequired, total=False):
314
+ error: FactResultError
315
+
316
+
317
+ class _FactResultErrorRequired(TypedDict):
318
+ code: Union[Literal["invalid_fact", "subject_unresolved", "duplicate_in_batch", "member_fact_limit"], str]
319
+
320
+
321
+ class FactResultError(_FactResultErrorRequired, total=False):
322
+ """Why the fact was not stored. Absent when `ok` is `true`."""
323
+ field: Union[Literal["subject", "key", "sentence", "value", "source_ref", "observed_at", "expires_at"], str]
324
+
325
+
326
+ class SubscriptionCreate(TypedDict):
327
+ url: str
328
+ events: List[Literal["trigger.result"]]
329
+
330
+
331
+ class Subscription(TypedDict):
332
+ id: str
333
+ url: str
334
+ events: List[str]
335
+ state: Union[Literal["active", "paused", "disabled"], str]
336
+ test: bool
337
+ managed: bool
338
+ secret_hint: str
339
+ created_at: str
340
+
341
+
342
+ class SubscriptionCreated(TypedDict):
343
+ """The subscription, as `GET /v1/subscriptions` shows it, and its signing secret, in this answer only."""
344
+ id: str
345
+ url: str
346
+ events: List[str]
347
+ state: Union[Literal["active", "paused", "disabled"], str]
348
+ test: bool
349
+ managed: Literal[True]
350
+ secret_hint: str
351
+ created_at: str
352
+ secret: str
353
+
354
+
355
+ class SubscriptionList(TypedDict):
356
+ data: List[Subscription]
357
+ next_cursor: Optional[str]
358
+
359
+
360
+ class SecretAlreadyShown(TypedDict):
361
+ """A replay of a request whose answer carried a signing secret, which is never kept. Rotate it if it was lost."""
362
+ id: Optional[str]
363
+ secret_already_shown: Literal[True]
364
+
365
+
366
+ class RotatedSecret(TypedDict):
367
+ id: str
368
+ secret: str
369
+ secret_hint: str
370
+
371
+
372
+ class Ping(TypedDict):
373
+ subscription_id: str
374
+ status_code: Optional[int]
375
+ error: Optional[str]
376
+
377
+
378
+ class Delivery(TypedDict):
379
+ id: str
380
+ subscription_id: str
381
+ event_id: str
382
+ case_id: str
383
+ revision: int
384
+ status: Union[Literal["pending", "delivered", "dead"], str]
385
+ attempts: int
386
+ last_attempt_at: Optional[str]
387
+ last_status_code: Optional[int]
388
+ last_error_code: Optional[str]
389
+ next_attempt_at: Optional[str]
390
+ delivered_at: Optional[str]
391
+ dead_at: Optional[str]
392
+ created_at: str
393
+
394
+
395
+ class DeliveryList(TypedDict):
396
+ data: List[Delivery]
397
+ next_cursor: Optional[str]
398
+
399
+
400
+ class Replay(TypedDict):
401
+ delivery_id: str
402
+ outcome: Union[Literal["delivered", "not_delivered", "requeued"], str]
403
+ status_code: Optional[int]
404
+ error: Optional[str]
405
+
406
+
407
+ OPERATIONS: Dict[str, Tuple[str, str, str]] = {
408
+ "getMe": ("GET", "/v1/me", "none"),
409
+ "listMembers": ("GET", "/v1/members", "none"),
410
+ "listRoutines": ("GET", "/v1/routines", "none"),
411
+ "listTriggerTemplates": ("GET", "/v1/trigger_templates", "none"),
412
+ "listTriggers": ("GET", "/v1/triggers", "none"),
413
+ "createTrigger": ("POST", "/v1/triggers", "optional"),
414
+ "getTrigger": ("GET", "/v1/triggers/{id}", "none"),
415
+ "updateTrigger": ("PATCH", "/v1/triggers/{id}", "none"),
416
+ "listTriggerExecutions": ("GET", "/v1/triggers/{id}/executions", "none"),
417
+ "sendEvent": ("POST", "/v1/events", "required"),
418
+ "getEvent": ("GET", "/v1/events/{id}", "none"),
419
+ "putFacts": ("PUT", "/v1/facts", "none"),
420
+ "listSubscriptions": ("GET", "/v1/subscriptions", "none"),
421
+ "createSubscription": ("POST", "/v1/subscriptions", "optional"),
422
+ "disableSubscription": ("DELETE", "/v1/subscriptions/{id}", "none"),
423
+ "pingSubscription": ("POST", "/v1/subscriptions/{id}/ping", "optional"),
424
+ "rotateSubscriptionSecret": ("POST", "/v1/subscriptions/{id}/rotate", "optional"),
425
+ "listDeliveries": ("GET", "/v1/deliveries", "none"),
426
+ "replayDelivery": ("POST", "/v1/deliveries/{id}/replay", "optional"),
427
+ }
428
+ """Every operation in the spec: its method, path and Idempotency-Key header (none, optional or required)."""
apprendo/webhooks.py ADDED
@@ -0,0 +1,204 @@
1
+ """Verifying the webhooks Apprendo sends (docs: Receive trigger results).
2
+
3
+ Needs no API key, only the subscription's signing secret. The header is
4
+ ``apprendo-signature: t=<unix seconds>,v1=<hex>``, with one ``v1`` per secret during a rotation;
5
+ each ``v1`` is the HMAC-SHA256 of ``t``, a period and the raw body, keyed by the whole secret as text.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import hmac
12
+ import json
13
+ import math
14
+ import re
15
+ import time
16
+ from typing import Any, Dict, List, Mapping, Optional, Sequence, TypedDict, Union
17
+
18
+ SIGNATURE_HEADER = "apprendo-signature"
19
+ DEFAULT_TOLERANCE_SECONDS = 300
20
+
21
+ _TIMESTAMP = re.compile(r"[0-9]{1,12}", re.ASCII)
22
+ _V1 = re.compile(r"[0-9a-f]{64}", re.ASCII)
23
+
24
+
25
+ class WebhookVerificationError(Exception):
26
+ """The request is not a webhook Apprendo signed with this secret, now. Answer it ``400``.
27
+
28
+ ``reason`` is one of ``missing_signature``, ``malformed_signature``,
29
+ ``timestamp_outside_tolerance``, ``no_matching_signature`` or ``invalid_payload``.
30
+ """
31
+
32
+ def __init__(self, reason: str, message: str) -> None:
33
+ super().__init__(message)
34
+ self.reason = reason
35
+
36
+
37
+ class TriggerResultReference(TypedDict):
38
+ path: str
39
+ value: str
40
+
41
+
42
+ class TriggerResultAnswer(TypedDict):
43
+ question: str
44
+ answer: str
45
+
46
+
47
+ class TriggerResultPhoto(TypedDict):
48
+ id: str
49
+ url: str
50
+ expires_at: str
51
+
52
+
53
+ class _TriggerResultRequired(TypedDict):
54
+ case_id: str
55
+ revision: int
56
+ trigger_id: str
57
+ trigger_version: int
58
+ event: Optional[Dict[str, Any]]
59
+ references: List[TriggerResultReference]
60
+ member_id: str
61
+ subject: Optional[str]
62
+ status: str
63
+ answered_at: Optional[str]
64
+ channel: Optional[str]
65
+
66
+
67
+ class TriggerResult(_TriggerResultRequired, total=False):
68
+ """``answers`` only while the workspace shares them; ``photos`` and ``photos_omitted`` only while it shares photos too."""
69
+
70
+ answers: List[TriggerResultAnswer]
71
+ photos: List[TriggerResultPhoto]
72
+ photos_omitted: bool
73
+
74
+
75
+ class TriggerResultEvent(TypedDict):
76
+ id: str
77
+ type: str
78
+ version: int
79
+ created_at: str
80
+ workspace_id: str
81
+ test: bool
82
+ data: TriggerResult
83
+
84
+
85
+ class PingEvent(TypedDict):
86
+ id: str
87
+ type: str
88
+ version: int
89
+ created_at: str
90
+ workspace_id: str
91
+
92
+
93
+ WebhookEvent = Union[TriggerResultEvent, PingEvent, Dict[str, Any]]
94
+ """A ``trigger.result``, a ``ping``, or a type this version does not know yet: answer it 2xx and ignore it."""
95
+
96
+
97
+ def _header(headers: Any, name: str) -> Optional[str]:
98
+ values: List[str] = []
99
+ items = getattr(headers, "items", None)
100
+ if callable(items):
101
+ for key, value in items():
102
+ if isinstance(key, bytes):
103
+ key = key.decode("latin-1")
104
+ if not isinstance(key, str) or key.lower() != name:
105
+ continue
106
+ for one in value if isinstance(value, (list, tuple)) else [value]:
107
+ if isinstance(one, bytes):
108
+ one = one.decode("latin-1")
109
+ if isinstance(one, str):
110
+ values.append(one)
111
+ else:
112
+ getter = getattr(headers, "get", None)
113
+ found = getter(name) if callable(getter) else None
114
+ if isinstance(found, str):
115
+ values.append(found)
116
+ return ",".join(values) if values else None
117
+
118
+
119
+ def _bytes_of(raw_body: Any) -> bytes:
120
+ if isinstance(raw_body, str):
121
+ return raw_body.encode("utf-8")
122
+ if isinstance(raw_body, (bytes, bytearray, memoryview)):
123
+ return bytes(raw_body)
124
+ raise TypeError("raw_body must be the raw request body, as bytes or str, never parsed JSON.")
125
+
126
+
127
+ def verify_webhook(
128
+ raw_body: Union[bytes, bytearray, memoryview, str],
129
+ headers: Mapping[str, Any],
130
+ secret: Union[str, Sequence[str]],
131
+ tolerance_seconds: float = DEFAULT_TOLERANCE_SECONDS,
132
+ *,
133
+ now: Optional[float] = None,
134
+ ) -> WebhookEvent:
135
+ """Verifies a webhook and returns its event.
136
+
137
+ ``raw_body`` is the body exactly as received; ``secret`` is the subscription's signing secret,
138
+ or several while you switch secrets. Accepts the request when any ``v1`` matches any secret,
139
+ compared in constant time, and ``t`` is within ``tolerance_seconds`` of your clock (``now``, in
140
+ unix seconds, defaults to the real clock). Raises ``WebhookVerificationError`` otherwise. An
141
+ event type this version does not know is returned as it came.
142
+ """
143
+ secrets = [secret] if isinstance(secret, str) else list(secret)
144
+ secrets = [s for s in secrets if isinstance(s, str) and s]
145
+ if not secrets:
146
+ raise ValueError("A signing secret is required.")
147
+ if isinstance(tolerance_seconds, bool) or not isinstance(tolerance_seconds, (int, float)) or not math.isfinite(tolerance_seconds) or tolerance_seconds < 0:
148
+ raise ValueError("tolerance_seconds must be a finite number of seconds, 0 or more.")
149
+ if now is not None and (isinstance(now, bool) or not isinstance(now, (int, float)) or not math.isfinite(now)):
150
+ raise ValueError("now must be a finite number of unix seconds.")
151
+ body = _bytes_of(raw_body)
152
+
153
+ header = _header(headers, SIGNATURE_HEADER)
154
+ if header is None or not header.strip():
155
+ raise WebhookVerificationError("missing_signature", "The request has no apprendo-signature header.")
156
+
157
+ timestamp: Optional[str] = None
158
+ saw_timestamp = False
159
+ signatures: List[bytes] = []
160
+ for part in header.split(","):
161
+ key, sep, value = part.strip().partition("=")
162
+ if not sep:
163
+ continue
164
+ if key == "t":
165
+ if not saw_timestamp:
166
+ timestamp = value
167
+ saw_timestamp = True
168
+ elif key == "v1" and _V1.fullmatch(value):
169
+ signatures.append(bytes.fromhex(value))
170
+ if timestamp is None or not _TIMESTAMP.fullmatch(timestamp):
171
+ raise WebhookVerificationError("malformed_signature", "The apprendo-signature header has no valid t.")
172
+ if not signatures:
173
+ raise WebhookVerificationError("malformed_signature", "The apprendo-signature header has no valid v1.")
174
+
175
+ t = int(timestamp)
176
+ clock = time.time() if now is None else now
177
+ if abs(int(clock) - t) > tolerance_seconds:
178
+ raise WebhookVerificationError("timestamp_outside_tolerance", f"t is more than {tolerance_seconds} seconds from this clock.")
179
+
180
+ signed = f"{t}.".encode("ascii") + body
181
+ matched = False
182
+ for key in secrets:
183
+ expected = hmac.new(key.encode("utf-8"), signed, hashlib.sha256).digest()
184
+ for signature in signatures:
185
+ if hmac.compare_digest(signature, expected):
186
+ matched = True
187
+ if not matched:
188
+ raise WebhookVerificationError("no_matching_signature", "No signature matches this body and secret.")
189
+
190
+ try:
191
+ event = json.loads(body.decode("utf-8"))
192
+ except (UnicodeDecodeError, ValueError):
193
+ raise WebhookVerificationError("invalid_payload", "The signed body is not UTF-8 JSON.") from None
194
+ if not isinstance(event, dict) or not isinstance(event.get("type"), str):
195
+ raise WebhookVerificationError("invalid_payload", "The signed body is not a webhook event.")
196
+ return event
197
+
198
+
199
+ def is_trigger_result(event: WebhookEvent) -> bool:
200
+ return event.get("type") == "trigger.result"
201
+
202
+
203
+ def is_ping(event: WebhookEvent) -> bool:
204
+ return event.get("type") == "ping"
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.4
2
+ Name: apprendo
3
+ Version: 0.1.0
4
+ Summary: Python client for the Apprendo API (version 1), with webhook verification.
5
+ License-Expression: Apache-2.0
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: Typing :: Typed
8
+ Requires-Python: >=3.9
9
+ Project-URL: Documentation, https://docs.apprendo.co/sdks/
10
+ Description-Content-Type: text/markdown
11
+
12
+ # apprendo
13
+
14
+ Python client for the Apprendo API, version 1, with webhook verification. Python 3.9 or later, no
15
+ dependencies.
16
+
17
+ ```sh
18
+ pip install apprendo
19
+ ```
20
+
21
+ ```python
22
+ from apprendo import Apprendo
23
+
24
+ client = Apprendo() # reads APPRENDO_API_KEY
25
+ me = client.me()
26
+ ```
27
+
28
+ Verify a signed webhook from the raw body, before you parse it:
29
+
30
+ ```python
31
+ import os
32
+
33
+ from apprendo import verify_webhook
34
+
35
+ event = verify_webhook(raw_body, headers, os.environ["APPRENDO_WEBHOOK_SECRET"])
36
+ ```
37
+
38
+ The guide, the quickstart and the API reference: <https://docs.apprendo.co/sdks/>.
39
+
40
+ The API is in private preview: a key comes from Apprendo.
@@ -0,0 +1,10 @@
1
+ apprendo/__init__.py,sha256=gzEQU2Bhmy87s0PDME2fAM7lm1zAXd08AlX4FPHJEs8,1166
2
+ apprendo/_client.py,sha256=60f39qilEF3uRPk8GWF70yjrXd168XovvMmgqTKgy-k,21008
3
+ apprendo/_errors.py,sha256=Ja_Q8lQuZrbRdOEe90NGLA82VJ8M0nAs4EU_Nh5QD_w,1695
4
+ apprendo/_version.py,sha256=kUR5RAFc7HCeiqdlX36dZOHkUI5wI6V_43RpEcD8b-0,22
5
+ apprendo/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ apprendo/types.py,sha256=FFZjbXm6BEL_k3fRtzOIYp4r3hxgfJVw6luMhgws0Ao,11880
7
+ apprendo/webhooks.py,sha256=jOVDtWvD0XTaZMPgWye2_UsmA6SqYNp2uO7okCSZ8eQ,7293
8
+ apprendo-0.1.0.dist-info/WHEEL,sha256=VOHKyukui3UMeyUkkBf5F7N5xN_6X6W7zHVvalNVVvI,81
9
+ apprendo-0.1.0.dist-info/METADATA,sha256=LBi82pYLYBp51_qQ1WTfhG2Fu-iCTQfNXPMsI_sgl_8,983
10
+ apprendo-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.12.21
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any