fvs-client 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.
- fvs_client/__init__.py +134 -0
- fvs_client/_async/__init__.py +1 -0
- fvs_client/_async/client.py +1069 -0
- fvs_client/_async/transport.py +114 -0
- fvs_client/_bodies.py +42 -0
- fvs_client/_config.py +154 -0
- fvs_client/_headers.py +37 -0
- fvs_client/_inputs.py +281 -0
- fvs_client/_logging.py +49 -0
- fvs_client/_parsing.py +471 -0
- fvs_client/_problems.py +183 -0
- fvs_client/_requests.py +295 -0
- fvs_client/_retry.py +82 -0
- fvs_client/_sync/__init__.py +1 -0
- fvs_client/_sync/client.py +1062 -0
- fvs_client/_sync/transport.py +113 -0
- fvs_client/_version.py +24 -0
- fvs_client/errors.py +257 -0
- fvs_client/models.py +1159 -0
- fvs_client/py.typed +0 -0
- fvs_client-0.1.0.dist-info/METADATA +124 -0
- fvs_client-0.1.0.dist-info/RECORD +25 -0
- fvs_client-0.1.0.dist-info/WHEEL +4 -0
- fvs_client-0.1.0.dist-info/licenses/LICENSE +202 -0
- fvs_client-0.1.0.dist-info/licenses/NOTICE +8 -0
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Asynchronous send loop: mirrors ``fvs_client._sync.transport`` line for line."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import random
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
8
|
+
from typing import cast
|
|
9
|
+
|
|
10
|
+
import anyio
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from fvs_client._config import Settings
|
|
14
|
+
from fvs_client._logging import log_attempt, log_retry
|
|
15
|
+
from fvs_client._parsing import build_meta, build_raw, is_report
|
|
16
|
+
from fvs_client._requests import RequestSpec, request_headers, request_kwargs
|
|
17
|
+
from fvs_client._retry import RetryPolicy
|
|
18
|
+
from fvs_client.errors import FVSConnectionError, FVSTimeoutError, TransportError
|
|
19
|
+
from fvs_client.models import RawResponse
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class AsyncTransport:
|
|
23
|
+
"""Sends ``RequestSpec`` objects with an ``httpx.AsyncClient``."""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
http: httpx.AsyncClient,
|
|
28
|
+
settings: Settings,
|
|
29
|
+
*,
|
|
30
|
+
sleep: Callable[[float], Awaitable[None]] | None = None,
|
|
31
|
+
clock: Callable[[], float] = time.perf_counter,
|
|
32
|
+
rng: random.Random | None = None,
|
|
33
|
+
) -> None:
|
|
34
|
+
self._http = http
|
|
35
|
+
self._settings = settings
|
|
36
|
+
self._sleep = sleep
|
|
37
|
+
self._clock = clock
|
|
38
|
+
self._policy = RetryPolicy(settings.retry, rng=rng)
|
|
39
|
+
|
|
40
|
+
async def send(
|
|
41
|
+
self,
|
|
42
|
+
spec: RequestSpec,
|
|
43
|
+
*,
|
|
44
|
+
timeout: httpx.Timeout,
|
|
45
|
+
extra_headers: Mapping[str, str],
|
|
46
|
+
retries: int | None = None,
|
|
47
|
+
) -> RawResponse:
|
|
48
|
+
"""Send ``spec``, retrying per the policy, and return the final raw response.
|
|
49
|
+
|
|
50
|
+
Raises:
|
|
51
|
+
FVSConnectionError: the service could not be reached (after retries).
|
|
52
|
+
FVSTimeoutError: the service did not answer in time.
|
|
53
|
+
"""
|
|
54
|
+
url, headers = request_headers(self._settings, spec, extra_headers)
|
|
55
|
+
attempt = 0
|
|
56
|
+
while True:
|
|
57
|
+
attempt += 1
|
|
58
|
+
start = self._clock()
|
|
59
|
+
raw: RawResponse | None = None
|
|
60
|
+
error: TransportError | None = None
|
|
61
|
+
try:
|
|
62
|
+
request = self._http.build_request(
|
|
63
|
+
spec.method,
|
|
64
|
+
url,
|
|
65
|
+
params=dict(spec.params) or None,
|
|
66
|
+
headers=headers,
|
|
67
|
+
timeout=timeout,
|
|
68
|
+
**request_kwargs(spec, asynchronous=True),
|
|
69
|
+
)
|
|
70
|
+
response = await self._http.send(request)
|
|
71
|
+
except httpx.TimeoutException as exc:
|
|
72
|
+
error = FVSTimeoutError(
|
|
73
|
+
f"{spec.method} {spec.path} timed out ({type(exc).__name__})"
|
|
74
|
+
)
|
|
75
|
+
error.__cause__ = exc
|
|
76
|
+
except httpx.TransportError as exc:
|
|
77
|
+
error = FVSConnectionError(
|
|
78
|
+
f"{spec.method} {spec.path} failed: {type(exc).__name__}: {exc}"
|
|
79
|
+
)
|
|
80
|
+
error.__cause__ = exc
|
|
81
|
+
else:
|
|
82
|
+
elapsed = self._clock() - start
|
|
83
|
+
pairs = response.headers.multi_items()
|
|
84
|
+
meta = build_meta(response.status_code, pairs, elapsed, attempt)
|
|
85
|
+
raw = build_raw(response.status_code, pairs, response.content, meta)
|
|
86
|
+
elapsed = self._clock() - start
|
|
87
|
+
log_attempt(
|
|
88
|
+
method=spec.method,
|
|
89
|
+
path=spec.path,
|
|
90
|
+
outcome=raw.status_code if raw is not None else type(error).__name__,
|
|
91
|
+
elapsed=elapsed,
|
|
92
|
+
request_id=raw.meta.request_id if raw is not None else None,
|
|
93
|
+
attempt=attempt,
|
|
94
|
+
)
|
|
95
|
+
delay = self._policy.decide(
|
|
96
|
+
attempt,
|
|
97
|
+
is_admin=spec.is_admin,
|
|
98
|
+
raw=raw,
|
|
99
|
+
exc=error,
|
|
100
|
+
override=retries,
|
|
101
|
+
retry_503=not (spec.report_on_503 and raw is not None and is_report(raw)),
|
|
102
|
+
)
|
|
103
|
+
if delay is None:
|
|
104
|
+
if raw is not None:
|
|
105
|
+
return raw
|
|
106
|
+
raise cast("TransportError", error)
|
|
107
|
+
log_retry(
|
|
108
|
+
method=spec.method,
|
|
109
|
+
path=spec.path,
|
|
110
|
+
attempt=attempt,
|
|
111
|
+
delay=delay,
|
|
112
|
+
reason=str(raw.status_code) if raw is not None else type(error).__name__,
|
|
113
|
+
)
|
|
114
|
+
await (self._sleep or anyio.sleep)(delay)
|
fvs_client/_bodies.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"""Request body sources (private)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import AsyncIterator, Iterator
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import IO
|
|
9
|
+
|
|
10
|
+
import anyio
|
|
11
|
+
|
|
12
|
+
CHUNK_SIZE = 64 * 1024
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True, slots=True)
|
|
16
|
+
class FileBody:
|
|
17
|
+
"""A request body streamed from a file; reopened for every attempt, so retries work."""
|
|
18
|
+
|
|
19
|
+
path: Path
|
|
20
|
+
chunk_size: int = CHUNK_SIZE
|
|
21
|
+
|
|
22
|
+
def iter_sync(self) -> Iterator[bytes]:
|
|
23
|
+
"""Yield the file in chunks."""
|
|
24
|
+
with self.path.open("rb") as fh:
|
|
25
|
+
while chunk := fh.read(self.chunk_size):
|
|
26
|
+
yield chunk
|
|
27
|
+
|
|
28
|
+
async def iter_async(self) -> AsyncIterator[bytes]:
|
|
29
|
+
"""Yield the file in chunks without blocking the event loop."""
|
|
30
|
+
async with await anyio.open_file(self.path, "rb") as fh:
|
|
31
|
+
while chunk := await fh.read(self.chunk_size):
|
|
32
|
+
yield chunk
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True, slots=True)
|
|
36
|
+
class MultipartFile:
|
|
37
|
+
"""One multipart file part, streamed from an open binary handle."""
|
|
38
|
+
|
|
39
|
+
field: str
|
|
40
|
+
filename: str
|
|
41
|
+
handle: IO[bytes]
|
|
42
|
+
content_type: str
|
fvs_client/_config.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""Client settings: environment resolution, secret handling, timeouts and default headers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import platform
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from fvs_client.errors import InputError
|
|
13
|
+
from fvs_client.models import RetryConfig
|
|
14
|
+
|
|
15
|
+
ENV_BASE_URL = "FVS_BASE_URL"
|
|
16
|
+
ENV_API_KEY = "FVS_API_KEY"
|
|
17
|
+
|
|
18
|
+
DEFAULT_TIMEOUT = httpx.Timeout(60.0, connect=10.0)
|
|
19
|
+
"""60 s overall per phase, 10 s to connect (research R11)."""
|
|
20
|
+
|
|
21
|
+
_MASK = "**********"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class SecretStr:
|
|
25
|
+
"""Holds the API key; ``repr``/``str`` never reveal it."""
|
|
26
|
+
|
|
27
|
+
__slots__ = ("_value",)
|
|
28
|
+
|
|
29
|
+
def __init__(self, value: str) -> None:
|
|
30
|
+
self._value = value
|
|
31
|
+
|
|
32
|
+
def get_secret_value(self) -> str:
|
|
33
|
+
"""Return the secret itself (only for building the ``Authorization`` header)."""
|
|
34
|
+
return self._value
|
|
35
|
+
|
|
36
|
+
def __repr__(self) -> str:
|
|
37
|
+
return repr(_MASK)
|
|
38
|
+
|
|
39
|
+
def __str__(self) -> str:
|
|
40
|
+
return _MASK
|
|
41
|
+
|
|
42
|
+
def __eq__(self, other: object) -> bool:
|
|
43
|
+
return isinstance(other, SecretStr) and other._value == self._value
|
|
44
|
+
|
|
45
|
+
def __hash__(self) -> int:
|
|
46
|
+
return hash(self._value)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def check_timeout(timeout: float | httpx.Timeout | None) -> httpx.Timeout:
|
|
50
|
+
"""Return a bounded ``httpx.Timeout`` (Constitution IV: no unbounded waits).
|
|
51
|
+
|
|
52
|
+
Raises:
|
|
53
|
+
InputError: ``timeout`` is ``None``, not positive, or an ``httpx.Timeout`` with any
|
|
54
|
+
``None`` (unbounded) phase.
|
|
55
|
+
"""
|
|
56
|
+
if timeout is None:
|
|
57
|
+
raise InputError("timeout must be set: None (wait forever) is not allowed")
|
|
58
|
+
if isinstance(timeout, httpx.Timeout):
|
|
59
|
+
phases = (timeout.connect, timeout.read, timeout.write, timeout.pool)
|
|
60
|
+
if any(p is None for p in phases):
|
|
61
|
+
raise InputError("timeout must bound every phase: connect, read, write and pool")
|
|
62
|
+
if any(p is not None and p <= 0 for p in phases):
|
|
63
|
+
raise InputError("timeout phases must be positive")
|
|
64
|
+
return timeout
|
|
65
|
+
if isinstance(timeout, bool) or not isinstance(timeout, int | float): # pyright: ignore[reportUnnecessaryIsInstance]
|
|
66
|
+
raise InputError("timeout must be a number of seconds or an httpx.Timeout")
|
|
67
|
+
if timeout <= 0:
|
|
68
|
+
raise InputError("timeout must be positive")
|
|
69
|
+
return httpx.Timeout(float(timeout))
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def check_extra_headers(headers: Mapping[str, str] | None) -> dict[str, str]:
|
|
73
|
+
"""Return ``headers`` as a dict, refusing ``Authorization`` (set it with ``api_key``).
|
|
74
|
+
|
|
75
|
+
Raises:
|
|
76
|
+
InputError: ``headers`` contains ``Authorization`` in any letter case.
|
|
77
|
+
"""
|
|
78
|
+
if not headers:
|
|
79
|
+
return {}
|
|
80
|
+
if any(k.lower() == "authorization" for k in headers):
|
|
81
|
+
raise InputError("The Authorization header cannot be set directly; pass api_key instead")
|
|
82
|
+
return dict(headers)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _version() -> str:
|
|
86
|
+
from fvs_client import __version__ # noqa: PLC0415 - package root imports this module
|
|
87
|
+
|
|
88
|
+
return __version__
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def build_user_agent(suffix: str | None) -> str:
|
|
92
|
+
"""Return ``fvs-client/<v> httpx/<v> python/<v>[ <suffix>]``."""
|
|
93
|
+
ua = f"fvs-client/{_version()} httpx/{httpx.__version__} python/{platform.python_version()}"
|
|
94
|
+
return f"{ua} {suffix}" if suffix else ua
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _check_base_url(value: str) -> str:
|
|
98
|
+
try:
|
|
99
|
+
url = httpx.URL(value.strip())
|
|
100
|
+
except (httpx.InvalidURL, TypeError) as exc:
|
|
101
|
+
raise InputError(f"base_url is not a valid URL: {value!r}") from exc
|
|
102
|
+
if url.scheme not in ("http", "https") or not url.host:
|
|
103
|
+
raise InputError(f"base_url must be an absolute http(s) URL, got {value!r}")
|
|
104
|
+
if url.query or url.fragment:
|
|
105
|
+
raise InputError("base_url must not contain a query or fragment")
|
|
106
|
+
return str(url.copy_with(path=url.path.rstrip("/") or "/")).rstrip("/")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass(frozen=True, slots=True)
|
|
110
|
+
class Settings:
|
|
111
|
+
"""Resolved, validated client settings."""
|
|
112
|
+
|
|
113
|
+
base_url: str
|
|
114
|
+
api_key: SecretStr | None
|
|
115
|
+
timeout: httpx.Timeout
|
|
116
|
+
headers: Mapping[str, str]
|
|
117
|
+
user_agent: str
|
|
118
|
+
retry: RetryConfig
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def resolve_settings(
|
|
122
|
+
*,
|
|
123
|
+
base_url: str | None = None,
|
|
124
|
+
api_key: str | None = None,
|
|
125
|
+
timeout: float | httpx.Timeout | None = DEFAULT_TIMEOUT,
|
|
126
|
+
headers: Mapping[str, str] | None = None,
|
|
127
|
+
user_agent_suffix: str | None = None,
|
|
128
|
+
retries: RetryConfig | int | None = None,
|
|
129
|
+
) -> Settings:
|
|
130
|
+
"""Resolve arguments and environment (``FVS_BASE_URL``, ``FVS_API_KEY``) into ``Settings``.
|
|
131
|
+
|
|
132
|
+
Raises:
|
|
133
|
+
InputError: no base URL anywhere, or any argument breaks its rules.
|
|
134
|
+
"""
|
|
135
|
+
url = base_url if base_url is not None else os.environ.get(ENV_BASE_URL)
|
|
136
|
+
if not url:
|
|
137
|
+
raise InputError(f"base_url is required: pass it or set the {ENV_BASE_URL} variable")
|
|
138
|
+
key = api_key if api_key is not None else os.environ.get(ENV_API_KEY)
|
|
139
|
+
if isinstance(retries, bool):
|
|
140
|
+
raise InputError("retries must be a RetryConfig or an int")
|
|
141
|
+
if retries is None:
|
|
142
|
+
retry = RetryConfig()
|
|
143
|
+
elif isinstance(retries, int):
|
|
144
|
+
retry = RetryConfig(max_retries=retries)
|
|
145
|
+
else:
|
|
146
|
+
retry = retries
|
|
147
|
+
return Settings(
|
|
148
|
+
base_url=_check_base_url(url),
|
|
149
|
+
api_key=SecretStr(key) if key else None,
|
|
150
|
+
timeout=check_timeout(timeout),
|
|
151
|
+
headers=check_extra_headers(headers),
|
|
152
|
+
user_agent=build_user_agent(user_agent_suffix),
|
|
153
|
+
retry=retry,
|
|
154
|
+
)
|
fvs_client/_headers.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Read-only, case-insensitive response headers (private)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable, Iterator, Mapping
|
|
6
|
+
from typing import cast
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Headers(Mapping[str, str]):
|
|
10
|
+
"""Read-only, case-insensitive header mapping (repeated headers joined with ``", "``)."""
|
|
11
|
+
|
|
12
|
+
__slots__ = ("_items",)
|
|
13
|
+
|
|
14
|
+
def __init__(self, items: Mapping[str, str] | Iterable[tuple[str, str]] = ()) -> None:
|
|
15
|
+
merged: dict[str, str] = {}
|
|
16
|
+
pairs: Iterable[tuple[str, str]] = (
|
|
17
|
+
cast("Mapping[str, str]", items).items() if isinstance(items, Mapping) else items
|
|
18
|
+
)
|
|
19
|
+
for key, value in pairs:
|
|
20
|
+
k = key.lower()
|
|
21
|
+
merged[k] = f"{merged[k]}, {value}" if k in merged else value
|
|
22
|
+
self._items = merged
|
|
23
|
+
|
|
24
|
+
def __getitem__(self, key: str) -> str:
|
|
25
|
+
return self._items[key.lower()]
|
|
26
|
+
|
|
27
|
+
def __contains__(self, key: object) -> bool:
|
|
28
|
+
return isinstance(key, str) and key.lower() in self._items
|
|
29
|
+
|
|
30
|
+
def __iter__(self) -> Iterator[str]:
|
|
31
|
+
return iter(self._items)
|
|
32
|
+
|
|
33
|
+
def __len__(self) -> int:
|
|
34
|
+
return len(self._items)
|
|
35
|
+
|
|
36
|
+
def __repr__(self) -> str:
|
|
37
|
+
return f"Headers({self._items!r})"
|
fvs_client/_inputs.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""Local input checks and resource preparation (nothing is sent when these fail)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import io
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
from collections.abc import Mapping, Sequence
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any, BinaryIO
|
|
13
|
+
from urllib.parse import urlsplit
|
|
14
|
+
|
|
15
|
+
import httpx
|
|
16
|
+
|
|
17
|
+
from fvs_client._bodies import FileBody
|
|
18
|
+
from fvs_client._config import check_extra_headers, check_timeout
|
|
19
|
+
from fvs_client.errors import InputError
|
|
20
|
+
from fvs_client.models import (
|
|
21
|
+
FhirVersion,
|
|
22
|
+
IgInput,
|
|
23
|
+
IgRef,
|
|
24
|
+
ResultFormat,
|
|
25
|
+
TerminologyMode,
|
|
26
|
+
ValidationOptions,
|
|
27
|
+
_render_ig, # pyright: ignore[reportPrivateUsage]
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
FHIR_JSON = "application/fhir+json"
|
|
31
|
+
FHIR_XML = "application/fhir+xml"
|
|
32
|
+
_SNIFF_BYTES = 1024
|
|
33
|
+
_BOM = b"\xef\xbb\xbf"
|
|
34
|
+
|
|
35
|
+
Resource = Mapping[str, Any] | str | bytes | os.PathLike[str]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def render_ig(ig: IgInput | None) -> str | None:
|
|
39
|
+
"""Render and check the ``ig`` value of a validation request (see ``ValidationOptions``)."""
|
|
40
|
+
return _render_ig(ig)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _sniff(head: bytes) -> str | None:
|
|
44
|
+
head = head.removeprefix(_BOM).lstrip()
|
|
45
|
+
if head.startswith(b"{"):
|
|
46
|
+
return FHIR_JSON
|
|
47
|
+
if head.startswith(b"<"):
|
|
48
|
+
return FHIR_XML
|
|
49
|
+
return None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _sniff_or_fail(head: bytes) -> str:
|
|
53
|
+
ctype = _sniff(head)
|
|
54
|
+
if ctype is None:
|
|
55
|
+
raise InputError(
|
|
56
|
+
"The resource is neither JSON (starting with '{') nor XML (starting with '<'); "
|
|
57
|
+
"pass content_type= to send it anyway"
|
|
58
|
+
)
|
|
59
|
+
return ctype
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _prepare_path(path: Path, content_type: str | None) -> tuple[FileBody, str]:
|
|
63
|
+
if not path.is_file():
|
|
64
|
+
raise InputError(f"{path} is not a readable file")
|
|
65
|
+
if content_type:
|
|
66
|
+
return FileBody(path), content_type
|
|
67
|
+
suffix = path.suffix.lower()
|
|
68
|
+
if suffix == ".json":
|
|
69
|
+
return FileBody(path), FHIR_JSON
|
|
70
|
+
if suffix == ".xml":
|
|
71
|
+
return FileBody(path), FHIR_XML
|
|
72
|
+
with path.open("rb") as fh:
|
|
73
|
+
head = fh.read(_SNIFF_BYTES)
|
|
74
|
+
return FileBody(path), _sniff_or_fail(head)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def prepare_resource(resource: Resource, content_type: str | None) -> tuple[bytes | FileBody, str]:
|
|
78
|
+
"""Return the request body and its ``Content-Type`` for ``resource``.
|
|
79
|
+
|
|
80
|
+
* ``dict`` → compact JSON, ``application/fhir+json``;
|
|
81
|
+
* ``str``/``bytes`` → sent as-is; JSON or XML is detected from the first character;
|
|
82
|
+
* path → streamed from disk; ``.json``/``.xml`` suffix decides, otherwise detected.
|
|
83
|
+
|
|
84
|
+
``content_type`` overrides the detection.
|
|
85
|
+
|
|
86
|
+
Raises:
|
|
87
|
+
InputError: unsupported type, unreadable file, or content that is neither JSON nor XML.
|
|
88
|
+
"""
|
|
89
|
+
if isinstance(resource, Mapping):
|
|
90
|
+
try:
|
|
91
|
+
body = json.dumps(dict(resource), separators=(",", ":"), ensure_ascii=False).encode()
|
|
92
|
+
except (TypeError, ValueError) as exc:
|
|
93
|
+
raise InputError(f"The resource cannot be encoded as JSON: {exc}") from exc
|
|
94
|
+
return body, content_type or FHIR_JSON
|
|
95
|
+
if isinstance(resource, str):
|
|
96
|
+
body = resource.encode("utf-8")
|
|
97
|
+
return body, content_type or _sniff_or_fail(body[:_SNIFF_BYTES])
|
|
98
|
+
if isinstance(resource, bytes | bytearray):
|
|
99
|
+
body = bytes(resource)
|
|
100
|
+
return body, content_type or _sniff_or_fail(body[:_SNIFF_BYTES])
|
|
101
|
+
if isinstance(resource, os.PathLike): # pyright: ignore[reportUnnecessaryIsInstance]
|
|
102
|
+
return _prepare_path(Path(os.fspath(resource)), content_type)
|
|
103
|
+
raise InputError(
|
|
104
|
+
f"Unsupported resource type {type(resource).__name__}: pass a dict, str, bytes or path"
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def resolve_validation_options(
|
|
109
|
+
options: ValidationOptions | None,
|
|
110
|
+
*,
|
|
111
|
+
ig: IgInput | None,
|
|
112
|
+
profiles: Sequence[str],
|
|
113
|
+
tx: str | None,
|
|
114
|
+
tx_mode: TerminologyMode | str | None,
|
|
115
|
+
result_format: ResultFormat | str,
|
|
116
|
+
content_type: str | None,
|
|
117
|
+
) -> ValidationOptions:
|
|
118
|
+
"""Return ``options``, or build them from the keyword arguments (never both).
|
|
119
|
+
|
|
120
|
+
Raises:
|
|
121
|
+
InputError: ``options`` given together with keyword options, or any rule broken.
|
|
122
|
+
"""
|
|
123
|
+
keywords_used = (
|
|
124
|
+
ig is not None
|
|
125
|
+
or bool(tuple(profiles) if not isinstance(profiles, str) else profiles)
|
|
126
|
+
or tx is not None
|
|
127
|
+
or tx_mode is not None
|
|
128
|
+
or result_format != ResultFormat.SUMMARY
|
|
129
|
+
or content_type is not None
|
|
130
|
+
)
|
|
131
|
+
if options is not None:
|
|
132
|
+
if keywords_used:
|
|
133
|
+
raise InputError("Pass either options= or keyword options (ig, profiles, …), not both")
|
|
134
|
+
return options
|
|
135
|
+
return ValidationOptions(
|
|
136
|
+
ig=ig,
|
|
137
|
+
profiles=profiles,
|
|
138
|
+
tx=tx,
|
|
139
|
+
tx_mode=tx_mode,
|
|
140
|
+
result_format=result_format,
|
|
141
|
+
content_type=content_type,
|
|
142
|
+
)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@dataclass(frozen=True, slots=True)
|
|
146
|
+
class Batch:
|
|
147
|
+
"""Checked settings shared by every resource of ``validate_many``."""
|
|
148
|
+
|
|
149
|
+
fhir_version: FhirVersion
|
|
150
|
+
options: ValidationOptions
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def prepare_batch(
|
|
154
|
+
concurrency: int,
|
|
155
|
+
fhir_version: FhirVersion | str,
|
|
156
|
+
options: ValidationOptions | None,
|
|
157
|
+
*,
|
|
158
|
+
ig: IgInput | None,
|
|
159
|
+
profiles: Sequence[str],
|
|
160
|
+
tx: str | None,
|
|
161
|
+
tx_mode: TerminologyMode | str | None,
|
|
162
|
+
result_format: ResultFormat | str,
|
|
163
|
+
content_type: str | None,
|
|
164
|
+
timeout: float | httpx.Timeout | None,
|
|
165
|
+
extra_headers: Mapping[str, str] | None,
|
|
166
|
+
) -> Batch:
|
|
167
|
+
"""Check everything shared by a batch once, before anything is sent.
|
|
168
|
+
|
|
169
|
+
Raises:
|
|
170
|
+
InputError: ``concurrency`` < 1, or invalid shared options.
|
|
171
|
+
"""
|
|
172
|
+
if isinstance(concurrency, bool) or concurrency < 1:
|
|
173
|
+
raise InputError("concurrency must be at least 1")
|
|
174
|
+
if timeout is not None:
|
|
175
|
+
check_timeout(timeout)
|
|
176
|
+
check_extra_headers(extra_headers)
|
|
177
|
+
opts = resolve_validation_options(
|
|
178
|
+
options,
|
|
179
|
+
ig=ig,
|
|
180
|
+
profiles=profiles,
|
|
181
|
+
tx=tx,
|
|
182
|
+
tx_mode=tx_mode,
|
|
183
|
+
result_format=result_format,
|
|
184
|
+
content_type=content_type,
|
|
185
|
+
)
|
|
186
|
+
return Batch(fhir_version=FhirVersion.parse(fhir_version), options=opts)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
# --------------------------------------------------------------------------- administration
|
|
190
|
+
|
|
191
|
+
_SERIES_RE = re.compile(r"^\d+\.[xX](\.[xX])?$|^\d+\.\d+\.[xX]$")
|
|
192
|
+
_MAX_REGISTER_VERSION = 64
|
|
193
|
+
_MAX_IG_KEY = 256
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _check_series(ref: IgRef) -> IgRef:
|
|
197
|
+
if ref.is_series and ref.version is not None and not _SERIES_RE.fullmatch(ref.version):
|
|
198
|
+
raise InputError(
|
|
199
|
+
f"Version {ref.version!r} is not a valid series: use N.x, N.x.x or N.N.x (e.g. 1.2.x)"
|
|
200
|
+
)
|
|
201
|
+
return ref
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _refs(ig: IgInput) -> tuple[IgRef, ...]:
|
|
205
|
+
if isinstance(ig, IgRef):
|
|
206
|
+
return (ig,)
|
|
207
|
+
if isinstance(ig, tuple):
|
|
208
|
+
return ig
|
|
209
|
+
if not ig.strip():
|
|
210
|
+
raise InputError("ig must not be empty")
|
|
211
|
+
return tuple(IgRef.parse(p) for p in ig.split("|"))
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def check_include_ig(ig: IgInput) -> tuple[IgRef, ...]:
|
|
215
|
+
"""IGs of ``contexts.include``: one or two; version exact, ``latest``, ``None`` or a series.
|
|
216
|
+
|
|
217
|
+
Raises:
|
|
218
|
+
InputError: more than two IGs, the same package twice, or an invalid series.
|
|
219
|
+
"""
|
|
220
|
+
refs = _refs(ig)
|
|
221
|
+
if len(refs) not in (1, 2):
|
|
222
|
+
raise InputError("include takes one IG, or exactly two for a two-IG context")
|
|
223
|
+
if len(refs) == 2 and refs[0].name == refs[1].name:
|
|
224
|
+
raise InputError("The two IGs of a two-IG context must be different packages")
|
|
225
|
+
return tuple(_check_series(r) for r in refs)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def check_exact_ig(ig: IgInput) -> str:
|
|
229
|
+
"""The ``ig`` of ``contexts.exclude``/``update``: exact ``name#version`` or a two-IG key.
|
|
230
|
+
|
|
231
|
+
Raises:
|
|
232
|
+
InputError: no version, ``latest``, a series, or longer than 256 characters.
|
|
233
|
+
"""
|
|
234
|
+
refs = _refs(ig)
|
|
235
|
+
if len(refs) not in (1, 2) or not all(r.is_exact for r in refs):
|
|
236
|
+
raise InputError(
|
|
237
|
+
"ig must be an exact name#version (or name#version|name#version); "
|
|
238
|
+
"'latest' and version series are not allowed here"
|
|
239
|
+
)
|
|
240
|
+
rendered = "|".join(str(r) for r in refs)
|
|
241
|
+
if len(rendered) > _MAX_IG_KEY:
|
|
242
|
+
raise InputError(f"ig must be at most {_MAX_IG_KEY} characters")
|
|
243
|
+
return rendered
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def check_register_args(name: str | None, version: str, download_url: str | None) -> None:
|
|
247
|
+
"""Rules of ``packages.register``.
|
|
248
|
+
|
|
249
|
+
Raises:
|
|
250
|
+
InputError: not exactly one of ``name``/``download_url``, a version over 64 characters
|
|
251
|
+
or an invalid series, or a ``download_url`` that is not an http(s) URL.
|
|
252
|
+
"""
|
|
253
|
+
if (name is None) == (download_url is None):
|
|
254
|
+
raise InputError("register needs exactly one of name or download_url")
|
|
255
|
+
if len(version) > _MAX_REGISTER_VERSION:
|
|
256
|
+
raise InputError(f"version must be at most {_MAX_REGISTER_VERSION} characters")
|
|
257
|
+
if name is not None:
|
|
258
|
+
_check_series(IgRef(name, version))
|
|
259
|
+
if download_url is not None:
|
|
260
|
+
parts = urlsplit(download_url)
|
|
261
|
+
if parts.scheme not in ("http", "https") or not parts.hostname:
|
|
262
|
+
raise InputError("download_url must be an absolute http(s) URL")
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def prepare_archive(archive: os.PathLike[str] | BinaryIO) -> tuple[str, BinaryIO, bool]:
|
|
266
|
+
"""Return ``(filename, binary handle, should_close)`` for streaming an IG archive.
|
|
267
|
+
|
|
268
|
+
Raises:
|
|
269
|
+
InputError: the file does not exist, or ``archive`` is a text-mode handle.
|
|
270
|
+
"""
|
|
271
|
+
if isinstance(archive, os.PathLike):
|
|
272
|
+
path = Path(os.fspath(archive))
|
|
273
|
+
if not path.is_file():
|
|
274
|
+
raise InputError(f"{path} is not a readable file")
|
|
275
|
+
return path.name, path.open("rb"), True
|
|
276
|
+
mode = getattr(archive, "mode", "rb")
|
|
277
|
+
if isinstance(archive, io.TextIOBase) or (isinstance(mode, str) and "b" not in mode):
|
|
278
|
+
raise InputError("archive must be a path or a file opened in binary mode ('rb')")
|
|
279
|
+
name = getattr(archive, "name", None)
|
|
280
|
+
filename = Path(name).name if isinstance(name, str) and name else "package.tgz"
|
|
281
|
+
return filename, archive, False
|
fvs_client/_logging.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""The ``fvs_client`` logger.
|
|
2
|
+
|
|
3
|
+
Silent by default (``NullHandler``). Records never contain headers, bodies, query values or the
|
|
4
|
+
API key: only method, path, status, timing, request id and attempt number.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger("fvs_client")
|
|
13
|
+
logger.addHandler(logging.NullHandler())
|
|
14
|
+
|
|
15
|
+
_MASK = "**********"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def redact_headers(headers: Mapping[str, str]) -> dict[str, str]:
|
|
19
|
+
"""Return a copy of ``headers`` with the ``Authorization`` value masked."""
|
|
20
|
+
return {k: (_MASK if k.lower() == "authorization" else v) for k, v in headers.items()}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def log_attempt(
|
|
24
|
+
*,
|
|
25
|
+
method: str,
|
|
26
|
+
path: str,
|
|
27
|
+
outcome: int | str,
|
|
28
|
+
elapsed: float,
|
|
29
|
+
request_id: str | None,
|
|
30
|
+
attempt: int,
|
|
31
|
+
) -> None:
|
|
32
|
+
"""Log one HTTP attempt at DEBUG (``outcome`` is the status or an exception class name)."""
|
|
33
|
+
if logger.isEnabledFor(logging.DEBUG):
|
|
34
|
+
logger.debug(
|
|
35
|
+
"%s %s -> %s in %.1f ms (request id %s, attempt %d)",
|
|
36
|
+
method,
|
|
37
|
+
path,
|
|
38
|
+
outcome,
|
|
39
|
+
elapsed * 1000.0,
|
|
40
|
+
request_id or "-",
|
|
41
|
+
attempt,
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def log_retry(*, method: str, path: str, attempt: int, delay: float, reason: str) -> None:
|
|
46
|
+
"""Log a retry decision at INFO."""
|
|
47
|
+
logger.info(
|
|
48
|
+
"%s %s: retrying after %.2f s (attempt %d failed: %s)", method, path, delay, attempt, reason
|
|
49
|
+
)
|