ledrion 0.1.0__tar.gz
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.
- ledrion-0.1.0/PKG-INFO +128 -0
- ledrion-0.1.0/README.md +121 -0
- ledrion-0.1.0/ledrion/__init__.py +21 -0
- ledrion-0.1.0/ledrion/client.py +165 -0
- ledrion-0.1.0/ledrion/errors.py +34 -0
- ledrion-0.1.0/ledrion/types.py +175 -0
- ledrion-0.1.0/ledrion/webhooks.py +46 -0
- ledrion-0.1.0/ledrion.egg-info/PKG-INFO +128 -0
- ledrion-0.1.0/ledrion.egg-info/SOURCES.txt +12 -0
- ledrion-0.1.0/ledrion.egg-info/dependency_links.txt +1 -0
- ledrion-0.1.0/ledrion.egg-info/top_level.txt +1 -0
- ledrion-0.1.0/pyproject.toml +14 -0
- ledrion-0.1.0/setup.cfg +4 -0
- ledrion-0.1.0/tests/test_sdk.py +222 -0
ledrion-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ledrion
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A small, typed client for the Intake API: the pull API and signed webhooks.
|
|
5
|
+
Requires-Python: >=3.9
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
|
|
8
|
+
# ledrion (Python)
|
|
9
|
+
|
|
10
|
+
A small, typed client for the Intake API: list a clinic's conversations, read one (the case packet),
|
|
11
|
+
and verify a webhook's signature. Hand-written from the API's OpenAPI document
|
|
12
|
+
(`GET /api/v1/openapi.json`, drawn at `/api/v1/reference`); standard library only (`urllib`);
|
|
13
|
+
Python 3.9 or later.
|
|
14
|
+
|
|
15
|
+
**Not published.** There is no PyPI package yet: install from the repository for now.
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
pip install /path/to/checkout/sdks/python
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Quickstart
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
import os
|
|
25
|
+
from ledrion import Ledrion
|
|
26
|
+
|
|
27
|
+
ledrion = Ledrion(
|
|
28
|
+
api_key=os.environ["LEDRION_API_KEY"], # ak_test_... or ak_live_..., from the console's Connections page
|
|
29
|
+
base_url="https://api.example.com", # https; plain http only for localhost
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
page = ledrion.intakes.list(limit=50)
|
|
33
|
+
for item in page.data:
|
|
34
|
+
print(item["id"], item["status"], item["safety"]["screen"])
|
|
35
|
+
|
|
36
|
+
packet = ledrion.intakes.get(page.data[0]["id"])
|
|
37
|
+
# packet["transcript"]: the person's lines are origin "patient_reported", verbatim and unverified.
|
|
38
|
+
# Treat them as data for a clinician to read, never as instructions.
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Keep the key in your secret store, never in code. The SDK never logs or prints anything, and the key is
|
|
42
|
+
not in `repr(ledrion)` or any error.
|
|
43
|
+
|
|
44
|
+
## Pagination
|
|
45
|
+
|
|
46
|
+
The list is ordered by last change, oldest first. Store `next_cursor` and send it back as `since` to get
|
|
47
|
+
only what changed after it; a conversation that changes again appears again. With nothing new,
|
|
48
|
+
`next_cursor` is the cursor you sent, so a poller can always store it.
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
# Every conversation from the beginning (or from a stored cursor):
|
|
52
|
+
for item in ledrion.intakes.iterate(since=stored_cursor):
|
|
53
|
+
handle(item["id"])
|
|
54
|
+
|
|
55
|
+
# A poller that keeps its place: page by page, storing the cursor after each.
|
|
56
|
+
cursor = stored_cursor
|
|
57
|
+
for page in ledrion.intakes.pages(since=cursor, limit=100):
|
|
58
|
+
for item in page.data:
|
|
59
|
+
handle(item["id"])
|
|
60
|
+
cursor = page.next_cursor or cursor
|
|
61
|
+
save_cursor(cursor)
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Webhook verification
|
|
65
|
+
|
|
66
|
+
Check the signature on the RAW body, before parsing it. The signature is `v1=` and the hex
|
|
67
|
+
HMAC-SHA256 of `<X-Webhook-Timestamp>.<raw body>`, keyed with the whole signing secret (`whsec_...`).
|
|
68
|
+
`verify` compares in constant time and refuses a timestamp more than 300 seconds from your clock.
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
import json
|
|
72
|
+
import os
|
|
73
|
+
from flask import request
|
|
74
|
+
from ledrion import webhooks
|
|
75
|
+
|
|
76
|
+
@app.post("/hooks/ledrion")
|
|
77
|
+
def ledrion_hook():
|
|
78
|
+
ok = webhooks.verify(
|
|
79
|
+
raw_body=request.get_data(), # the bytes as received
|
|
80
|
+
timestamp=request.headers.get(webhooks.HEADER_TIMESTAMP),
|
|
81
|
+
signature=request.headers.get(webhooks.HEADER_SIGNATURE),
|
|
82
|
+
secret=os.environ["LEDRION_WEBHOOK_SECRET"],
|
|
83
|
+
)
|
|
84
|
+
if not ok:
|
|
85
|
+
return "", 400
|
|
86
|
+
event = json.loads(request.get_data())
|
|
87
|
+
# Delivery is at least once: drop an event whose "id" you have already handled.
|
|
88
|
+
# The event holds ids only; read the conversation with ledrion.intakes.get(event["intake_id"]).
|
|
89
|
+
queue_work(event)
|
|
90
|
+
return "", 204 # answer at once; do the work afterwards
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## Errors
|
|
94
|
+
|
|
95
|
+
| Error | When | Attributes |
|
|
96
|
+
|---|---|---|
|
|
97
|
+
| `AuthenticationError` | 401: the key is missing, malformed, unknown or revoked | `status`, `code` |
|
|
98
|
+
| `RateLimitError` | 429 after the retries | `status`, `code`, `retry_after_sec` |
|
|
99
|
+
| `ApiError` | any other refusal (400 `invalid_query`, 404 `not_found`, 503 `api_unavailable`), or a redirect | `status`, `code` |
|
|
100
|
+
| `ConnectionError` | no answer (unreachable, timeout) | `__cause__` |
|
|
101
|
+
|
|
102
|
+
All subclass `LedrionError` (`ledrion.ConnectionError` is the SDK's own, not the builtin). A 429 is
|
|
103
|
+
waited out (its `Retry-After`) and tried again up to `max_retries` times (default 2) when the wait is at
|
|
104
|
+
most `max_retry_wait_sec` (default 60); otherwise it is raised at once. Redirects are never followed
|
|
105
|
+
(urllib would carry the key to the new address).
|
|
106
|
+
|
|
107
|
+
## Types
|
|
108
|
+
|
|
109
|
+
`ledrion.types` holds a `TypedDict` per shape (`CasePacket`, `IntakeListItem`, `Summary`,
|
|
110
|
+
`WebhookEvent`, ...), with the wire's names. `apps/api/test/sdk-conformance.test.ts` fails if a property
|
|
111
|
+
is renamed or removed in the API's document, and runs this client against the API's real routes over HTTP.
|
|
112
|
+
|
|
113
|
+
## Releasing the SDKs
|
|
114
|
+
|
|
115
|
+
- The owner starts it, by hand: GitHub, Actions, **publish-sdks**, Run workflow (`.github/workflows/publish-sdks.yml`).
|
|
116
|
+
Choose `npm`, `pypi` or `both`; `dry_run` is on by default (npm `--dry-run`, `twine check`; nothing leaves). It never
|
|
117
|
+
runs on a push or a tag. Both SDKs are built and tested first, as `scripts/sdk-check.mjs` does.
|
|
118
|
+
- A version already on the registry fails the job with a plain line. Nothing bumps a version: raise it in
|
|
119
|
+
`sdks/node/package.json` and `sdks/python/pyproject.toml` in a PR first.
|
|
120
|
+
- Secrets (GitHub Actions, set by the owner): `NPM_TOKEN` (expires **2027-02-19**; renew before then) and
|
|
121
|
+
`PYPI_API_TOKEN`. After the first PyPI upload, replace the account-wide PyPI token with one scoped to the
|
|
122
|
+
`ledrion` project.
|
|
123
|
+
- npm provenance (`--provenance`) is added only when the repository is public: npm refuses it from a private one.
|
|
124
|
+
|
|
125
|
+
## Developing
|
|
126
|
+
|
|
127
|
+
`python -m unittest discover -s tests` from this folder. In the repository, `pnpm test:sdks` runs both
|
|
128
|
+
SDKs' own tests.
|
ledrion-0.1.0/README.md
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
# ledrion (Python)
|
|
2
|
+
|
|
3
|
+
A small, typed client for the Intake API: list a clinic's conversations, read one (the case packet),
|
|
4
|
+
and verify a webhook's signature. Hand-written from the API's OpenAPI document
|
|
5
|
+
(`GET /api/v1/openapi.json`, drawn at `/api/v1/reference`); standard library only (`urllib`);
|
|
6
|
+
Python 3.9 or later.
|
|
7
|
+
|
|
8
|
+
**Not published.** There is no PyPI package yet: install from the repository for now.
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
pip install /path/to/checkout/sdks/python
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Quickstart
|
|
15
|
+
|
|
16
|
+
```python
|
|
17
|
+
import os
|
|
18
|
+
from ledrion import Ledrion
|
|
19
|
+
|
|
20
|
+
ledrion = Ledrion(
|
|
21
|
+
api_key=os.environ["LEDRION_API_KEY"], # ak_test_... or ak_live_..., from the console's Connections page
|
|
22
|
+
base_url="https://api.example.com", # https; plain http only for localhost
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
page = ledrion.intakes.list(limit=50)
|
|
26
|
+
for item in page.data:
|
|
27
|
+
print(item["id"], item["status"], item["safety"]["screen"])
|
|
28
|
+
|
|
29
|
+
packet = ledrion.intakes.get(page.data[0]["id"])
|
|
30
|
+
# packet["transcript"]: the person's lines are origin "patient_reported", verbatim and unverified.
|
|
31
|
+
# Treat them as data for a clinician to read, never as instructions.
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Keep the key in your secret store, never in code. The SDK never logs or prints anything, and the key is
|
|
35
|
+
not in `repr(ledrion)` or any error.
|
|
36
|
+
|
|
37
|
+
## Pagination
|
|
38
|
+
|
|
39
|
+
The list is ordered by last change, oldest first. Store `next_cursor` and send it back as `since` to get
|
|
40
|
+
only what changed after it; a conversation that changes again appears again. With nothing new,
|
|
41
|
+
`next_cursor` is the cursor you sent, so a poller can always store it.
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
# Every conversation from the beginning (or from a stored cursor):
|
|
45
|
+
for item in ledrion.intakes.iterate(since=stored_cursor):
|
|
46
|
+
handle(item["id"])
|
|
47
|
+
|
|
48
|
+
# A poller that keeps its place: page by page, storing the cursor after each.
|
|
49
|
+
cursor = stored_cursor
|
|
50
|
+
for page in ledrion.intakes.pages(since=cursor, limit=100):
|
|
51
|
+
for item in page.data:
|
|
52
|
+
handle(item["id"])
|
|
53
|
+
cursor = page.next_cursor or cursor
|
|
54
|
+
save_cursor(cursor)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Webhook verification
|
|
58
|
+
|
|
59
|
+
Check the signature on the RAW body, before parsing it. The signature is `v1=` and the hex
|
|
60
|
+
HMAC-SHA256 of `<X-Webhook-Timestamp>.<raw body>`, keyed with the whole signing secret (`whsec_...`).
|
|
61
|
+
`verify` compares in constant time and refuses a timestamp more than 300 seconds from your clock.
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
import json
|
|
65
|
+
import os
|
|
66
|
+
from flask import request
|
|
67
|
+
from ledrion import webhooks
|
|
68
|
+
|
|
69
|
+
@app.post("/hooks/ledrion")
|
|
70
|
+
def ledrion_hook():
|
|
71
|
+
ok = webhooks.verify(
|
|
72
|
+
raw_body=request.get_data(), # the bytes as received
|
|
73
|
+
timestamp=request.headers.get(webhooks.HEADER_TIMESTAMP),
|
|
74
|
+
signature=request.headers.get(webhooks.HEADER_SIGNATURE),
|
|
75
|
+
secret=os.environ["LEDRION_WEBHOOK_SECRET"],
|
|
76
|
+
)
|
|
77
|
+
if not ok:
|
|
78
|
+
return "", 400
|
|
79
|
+
event = json.loads(request.get_data())
|
|
80
|
+
# Delivery is at least once: drop an event whose "id" you have already handled.
|
|
81
|
+
# The event holds ids only; read the conversation with ledrion.intakes.get(event["intake_id"]).
|
|
82
|
+
queue_work(event)
|
|
83
|
+
return "", 204 # answer at once; do the work afterwards
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Errors
|
|
87
|
+
|
|
88
|
+
| Error | When | Attributes |
|
|
89
|
+
|---|---|---|
|
|
90
|
+
| `AuthenticationError` | 401: the key is missing, malformed, unknown or revoked | `status`, `code` |
|
|
91
|
+
| `RateLimitError` | 429 after the retries | `status`, `code`, `retry_after_sec` |
|
|
92
|
+
| `ApiError` | any other refusal (400 `invalid_query`, 404 `not_found`, 503 `api_unavailable`), or a redirect | `status`, `code` |
|
|
93
|
+
| `ConnectionError` | no answer (unreachable, timeout) | `__cause__` |
|
|
94
|
+
|
|
95
|
+
All subclass `LedrionError` (`ledrion.ConnectionError` is the SDK's own, not the builtin). A 429 is
|
|
96
|
+
waited out (its `Retry-After`) and tried again up to `max_retries` times (default 2) when the wait is at
|
|
97
|
+
most `max_retry_wait_sec` (default 60); otherwise it is raised at once. Redirects are never followed
|
|
98
|
+
(urllib would carry the key to the new address).
|
|
99
|
+
|
|
100
|
+
## Types
|
|
101
|
+
|
|
102
|
+
`ledrion.types` holds a `TypedDict` per shape (`CasePacket`, `IntakeListItem`, `Summary`,
|
|
103
|
+
`WebhookEvent`, ...), with the wire's names. `apps/api/test/sdk-conformance.test.ts` fails if a property
|
|
104
|
+
is renamed or removed in the API's document, and runs this client against the API's real routes over HTTP.
|
|
105
|
+
|
|
106
|
+
## Releasing the SDKs
|
|
107
|
+
|
|
108
|
+
- The owner starts it, by hand: GitHub, Actions, **publish-sdks**, Run workflow (`.github/workflows/publish-sdks.yml`).
|
|
109
|
+
Choose `npm`, `pypi` or `both`; `dry_run` is on by default (npm `--dry-run`, `twine check`; nothing leaves). It never
|
|
110
|
+
runs on a push or a tag. Both SDKs are built and tested first, as `scripts/sdk-check.mjs` does.
|
|
111
|
+
- A version already on the registry fails the job with a plain line. Nothing bumps a version: raise it in
|
|
112
|
+
`sdks/node/package.json` and `sdks/python/pyproject.toml` in a PR first.
|
|
113
|
+
- Secrets (GitHub Actions, set by the owner): `NPM_TOKEN` (expires **2027-02-19**; renew before then) and
|
|
114
|
+
`PYPI_API_TOKEN`. After the first PyPI upload, replace the account-wide PyPI token with one scoped to the
|
|
115
|
+
`ledrion` project.
|
|
116
|
+
- npm provenance (`--provenance`) is added only when the repository is public: npm refuses it from a private one.
|
|
117
|
+
|
|
118
|
+
## Developing
|
|
119
|
+
|
|
120
|
+
`python -m unittest discover -s tests` from this folder. In the repository, `pnpm test:sdks` runs both
|
|
121
|
+
SDKs' own tests.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""ledrion: a small, typed client for the Intake API (the pull API and signed webhooks).
|
|
2
|
+
|
|
3
|
+
Hand-written from the OpenAPI document; standard library only. See README.md.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from . import webhooks
|
|
7
|
+
from .client import VERSION, IntakePage, Ledrion
|
|
8
|
+
from .errors import ApiError, AuthenticationError, ConnectionError, LedrionError, RateLimitError
|
|
9
|
+
|
|
10
|
+
__version__ = VERSION
|
|
11
|
+
__all__ = [
|
|
12
|
+
"ApiError",
|
|
13
|
+
"AuthenticationError",
|
|
14
|
+
"ConnectionError",
|
|
15
|
+
"IntakePage",
|
|
16
|
+
"Ledrion",
|
|
17
|
+
"LedrionError",
|
|
18
|
+
"RateLimitError",
|
|
19
|
+
"VERSION",
|
|
20
|
+
"webhooks",
|
|
21
|
+
]
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""The client: the pull API over urllib, with typed errors and Retry-After honored."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
import time
|
|
6
|
+
import urllib.error
|
|
7
|
+
import urllib.parse
|
|
8
|
+
import urllib.request
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from email.utils import parsedate_to_datetime
|
|
11
|
+
from typing import Callable, Iterator, List, Optional
|
|
12
|
+
|
|
13
|
+
from . import webhooks as _webhooks
|
|
14
|
+
from .errors import ApiError, AuthenticationError, ConnectionError, RateLimitError
|
|
15
|
+
from .types import CasePacket, IntakeListItem
|
|
16
|
+
|
|
17
|
+
VERSION = "0.1.0"
|
|
18
|
+
_LOCAL = {"localhost", "127.0.0.1", "::1"}
|
|
19
|
+
_CODE = re.compile(r"[a-z_]{1,40}")
|
|
20
|
+
_MAX_BODY = 8 * 1024 * 1024
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class IntakePage:
|
|
25
|
+
"""One page of GET /api/v1/intakes."""
|
|
26
|
+
|
|
27
|
+
data: List[IntakeListItem] = field(default_factory=list)
|
|
28
|
+
#: Send back as `since`. With nothing new it is the cursor you sent; None only on a first, empty answer.
|
|
29
|
+
next_cursor: Optional[str] = None
|
|
30
|
+
#: True when another page is waiting now.
|
|
31
|
+
has_more: bool = False
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
35
|
+
"""Never follow a redirect: urllib would carry the Authorization header to the new address."""
|
|
36
|
+
|
|
37
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: D102
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Intakes:
|
|
42
|
+
def __init__(self, client: "Ledrion"):
|
|
43
|
+
self._client = client
|
|
44
|
+
|
|
45
|
+
def list(self, *, since: Optional[str] = None, limit: Optional[int] = None) -> IntakePage:
|
|
46
|
+
"""A page of conversations in the order they last changed, oldest change first."""
|
|
47
|
+
query = {}
|
|
48
|
+
if limit is not None:
|
|
49
|
+
query["limit"] = str(limit)
|
|
50
|
+
if since is not None:
|
|
51
|
+
query["since"] = since
|
|
52
|
+
path = "/api/v1/intakes" + ("?" + urllib.parse.urlencode(query) if query else "")
|
|
53
|
+
answer = self._client._get(path)
|
|
54
|
+
return IntakePage(data=answer["data"], next_cursor=answer["next_cursor"], has_more=answer["has_more"])
|
|
55
|
+
|
|
56
|
+
def pages(self, *, since: Optional[str] = None, limit: Optional[int] = None) -> Iterator[IntakePage]:
|
|
57
|
+
"""Every page from `since`, sending each next_cursor back."""
|
|
58
|
+
while True:
|
|
59
|
+
page = self.list(since=since, limit=limit)
|
|
60
|
+
yield page
|
|
61
|
+
if not page.has_more or page.next_cursor is None:
|
|
62
|
+
return
|
|
63
|
+
since = page.next_cursor
|
|
64
|
+
|
|
65
|
+
def iterate(self, *, since: Optional[str] = None, limit: Optional[int] = None) -> Iterator[IntakeListItem]:
|
|
66
|
+
"""Every conversation from `since`, page after page."""
|
|
67
|
+
for page in self.pages(since=since, limit=limit):
|
|
68
|
+
yield from page.data
|
|
69
|
+
|
|
70
|
+
def get(self, intake_id: str) -> CasePacket:
|
|
71
|
+
"""One conversation: the case packet."""
|
|
72
|
+
return self._client._get("/api/v1/intakes/" + urllib.parse.quote(intake_id, safe=""))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class Ledrion:
|
|
76
|
+
"""A client for the Intake API.
|
|
77
|
+
|
|
78
|
+
api_key: the clinic's key (ak_test_... or ak_live_...), from the console's Connections page.
|
|
79
|
+
base_url: the API's address; https, or http only for this machine.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
webhooks = _webhooks
|
|
83
|
+
|
|
84
|
+
def __init__(
|
|
85
|
+
self,
|
|
86
|
+
api_key: str,
|
|
87
|
+
base_url: str,
|
|
88
|
+
*,
|
|
89
|
+
timeout: float = 30.0,
|
|
90
|
+
max_retries: int = 2,
|
|
91
|
+
max_retry_wait_sec: float = 60.0,
|
|
92
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
93
|
+
):
|
|
94
|
+
if not isinstance(api_key, str) or not re.fullmatch(r"\S+", api_key):
|
|
95
|
+
raise ValueError("Ledrion: api_key is required")
|
|
96
|
+
url = urllib.parse.urlsplit(base_url if isinstance(base_url, str) else "")
|
|
97
|
+
if url.scheme not in ("https", "http") or not url.hostname:
|
|
98
|
+
raise ValueError("Ledrion: base_url is not an address")
|
|
99
|
+
if url.scheme != "https" and url.hostname not in _LOCAL:
|
|
100
|
+
raise ValueError("Ledrion: base_url must be https (plain http only for localhost), so the key is never sent in the clear")
|
|
101
|
+
self.__api_key = api_key
|
|
102
|
+
self._base = "%s://%s%s" % (url.scheme, url.netloc, url.path.rstrip("/"))
|
|
103
|
+
self._timeout = timeout
|
|
104
|
+
self._max_retries = max(0, int(max_retries))
|
|
105
|
+
self._max_retry_wait_sec = max_retry_wait_sec
|
|
106
|
+
self._sleep = sleep
|
|
107
|
+
self._opener = urllib.request.build_opener(_NoRedirect())
|
|
108
|
+
self.intakes = Intakes(self)
|
|
109
|
+
|
|
110
|
+
def __repr__(self) -> str:
|
|
111
|
+
return "Ledrion(%r)" % self._base
|
|
112
|
+
|
|
113
|
+
__str__ = __repr__
|
|
114
|
+
|
|
115
|
+
def _get(self, path: str):
|
|
116
|
+
attempt = 0
|
|
117
|
+
while True:
|
|
118
|
+
request = urllib.request.Request(
|
|
119
|
+
self._base + path,
|
|
120
|
+
method="GET",
|
|
121
|
+
headers={"Authorization": "Bearer " + self.__api_key, "Accept": "application/json", "User-Agent": "ledrion-python/" + VERSION},
|
|
122
|
+
)
|
|
123
|
+
try:
|
|
124
|
+
with self._opener.open(request, timeout=self._timeout) as response:
|
|
125
|
+
return json.loads(response.read(_MAX_BODY).decode("utf-8"))
|
|
126
|
+
except urllib.error.HTTPError as answer:
|
|
127
|
+
status, code, retry_after = answer.code, _code_of(answer), _retry_after_of(answer.headers.get("Retry-After"))
|
|
128
|
+
answer.close()
|
|
129
|
+
except (urllib.error.URLError, OSError) as err:
|
|
130
|
+
raise ConnectionError("Ledrion: no answer from the API") from err
|
|
131
|
+
|
|
132
|
+
if status == 401:
|
|
133
|
+
raise AuthenticationError("Ledrion: the API key was refused (401)", 401, code)
|
|
134
|
+
if status == 429:
|
|
135
|
+
if attempt < self._max_retries and retry_after is not None and retry_after <= self._max_retry_wait_sec:
|
|
136
|
+
attempt += 1
|
|
137
|
+
self._sleep(retry_after)
|
|
138
|
+
continue
|
|
139
|
+
suffix = "" if retry_after is None else ", retry after %ds" % retry_after
|
|
140
|
+
raise RateLimitError("Ledrion: rate limited (429)" + suffix, code, retry_after)
|
|
141
|
+
raise ApiError("Ledrion: the API answered %d%s" % (status, " " + code if code else ""), status, code)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _code_of(answer: urllib.error.HTTPError) -> Optional[str]:
|
|
145
|
+
"""The {"error": "<code>"} word, read by shape only; anything else is None and never echoed."""
|
|
146
|
+
try:
|
|
147
|
+
body = json.loads(answer.read(64 * 1024).decode("utf-8"))
|
|
148
|
+
except Exception: # noqa: BLE001
|
|
149
|
+
return None
|
|
150
|
+
code = body.get("error") if isinstance(body, dict) else None
|
|
151
|
+
return code if isinstance(code, str) and _CODE.fullmatch(code) else None
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _retry_after_of(value: Optional[str]) -> Optional[int]:
|
|
155
|
+
"""Seconds from Retry-After: a number of seconds, or an HTTP date."""
|
|
156
|
+
if value is None:
|
|
157
|
+
return None
|
|
158
|
+
value = value.strip()
|
|
159
|
+
if re.fullmatch(r"\d{1,6}", value):
|
|
160
|
+
return int(value)
|
|
161
|
+
try:
|
|
162
|
+
at = parsedate_to_datetime(value)
|
|
163
|
+
except (TypeError, ValueError):
|
|
164
|
+
return None
|
|
165
|
+
return max(0, int(at.timestamp() - time.time() + 0.999))
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Errors carry the HTTP status and the API's code word, nothing more: never the key, never a body."""
|
|
2
|
+
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class LedrionError(Exception):
|
|
7
|
+
"""Base of every error this SDK raises."""
|
|
8
|
+
|
|
9
|
+
def __init__(self, message: str, status: Optional[int] = None, code: Optional[str] = None):
|
|
10
|
+
super().__init__(message)
|
|
11
|
+
#: The HTTP status, or None when no answer came.
|
|
12
|
+
self.status = status
|
|
13
|
+
#: The API's code word (`{"error": "<code>"}`), or None when the answer had none.
|
|
14
|
+
self.code = code
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ApiError(LedrionError):
|
|
18
|
+
"""Any refusal other than 401 and 429 (400 invalid_query, 404 not_found, 503 api_unavailable, ...)."""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class AuthenticationError(LedrionError):
|
|
22
|
+
"""401: the key is missing, malformed, unknown or revoked (one answer for all of them)."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class RateLimitError(LedrionError):
|
|
26
|
+
"""429: too many requests. `retry_after_sec` is the server's Retry-After, when it sent one."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, message: str, code: Optional[str], retry_after_sec: Optional[int]):
|
|
29
|
+
super().__init__(message, 429, code)
|
|
30
|
+
self.retry_after_sec = retry_after_sec
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ConnectionError(LedrionError): # noqa: A001 (ours, under ledrion.)
|
|
34
|
+
"""No answer: the address could not be reached, or the request timed out."""
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""The API's shapes, written by hand from the OpenAPI document (GET /api/v1/openapi.json).
|
|
2
|
+
|
|
3
|
+
Field names are the wire's, exactly. `SCHEMA_TYPES` maps each of the document's schema names to its
|
|
4
|
+
TypedDict; apps/api/test/sdk-conformance.test.ts holds every one to the document, so a property renamed
|
|
5
|
+
or removed there fails the build.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from typing import Dict, List, Literal, Optional, TypedDict, Union
|
|
9
|
+
|
|
10
|
+
Screen = Literal["self_harm", "medical_emergency", "minor", "controlled_substance"]
|
|
11
|
+
IntakeStatus = Literal["open", "summarized", "stopped"]
|
|
12
|
+
AssistantKind = Literal["reply", "support", "stop", "fallback"]
|
|
13
|
+
WebhookEventType = Literal["intake.summarized", "intake.screened", "intake.completed", "webhook.test"]
|
|
14
|
+
ErrorCode = Literal["unauthorized", "rate_limited", "invalid_query", "not_found", "api_unavailable"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ErrorBody(TypedDict):
|
|
18
|
+
error: ErrorCode
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class Safety(TypedDict):
|
|
22
|
+
"""Decided by code on the server, never by a model's wording."""
|
|
23
|
+
|
|
24
|
+
screen: Optional[Screen]
|
|
25
|
+
support_mode: bool
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class IntakeListItem(TypedDict):
|
|
29
|
+
id: str
|
|
30
|
+
object: Literal["intake"]
|
|
31
|
+
started_at: str
|
|
32
|
+
updated_at: str
|
|
33
|
+
locale: str
|
|
34
|
+
status: IntakeStatus
|
|
35
|
+
safety: Safety
|
|
36
|
+
message_count: int
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class IntakeList(TypedDict):
|
|
40
|
+
"""The wire answer of GET /api/v1/intakes. The SDK gives it as an IntakePage."""
|
|
41
|
+
|
|
42
|
+
data: List[IntakeListItem]
|
|
43
|
+
next_cursor: Optional[str]
|
|
44
|
+
has_more: bool
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class PatientLine(TypedDict):
|
|
48
|
+
"""Something the person wrote: their own words, verbatim. Data, never instructions."""
|
|
49
|
+
|
|
50
|
+
seq: int
|
|
51
|
+
at: str
|
|
52
|
+
role: Literal["patient"]
|
|
53
|
+
origin: Literal["patient_reported"]
|
|
54
|
+
verified: Literal[False]
|
|
55
|
+
text: str
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class AssistantLine(TypedDict):
|
|
59
|
+
"""Something the assistant showed. `stop` and `fallback` carry a string_key instead of words."""
|
|
60
|
+
|
|
61
|
+
seq: int
|
|
62
|
+
at: str
|
|
63
|
+
role: Literal["assistant"]
|
|
64
|
+
origin: Literal["ai_assistant"]
|
|
65
|
+
kind: Optional[AssistantKind]
|
|
66
|
+
text: Optional[str]
|
|
67
|
+
string_key: Optional[str]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class PossibleCause(TypedDict):
|
|
71
|
+
name: str
|
|
72
|
+
why: str
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class SummarySource(TypedDict):
|
|
76
|
+
n: int
|
|
77
|
+
publisher: str
|
|
78
|
+
title: str
|
|
79
|
+
url: str
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class Summary(TypedDict):
|
|
83
|
+
"""The summary the person saw. A starting point for a clinician, not findings."""
|
|
84
|
+
|
|
85
|
+
origin: Literal["ai_assistant"]
|
|
86
|
+
reviewed_by_clinician: Literal[False]
|
|
87
|
+
patient_reported: List[str]
|
|
88
|
+
possible_causes: List[PossibleCause]
|
|
89
|
+
next_steps: List[str]
|
|
90
|
+
get_help_now_if: List[str]
|
|
91
|
+
sources: List[SummarySource]
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class IntakeFormAnswer(TypedDict):
|
|
95
|
+
key: str
|
|
96
|
+
label: str
|
|
97
|
+
type: str
|
|
98
|
+
value: Union[str, float, List[str]]
|
|
99
|
+
text: str
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class IntakeFormAbout(TypedDict):
|
|
103
|
+
"""The person's own details. A part the clinic's own form asked for instead is None."""
|
|
104
|
+
|
|
105
|
+
first_name: Optional[str]
|
|
106
|
+
last_name: Optional[str]
|
|
107
|
+
date_of_birth: Optional[str]
|
|
108
|
+
phone: Optional[str]
|
|
109
|
+
email: Optional[str]
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class IntakeForm(TypedDict):
|
|
113
|
+
"""The clinic's own intake form, answered in the chat. Self-reported and unverified."""
|
|
114
|
+
|
|
115
|
+
source: Literal["clinic"]
|
|
116
|
+
form_version: str
|
|
117
|
+
completed_at: Optional[str]
|
|
118
|
+
origin: Literal["patient_reported"]
|
|
119
|
+
verified: Literal[False]
|
|
120
|
+
reviewed_by_clinician: Literal[False]
|
|
121
|
+
notice: str
|
|
122
|
+
about: Optional[IntakeFormAbout]
|
|
123
|
+
answers: Optional[List[IntakeFormAnswer]]
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class _CasePacketRequired(TypedDict):
|
|
127
|
+
id: str
|
|
128
|
+
object: Literal["intake"]
|
|
129
|
+
clinic: str
|
|
130
|
+
started_at: str
|
|
131
|
+
updated_at: str
|
|
132
|
+
locale: str
|
|
133
|
+
status: IntakeStatus
|
|
134
|
+
safety: Safety
|
|
135
|
+
notice: str
|
|
136
|
+
reviewed_by_clinician: Literal[False]
|
|
137
|
+
transcript_notice: str
|
|
138
|
+
transcript: List[Union[PatientLine, AssistantLine]]
|
|
139
|
+
summary: Optional[Summary]
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class CasePacket(_CasePacketRequired, total=False):
|
|
143
|
+
"""One conversation as a clinic's system receives it. Gathered by an AI assistant; unreviewed."""
|
|
144
|
+
|
|
145
|
+
#: Present on servers that keep intake forms.
|
|
146
|
+
form: Optional[IntakeForm]
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class WebhookEvent(TypedDict):
|
|
150
|
+
"""A webhook's body: ids, a type and a time, never anything a patient wrote."""
|
|
151
|
+
|
|
152
|
+
id: str
|
|
153
|
+
type: WebhookEventType
|
|
154
|
+
clinic: str
|
|
155
|
+
intake_id: Optional[str]
|
|
156
|
+
created_at: str
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
#: Every type, by the document's schema name (`Name.prop[]` for an inline item shape).
|
|
160
|
+
SCHEMA_TYPES: Dict[str, type] = {
|
|
161
|
+
"Error": ErrorBody,
|
|
162
|
+
"Safety": Safety,
|
|
163
|
+
"IntakeListItem": IntakeListItem,
|
|
164
|
+
"IntakeList": IntakeList,
|
|
165
|
+
"PatientLine": PatientLine,
|
|
166
|
+
"AssistantLine": AssistantLine,
|
|
167
|
+
"Summary": Summary,
|
|
168
|
+
"Summary.possible_causes[]": PossibleCause,
|
|
169
|
+
"Summary.sources[]": SummarySource,
|
|
170
|
+
"IntakeFormAnswer": IntakeFormAnswer,
|
|
171
|
+
"IntakeForm": IntakeForm,
|
|
172
|
+
"IntakeForm.about": IntakeFormAbout,
|
|
173
|
+
"CasePacket": CasePacket,
|
|
174
|
+
"WebhookEvent": WebhookEvent,
|
|
175
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Verify a webhook's signature: `v1=` and the hex HMAC-SHA256 of `<timestamp>.<raw body>`."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import hmac
|
|
5
|
+
import re
|
|
6
|
+
import time
|
|
7
|
+
from typing import Optional, Union
|
|
8
|
+
|
|
9
|
+
#: Refuse a timestamp further than this from your clock, in seconds.
|
|
10
|
+
SIGNATURE_TOLERANCE_SEC = 300
|
|
11
|
+
|
|
12
|
+
#: The headers a webhook arrives with, as the server names them.
|
|
13
|
+
HEADER_ID = "X-Webhook-Id"
|
|
14
|
+
HEADER_TIMESTAMP = "X-Webhook-Timestamp"
|
|
15
|
+
HEADER_SIGNATURE = "X-Webhook-Signature"
|
|
16
|
+
|
|
17
|
+
_TIMESTAMP = re.compile(r"\d{1,12}", re.ASCII)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def verify(
|
|
21
|
+
*,
|
|
22
|
+
raw_body: Union[bytes, str],
|
|
23
|
+
timestamp: Optional[str],
|
|
24
|
+
signature: Optional[str],
|
|
25
|
+
secret: str,
|
|
26
|
+
tolerance_sec: int = SIGNATURE_TOLERANCE_SEC,
|
|
27
|
+
now: Optional[int] = None,
|
|
28
|
+
) -> bool:
|
|
29
|
+
"""True only when the signature is the server's for this body and timestamp, and the timestamp is
|
|
30
|
+
within `tolerance_sec` of now. Compared in constant time. Never raises.
|
|
31
|
+
|
|
32
|
+
raw_body: the body exactly as received, BEFORE any JSON parsing (bytes; text is read as UTF-8).
|
|
33
|
+
timestamp: the `X-Webhook-Timestamp` header.
|
|
34
|
+
signature: the `X-Webhook-Signature` header.
|
|
35
|
+
secret: the whole `whsec_...` text the console showed once.
|
|
36
|
+
"""
|
|
37
|
+
if not isinstance(timestamp, str) or not _TIMESTAMP.fullmatch(timestamp):
|
|
38
|
+
return False
|
|
39
|
+
if not isinstance(signature, str) or not isinstance(secret, str) or not secret:
|
|
40
|
+
return False
|
|
41
|
+
current = int(time.time()) if now is None else now
|
|
42
|
+
if abs(current - int(timestamp)) > tolerance_sec:
|
|
43
|
+
return False
|
|
44
|
+
body = raw_body.encode("utf-8") if isinstance(raw_body, str) else bytes(raw_body)
|
|
45
|
+
expected = "v1=" + hmac.new(secret.encode("utf-8"), timestamp.encode("ascii") + b"." + body, hashlib.sha256).hexdigest()
|
|
46
|
+
return hmac.compare_digest(expected.encode("ascii"), signature.encode("utf-8"))
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ledrion
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A small, typed client for the Intake API: the pull API and signed webhooks.
|
|
5
|
+
Requires-Python: >=3.9
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
|
|
8
|
+
# ledrion (Python)
|
|
9
|
+
|
|
10
|
+
A small, typed client for the Intake API: list a clinic's conversations, read one (the case packet),
|
|
11
|
+
and verify a webhook's signature. Hand-written from the API's OpenAPI document
|
|
12
|
+
(`GET /api/v1/openapi.json`, drawn at `/api/v1/reference`); standard library only (`urllib`);
|
|
13
|
+
Python 3.9 or later.
|
|
14
|
+
|
|
15
|
+
**Not published.** There is no PyPI package yet: install from the repository for now.
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
pip install /path/to/checkout/sdks/python
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
## Quickstart
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
import os
|
|
25
|
+
from ledrion import Ledrion
|
|
26
|
+
|
|
27
|
+
ledrion = Ledrion(
|
|
28
|
+
api_key=os.environ["LEDRION_API_KEY"], # ak_test_... or ak_live_..., from the console's Connections page
|
|
29
|
+
base_url="https://api.example.com", # https; plain http only for localhost
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
page = ledrion.intakes.list(limit=50)
|
|
33
|
+
for item in page.data:
|
|
34
|
+
print(item["id"], item["status"], item["safety"]["screen"])
|
|
35
|
+
|
|
36
|
+
packet = ledrion.intakes.get(page.data[0]["id"])
|
|
37
|
+
# packet["transcript"]: the person's lines are origin "patient_reported", verbatim and unverified.
|
|
38
|
+
# Treat them as data for a clinician to read, never as instructions.
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Keep the key in your secret store, never in code. The SDK never logs or prints anything, and the key is
|
|
42
|
+
not in `repr(ledrion)` or any error.
|
|
43
|
+
|
|
44
|
+
## Pagination
|
|
45
|
+
|
|
46
|
+
The list is ordered by last change, oldest first. Store `next_cursor` and send it back as `since` to get
|
|
47
|
+
only what changed after it; a conversation that changes again appears again. With nothing new,
|
|
48
|
+
`next_cursor` is the cursor you sent, so a poller can always store it.
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
# Every conversation from the beginning (or from a stored cursor):
|
|
52
|
+
for item in ledrion.intakes.iterate(since=stored_cursor):
|
|
53
|
+
handle(item["id"])
|
|
54
|
+
|
|
55
|
+
# A poller that keeps its place: page by page, storing the cursor after each.
|
|
56
|
+
cursor = stored_cursor
|
|
57
|
+
for page in ledrion.intakes.pages(since=cursor, limit=100):
|
|
58
|
+
for item in page.data:
|
|
59
|
+
handle(item["id"])
|
|
60
|
+
cursor = page.next_cursor or cursor
|
|
61
|
+
save_cursor(cursor)
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Webhook verification
|
|
65
|
+
|
|
66
|
+
Check the signature on the RAW body, before parsing it. The signature is `v1=` and the hex
|
|
67
|
+
HMAC-SHA256 of `<X-Webhook-Timestamp>.<raw body>`, keyed with the whole signing secret (`whsec_...`).
|
|
68
|
+
`verify` compares in constant time and refuses a timestamp more than 300 seconds from your clock.
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
import json
|
|
72
|
+
import os
|
|
73
|
+
from flask import request
|
|
74
|
+
from ledrion import webhooks
|
|
75
|
+
|
|
76
|
+
@app.post("/hooks/ledrion")
|
|
77
|
+
def ledrion_hook():
|
|
78
|
+
ok = webhooks.verify(
|
|
79
|
+
raw_body=request.get_data(), # the bytes as received
|
|
80
|
+
timestamp=request.headers.get(webhooks.HEADER_TIMESTAMP),
|
|
81
|
+
signature=request.headers.get(webhooks.HEADER_SIGNATURE),
|
|
82
|
+
secret=os.environ["LEDRION_WEBHOOK_SECRET"],
|
|
83
|
+
)
|
|
84
|
+
if not ok:
|
|
85
|
+
return "", 400
|
|
86
|
+
event = json.loads(request.get_data())
|
|
87
|
+
# Delivery is at least once: drop an event whose "id" you have already handled.
|
|
88
|
+
# The event holds ids only; read the conversation with ledrion.intakes.get(event["intake_id"]).
|
|
89
|
+
queue_work(event)
|
|
90
|
+
return "", 204 # answer at once; do the work afterwards
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## Errors
|
|
94
|
+
|
|
95
|
+
| Error | When | Attributes |
|
|
96
|
+
|---|---|---|
|
|
97
|
+
| `AuthenticationError` | 401: the key is missing, malformed, unknown or revoked | `status`, `code` |
|
|
98
|
+
| `RateLimitError` | 429 after the retries | `status`, `code`, `retry_after_sec` |
|
|
99
|
+
| `ApiError` | any other refusal (400 `invalid_query`, 404 `not_found`, 503 `api_unavailable`), or a redirect | `status`, `code` |
|
|
100
|
+
| `ConnectionError` | no answer (unreachable, timeout) | `__cause__` |
|
|
101
|
+
|
|
102
|
+
All subclass `LedrionError` (`ledrion.ConnectionError` is the SDK's own, not the builtin). A 429 is
|
|
103
|
+
waited out (its `Retry-After`) and tried again up to `max_retries` times (default 2) when the wait is at
|
|
104
|
+
most `max_retry_wait_sec` (default 60); otherwise it is raised at once. Redirects are never followed
|
|
105
|
+
(urllib would carry the key to the new address).
|
|
106
|
+
|
|
107
|
+
## Types
|
|
108
|
+
|
|
109
|
+
`ledrion.types` holds a `TypedDict` per shape (`CasePacket`, `IntakeListItem`, `Summary`,
|
|
110
|
+
`WebhookEvent`, ...), with the wire's names. `apps/api/test/sdk-conformance.test.ts` fails if a property
|
|
111
|
+
is renamed or removed in the API's document, and runs this client against the API's real routes over HTTP.
|
|
112
|
+
|
|
113
|
+
## Releasing the SDKs
|
|
114
|
+
|
|
115
|
+
- The owner starts it, by hand: GitHub, Actions, **publish-sdks**, Run workflow (`.github/workflows/publish-sdks.yml`).
|
|
116
|
+
Choose `npm`, `pypi` or `both`; `dry_run` is on by default (npm `--dry-run`, `twine check`; nothing leaves). It never
|
|
117
|
+
runs on a push or a tag. Both SDKs are built and tested first, as `scripts/sdk-check.mjs` does.
|
|
118
|
+
- A version already on the registry fails the job with a plain line. Nothing bumps a version: raise it in
|
|
119
|
+
`sdks/node/package.json` and `sdks/python/pyproject.toml` in a PR first.
|
|
120
|
+
- Secrets (GitHub Actions, set by the owner): `NPM_TOKEN` (expires **2027-02-19**; renew before then) and
|
|
121
|
+
`PYPI_API_TOKEN`. After the first PyPI upload, replace the account-wide PyPI token with one scoped to the
|
|
122
|
+
`ledrion` project.
|
|
123
|
+
- npm provenance (`--provenance`) is added only when the repository is public: npm refuses it from a private one.
|
|
124
|
+
|
|
125
|
+
## Developing
|
|
126
|
+
|
|
127
|
+
`python -m unittest discover -s tests` from this folder. In the repository, `pnpm test:sdks` runs both
|
|
128
|
+
SDKs' own tests.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
ledrion/__init__.py
|
|
4
|
+
ledrion/client.py
|
|
5
|
+
ledrion/errors.py
|
|
6
|
+
ledrion/types.py
|
|
7
|
+
ledrion/webhooks.py
|
|
8
|
+
ledrion.egg-info/PKG-INFO
|
|
9
|
+
ledrion.egg-info/SOURCES.txt
|
|
10
|
+
ledrion.egg-info/dependency_links.txt
|
|
11
|
+
ledrion.egg-info/top_level.txt
|
|
12
|
+
tests/test_sdk.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
ledrion
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "ledrion"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "A small, typed client for the Intake API: the pull API and signed webhooks."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
dependencies = []
|
|
12
|
+
|
|
13
|
+
[tool.setuptools]
|
|
14
|
+
packages = ["ledrion"]
|
ledrion-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""The SDK's own tests: stdlib only. Run from sdks/python with `python -m unittest discover -s tests`.
|
|
2
|
+
|
|
3
|
+
A small local HTTP server stands in for the API. The conformance test that holds this SDK to the real
|
|
4
|
+
API and its OpenAPI document is apps/api/test/sdk-conformance.test.ts.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import hashlib
|
|
8
|
+
import hmac
|
|
9
|
+
import json
|
|
10
|
+
import threading
|
|
11
|
+
import unittest
|
|
12
|
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
13
|
+
from urllib.parse import parse_qs, urlparse
|
|
14
|
+
|
|
15
|
+
from ledrion import (
|
|
16
|
+
ApiError,
|
|
17
|
+
AuthenticationError,
|
|
18
|
+
IntakePage,
|
|
19
|
+
Ledrion,
|
|
20
|
+
LedrionError,
|
|
21
|
+
RateLimitError,
|
|
22
|
+
webhooks,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
KEY = "ak_test_" + "k" * 43
|
|
26
|
+
ITEM = {
|
|
27
|
+
"id": "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
|
|
28
|
+
"object": "intake",
|
|
29
|
+
"started_at": "2026-11-21T11:00:00.000Z",
|
|
30
|
+
"updated_at": "2026-11-21T11:05:00.000Z",
|
|
31
|
+
"locale": "en",
|
|
32
|
+
"status": "summarized",
|
|
33
|
+
"safety": {"screen": None, "support_mode": False},
|
|
34
|
+
"message_count": 4,
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class FakeApi:
|
|
39
|
+
"""Answers queued (status, body, headers) in order and records every request."""
|
|
40
|
+
|
|
41
|
+
def __init__(self):
|
|
42
|
+
self.answers = []
|
|
43
|
+
self.requests = []
|
|
44
|
+
api = self
|
|
45
|
+
|
|
46
|
+
class Handler(BaseHTTPRequestHandler):
|
|
47
|
+
def do_GET(self): # noqa: N802
|
|
48
|
+
api.requests.append({"path": self.path, "headers": dict(self.headers)})
|
|
49
|
+
status, body, headers = api.answers.pop(0)
|
|
50
|
+
data = body if isinstance(body, bytes) else json.dumps(body).encode()
|
|
51
|
+
self.send_response(status)
|
|
52
|
+
for k, v in headers.items():
|
|
53
|
+
self.send_header(k, v)
|
|
54
|
+
self.send_header("Content-Length", str(len(data)))
|
|
55
|
+
self.end_headers()
|
|
56
|
+
self.wfile.write(data)
|
|
57
|
+
|
|
58
|
+
def log_message(self, *args):
|
|
59
|
+
pass
|
|
60
|
+
|
|
61
|
+
self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
|
62
|
+
self.thread = threading.Thread(target=self.server.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True)
|
|
63
|
+
self.thread.start()
|
|
64
|
+
self.base = "http://127.0.0.1:%d" % self.server.server_address[1]
|
|
65
|
+
|
|
66
|
+
def close(self):
|
|
67
|
+
self.server.shutdown()
|
|
68
|
+
self.server.server_close()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class ClientTest(unittest.TestCase):
|
|
72
|
+
def setUp(self):
|
|
73
|
+
self.api = FakeApi()
|
|
74
|
+
self.waits = []
|
|
75
|
+
self.client = Ledrion(api_key=KEY, base_url=self.api.base, sleep=self.waits.append)
|
|
76
|
+
|
|
77
|
+
def tearDown(self):
|
|
78
|
+
self.api.close()
|
|
79
|
+
|
|
80
|
+
def test_needs_a_key_and_https(self):
|
|
81
|
+
with self.assertRaises(ValueError):
|
|
82
|
+
Ledrion(api_key="", base_url="https://api.example.test")
|
|
83
|
+
with self.assertRaises(ValueError) as caught:
|
|
84
|
+
Ledrion(api_key=KEY, base_url="http://api.example.test")
|
|
85
|
+
self.assertNotIn(KEY, str(caught.exception))
|
|
86
|
+
Ledrion(api_key=KEY, base_url="https://api.example.test")
|
|
87
|
+
Ledrion(api_key=KEY, base_url="http://localhost:8080")
|
|
88
|
+
|
|
89
|
+
def test_never_shows_the_key(self):
|
|
90
|
+
self.assertNotIn(KEY, repr(self.client))
|
|
91
|
+
self.assertNotIn(KEY, str(self.client))
|
|
92
|
+
|
|
93
|
+
def test_list_sends_key_limit_since_and_gives_the_page(self):
|
|
94
|
+
self.api.answers.append((200, {"data": [ITEM], "next_cursor": "c1", "has_more": True}, {}))
|
|
95
|
+
page = self.client.intakes.list(since="2026-11-21T11:05:00.000Z_x", limit=10)
|
|
96
|
+
self.assertIsInstance(page, IntakePage)
|
|
97
|
+
self.assertEqual(page.data, [ITEM])
|
|
98
|
+
self.assertEqual(page.next_cursor, "c1")
|
|
99
|
+
self.assertTrue(page.has_more)
|
|
100
|
+
req = self.api.requests[0]
|
|
101
|
+
url = urlparse(req["path"])
|
|
102
|
+
self.assertEqual(url.path, "/api/v1/intakes")
|
|
103
|
+
self.assertEqual(parse_qs(url.query), {"limit": ["10"], "since": ["2026-11-21T11:05:00.000Z_x"]})
|
|
104
|
+
self.assertEqual(req["headers"]["Authorization"], "Bearer " + KEY)
|
|
105
|
+
|
|
106
|
+
def test_list_with_nothing_sends_no_query(self):
|
|
107
|
+
self.api.answers.append((200, {"data": [], "next_cursor": None, "has_more": False}, {}))
|
|
108
|
+
page = self.client.intakes.list()
|
|
109
|
+
self.assertEqual((page.data, page.next_cursor, page.has_more), ([], None, False))
|
|
110
|
+
self.assertEqual(self.api.requests[0]["path"], "/api/v1/intakes")
|
|
111
|
+
|
|
112
|
+
def test_iterate_walks_every_page(self):
|
|
113
|
+
second = dict(ITEM, id="bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")
|
|
114
|
+
self.api.answers.append((200, {"data": [ITEM], "next_cursor": "c1", "has_more": True}, {}))
|
|
115
|
+
self.api.answers.append((200, {"data": [second], "next_cursor": "c2", "has_more": False}, {}))
|
|
116
|
+
seen = [d["id"] for d in self.client.intakes.iterate(limit=1)]
|
|
117
|
+
self.assertEqual(seen, [ITEM["id"], second["id"]])
|
|
118
|
+
self.assertEqual(parse_qs(urlparse(self.api.requests[1]["path"]).query)["since"], ["c1"])
|
|
119
|
+
self.assertEqual(len(self.api.requests), 2)
|
|
120
|
+
|
|
121
|
+
def test_get_reads_one_and_escapes_the_id(self):
|
|
122
|
+
self.api.answers.append((200, {"id": ITEM["id"], "object": "intake"}, {}))
|
|
123
|
+
self.assertEqual(self.client.intakes.get(ITEM["id"])["id"], ITEM["id"])
|
|
124
|
+
self.assertEqual(self.api.requests[0]["path"], "/api/v1/intakes/" + ITEM["id"])
|
|
125
|
+
self.api.answers.append((404, {"error": "not_found"}, {}))
|
|
126
|
+
with self.assertRaises(ApiError):
|
|
127
|
+
self.client.intakes.get("../x?y")
|
|
128
|
+
self.assertEqual(self.api.requests[1]["path"], "/api/v1/intakes/..%2Fx%3Fy")
|
|
129
|
+
|
|
130
|
+
def test_401_is_an_authentication_error_without_the_key(self):
|
|
131
|
+
self.api.answers.append((401, {"error": "unauthorized"}, {"WWW-Authenticate": "Bearer"}))
|
|
132
|
+
with self.assertRaises(AuthenticationError) as caught:
|
|
133
|
+
self.client.intakes.list()
|
|
134
|
+
err = caught.exception
|
|
135
|
+
self.assertIsInstance(err, LedrionError)
|
|
136
|
+
self.assertEqual((err.status, err.code), (401, "unauthorized"))
|
|
137
|
+
self.assertNotIn(KEY, str(err) + repr(err))
|
|
138
|
+
|
|
139
|
+
def test_429_waits_retry_after_and_tries_again(self):
|
|
140
|
+
self.api.answers.append((429, {"error": "rate_limited"}, {"Retry-After": "7"}))
|
|
141
|
+
self.api.answers.append((200, {"data": [], "next_cursor": None, "has_more": False}, {}))
|
|
142
|
+
self.client.intakes.list()
|
|
143
|
+
self.assertEqual(self.waits, [7])
|
|
144
|
+
self.assertEqual(len(self.api.requests), 2)
|
|
145
|
+
|
|
146
|
+
def test_429_past_the_retries_is_a_rate_limit_error(self):
|
|
147
|
+
for _ in range(3):
|
|
148
|
+
self.api.answers.append((429, {"error": "rate_limited"}, {"Retry-After": "3"}))
|
|
149
|
+
with self.assertRaises(RateLimitError) as caught:
|
|
150
|
+
self.client.intakes.list()
|
|
151
|
+
self.assertEqual(caught.exception.retry_after_sec, 3)
|
|
152
|
+
self.assertEqual(caught.exception.code, "rate_limited")
|
|
153
|
+
self.assertEqual(self.waits, [3, 3])
|
|
154
|
+
self.assertEqual(len(self.api.requests), 3)
|
|
155
|
+
|
|
156
|
+
def test_429_with_a_long_wait_is_not_waited_for(self):
|
|
157
|
+
self.api.answers.append((429, {"error": "rate_limited"}, {"Retry-After": "120"}))
|
|
158
|
+
with self.assertRaises(RateLimitError) as caught:
|
|
159
|
+
self.client.intakes.list()
|
|
160
|
+
self.assertEqual(caught.exception.retry_after_sec, 120)
|
|
161
|
+
self.assertEqual(self.waits, [])
|
|
162
|
+
|
|
163
|
+
def test_another_status_is_an_api_error_with_the_code_or_none(self):
|
|
164
|
+
self.api.answers.append((400, {"error": "invalid_query"}, {}))
|
|
165
|
+
self.api.answers.append((502, b"<html>oops</html>", {"Content-Type": "text/html"}))
|
|
166
|
+
with self.assertRaises(ApiError) as a:
|
|
167
|
+
self.client.intakes.list()
|
|
168
|
+
self.assertEqual((a.exception.status, a.exception.code), (400, "invalid_query"))
|
|
169
|
+
with self.assertRaises(ApiError) as b:
|
|
170
|
+
self.client.intakes.list()
|
|
171
|
+
self.assertEqual((b.exception.status, b.exception.code), (502, None))
|
|
172
|
+
self.assertNotIn("oops", str(b.exception))
|
|
173
|
+
|
|
174
|
+
def test_a_redirect_is_never_followed(self):
|
|
175
|
+
self.api.answers.append((302, b"", {"Location": "http://127.0.0.1:1/steal"}))
|
|
176
|
+
with self.assertRaises(ApiError) as caught:
|
|
177
|
+
self.client.intakes.list()
|
|
178
|
+
self.assertEqual(caught.exception.status, 302)
|
|
179
|
+
self.assertEqual(len(self.api.requests), 1)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class WebhookTest(unittest.TestCase):
|
|
183
|
+
secret = "whsec_" + "t" * 43
|
|
184
|
+
body = b'{"id":"evt_00000000000000000000000000000000","type":"webhook.test"}'
|
|
185
|
+
at = 1800000000
|
|
186
|
+
|
|
187
|
+
def sign(self, secret, at, body):
|
|
188
|
+
return "v1=" + hmac.new(secret.encode(), str(at).encode() + b"." + body, hashlib.sha256).hexdigest()
|
|
189
|
+
|
|
190
|
+
def verify(self, **over):
|
|
191
|
+
args = dict(raw_body=self.body, timestamp=str(self.at), signature=self.sign(self.secret, self.at, self.body), secret=self.secret, now=self.at)
|
|
192
|
+
args.update(over)
|
|
193
|
+
return webhooks.verify(**args)
|
|
194
|
+
|
|
195
|
+
def test_accepts_the_servers_signature_as_bytes_or_text(self):
|
|
196
|
+
self.assertTrue(self.verify())
|
|
197
|
+
self.assertTrue(self.verify(raw_body=self.body.decode()))
|
|
198
|
+
|
|
199
|
+
def test_refuses_anything_changed(self):
|
|
200
|
+
self.assertFalse(self.verify(raw_body=self.body + b" "))
|
|
201
|
+
self.assertFalse(self.verify(secret=self.secret + "x"))
|
|
202
|
+
self.assertFalse(self.verify(signature=self.sign(self.secret, self.at, self.body)[:-1]))
|
|
203
|
+
self.assertFalse(self.verify(signature=self.sign(self.secret, self.at, self.body).replace("v1=", "v2=")))
|
|
204
|
+
self.assertFalse(self.verify(timestamp="1e9"))
|
|
205
|
+
self.assertFalse(self.verify(timestamp=None))
|
|
206
|
+
self.assertFalse(self.verify(signature=None))
|
|
207
|
+
self.assertFalse(self.verify(secret=""))
|
|
208
|
+
|
|
209
|
+
def test_refuses_a_timestamp_outside_the_tolerance(self):
|
|
210
|
+
self.assertEqual(webhooks.SIGNATURE_TOLERANCE_SEC, 300)
|
|
211
|
+
self.assertTrue(self.verify(now=self.at + 300))
|
|
212
|
+
self.assertFalse(self.verify(now=self.at + 301))
|
|
213
|
+
self.assertFalse(self.verify(now=self.at - 301))
|
|
214
|
+
self.assertTrue(self.verify(now=self.at + 500, tolerance_sec=600))
|
|
215
|
+
|
|
216
|
+
def test_is_on_the_client_too(self):
|
|
217
|
+
client = Ledrion(api_key=KEY, base_url="https://api.example.test")
|
|
218
|
+
self.assertTrue(client.webhooks.verify(raw_body=self.body, timestamp=str(self.at), signature=self.sign(self.secret, self.at, self.body), secret=self.secret, now=self.at))
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
if __name__ == "__main__":
|
|
222
|
+
unittest.main()
|