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/_parsing.py ADDED
@@ -0,0 +1,471 @@
1
+ """Sans-I/O response handling: metadata, raw responses and result parsers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime as _dt
6
+ import enum
7
+ from collections.abc import Callable, Iterable, Mapping
8
+ from typing import Any, TypeVar
9
+
10
+ from fvs_client._headers import Headers
11
+ from fvs_client._problems import as_list, error_for, media_type, parse_issue
12
+ from fvs_client.errors import InputError, ServerError
13
+ from fvs_client.models import (
14
+ AllowlistSource,
15
+ AllowlistState,
16
+ ContextAccessResult,
17
+ DatabaseHealth,
18
+ ExcludeResult,
19
+ FhirVersion,
20
+ HealthReport,
21
+ HealthStatus,
22
+ IgPackageResult,
23
+ InactiveContext,
24
+ InactiveContexts,
25
+ IncludedIg,
26
+ IncludeResult,
27
+ LivenessReport,
28
+ OperationOutcomeResult,
29
+ PackageAccessResult,
30
+ PackageDependencies,
31
+ PackageFiles,
32
+ RateLimitInfo,
33
+ RawResponse,
34
+ ReadinessReport,
35
+ ResponseMeta,
36
+ ResultFormat,
37
+ TerminologyMode,
38
+ TerminologySettings,
39
+ TxSource,
40
+ ValidationContextInfo,
41
+ ValidationResult,
42
+ )
43
+
44
+ T = TypeVar("T")
45
+ E = TypeVar("E", bound=enum.Enum)
46
+
47
+ HeaderInput = Mapping[str, str] | Iterable[tuple[str, str]]
48
+
49
+
50
+ def coerce_enum(cls: type[E], value: Any) -> E | str | None:
51
+ """Return ``cls(value)``, the value as ``str`` if the enum doesn't know it, or ``None``."""
52
+ if value is None:
53
+ return None
54
+ try:
55
+ return cls(value)
56
+ except ValueError:
57
+ return str(value)
58
+
59
+
60
+ def _int_header(headers: Mapping[str, str], name: str) -> int | None:
61
+ value = headers.get(name)
62
+ if value is None:
63
+ return None
64
+ try:
65
+ return int(value.strip())
66
+ except ValueError:
67
+ return None
68
+
69
+
70
+ def build_meta(status: int, headers: HeaderInput, elapsed: float, attempts: int) -> ResponseMeta:
71
+ """Build ``ResponseMeta`` from the final attempt's status and headers."""
72
+ h = headers if isinstance(headers, Headers) else Headers(headers)
73
+ return ResponseMeta(
74
+ status_code=status,
75
+ request_id=h.get("x-request-id"),
76
+ rate_limit=RateLimitInfo(
77
+ limit=_int_header(h, "ratelimit-limit"),
78
+ remaining=_int_header(h, "ratelimit-remaining"),
79
+ reset_seconds=_int_header(h, "ratelimit-reset"),
80
+ retry_after_seconds=_int_header(h, "retry-after"),
81
+ ),
82
+ elapsed_seconds=elapsed,
83
+ attempts=attempts,
84
+ )
85
+
86
+
87
+ def build_raw(status: int, headers: HeaderInput, content: bytes, meta: ResponseMeta) -> RawResponse:
88
+ """Build the immutable ``RawResponse``."""
89
+ h = headers if isinstance(headers, Headers) else Headers(headers)
90
+ return RawResponse(status_code=status, headers=h, content=content, meta=meta)
91
+
92
+
93
+ def decode_json(raw: RawResponse) -> Any:
94
+ """Decode the body as JSON, or raise the typed error for an unexpected body."""
95
+ try:
96
+ return raw.json()
97
+ except ValueError:
98
+ # A 2xx whose body isn't JSON is an unexpected shape → ServerError.
99
+ raise ServerError(raw) from None
100
+
101
+
102
+ def json_object(raw: RawResponse) -> dict[str, Any]:
103
+ """Decode the body as a JSON object, or raise ``ServerError``."""
104
+ data = decode_json(raw)
105
+ if not isinstance(data, dict):
106
+ raise ServerError(raw)
107
+ return data # pyright: ignore[reportUnknownVariableType]
108
+
109
+
110
+ def finalize(
111
+ raw: RawResponse,
112
+ parser: Callable[[RawResponse], T],
113
+ *,
114
+ want_raw: bool,
115
+ report_on_503: bool = False,
116
+ ) -> T | RawResponse:
117
+ """Turn a raw response into the caller's result.
118
+
119
+ * error status → raise the typed ``APIError`` (also in raw mode);
120
+ * ``want_raw`` → return ``raw`` unparsed;
121
+ * otherwise → ``parser(raw)``.
122
+ """
123
+ ok = 200 <= raw.status_code < 300
124
+ if not ok and report_on_503 and raw.status_code == 503 and is_report(raw):
125
+ ok = True
126
+ if not ok:
127
+ raise error_for(raw)
128
+ if want_raw:
129
+ return raw
130
+ return parser(raw)
131
+
132
+
133
+ def is_report(raw: RawResponse) -> bool:
134
+ """True for a 503 health/readiness report body (JSON object, not a problem document)."""
135
+ if media_type(raw.headers) == "application/problem+json" or not raw.content:
136
+ return False
137
+ try:
138
+ return isinstance(raw.json(), dict)
139
+ except ValueError:
140
+ return False
141
+
142
+
143
+ # --------------------------------------------------------------------------- validation
144
+
145
+
146
+ def _opt_str(value: Any) -> str | None:
147
+ return value if isinstance(value, str) else None
148
+
149
+
150
+ def _opt_bool(value: Any) -> bool | None:
151
+ return value if isinstance(value, bool) else None
152
+
153
+
154
+ def _header_bool(value: str | None) -> bool | None:
155
+ if value is None:
156
+ return None
157
+ lowered = value.strip().lower()
158
+ if lowered in ("true", "false"):
159
+ return lowered == "true"
160
+ return None
161
+
162
+
163
+ def build_context_info(headers: HeaderInput) -> ValidationContextInfo:
164
+ """Read the ``X-Validation-Context*`` and ``X-Tx-*`` headers."""
165
+ h = headers if isinstance(headers, Headers) else Headers(headers)
166
+ return ValidationContextInfo(
167
+ key=h.get("x-validation-context", ""),
168
+ owner=h.get("x-validation-context-owner"),
169
+ shareable=_header_bool(h.get("x-validation-context-shareable")),
170
+ tx_mode=coerce_enum(TerminologyMode, h.get("x-tx-mode")),
171
+ tx_server=h.get("x-tx-server"),
172
+ tx_source=coerce_enum(TxSource, h.get("x-tx-source")),
173
+ )
174
+
175
+
176
+ def parse_validation(raw: RawResponse) -> ValidationResult:
177
+ """Parse a ``ValidationResponse`` body (``Accept: application/json``)."""
178
+ data = json_object(raw)
179
+ issues = tuple(
180
+ i for i in (parse_issue(m) for m in as_list(data.get("messages"))) if i is not None
181
+ )
182
+ return ValidationResult(
183
+ valid=data.get("valid") is True,
184
+ issues=issues,
185
+ fhir_version=coerce_enum(FhirVersion, data.get("fhirVersion")),
186
+ applied_profiles=tuple(str(p) for p in as_list(data.get("appliedProfiles"))),
187
+ ig_package=_opt_str(data.get("igPackage")),
188
+ ig_owner=_opt_str(data.get("igOwner")),
189
+ ig_shareable=_opt_bool(data.get("igShareable")),
190
+ context=build_context_info(raw.headers),
191
+ meta=raw.meta,
192
+ raw=data,
193
+ )
194
+
195
+
196
+ def parse_operation_outcome(raw: RawResponse, fmt: ResultFormat) -> OperationOutcomeResult:
197
+ """Parse an OperationOutcome body (JSON → dict, XML → str)."""
198
+ body: dict[str, Any] | str = (
199
+ raw.text if fmt is ResultFormat.OPERATION_OUTCOME_XML else json_object(raw)
200
+ )
201
+ return OperationOutcomeResult(
202
+ format=fmt,
203
+ body=body,
204
+ context=build_context_info(raw.headers),
205
+ meta=raw.meta,
206
+ raw=body,
207
+ )
208
+
209
+
210
+ def validation_parser(
211
+ fmt: ResultFormat,
212
+ ) -> Callable[[RawResponse], ValidationResult | OperationOutcomeResult]:
213
+ """The parser for a validation response in ``fmt``."""
214
+ if fmt is ResultFormat.SUMMARY:
215
+ return parse_validation
216
+
217
+ def parse(raw: RawResponse) -> OperationOutcomeResult:
218
+ return parse_operation_outcome(raw, fmt)
219
+
220
+ return parse
221
+
222
+
223
+ # --------------------------------------------------------------------------- administration
224
+
225
+
226
+ def _opt_int(value: Any) -> int | None:
227
+ return value if isinstance(value, int) and not isinstance(value, bool) else None
228
+
229
+
230
+ def _strs(value: Any) -> tuple[str, ...]:
231
+ return tuple(str(v) for v in as_list(value))
232
+
233
+
234
+ def _terminology(value: Any) -> TerminologySettings | None:
235
+ """Parse a ``TerminologySettings`` object leniently (never raises on odd server data)."""
236
+ if not isinstance(value, dict):
237
+ return None
238
+ mode = _opt_str(value.get("mode")) # pyright: ignore[reportUnknownMemberType]
239
+ server = _opt_str(value.get("server")) # pyright: ignore[reportUnknownMemberType]
240
+ if mode is None:
241
+ return None
242
+ try:
243
+ return TerminologySettings(mode=mode, server=server)
244
+ except InputError:
245
+ settings = object.__new__(TerminologySettings)
246
+ object.__setattr__(settings, "mode", coerce_enum(TerminologyMode, mode))
247
+ object.__setattr__(settings, "server", server)
248
+ return settings
249
+
250
+
251
+ def _included_ig(value: Any) -> IncludedIg | None:
252
+ if not isinstance(value, dict):
253
+ return None
254
+ item: dict[str, Any] = value # pyright: ignore[reportUnknownVariableType]
255
+ return IncludedIg(
256
+ ig_package_id=str(item.get("igPackageId", "")),
257
+ ig_package_version=str(item.get("igPackageVersion", "")),
258
+ requested_version=_opt_str(item.get("requestedVersion")),
259
+ )
260
+
261
+
262
+ def parse_include(raw: RawResponse) -> IncludeResult:
263
+ """Parse an ``IncludeResponse``."""
264
+ data = json_object(raw)
265
+ key = data.get("key")
266
+ key_value = _opt_str(key.get("igPackage")) if isinstance(key, dict) else None # pyright: ignore[reportUnknownMemberType]
267
+ return IncludeResult(
268
+ fhir_version=_opt_str(data.get("fhirVersion")),
269
+ key=key_value or "",
270
+ ig_packages=tuple(
271
+ i for i in (_included_ig(x) for x in as_list(data.get("igPackages"))) if i is not None
272
+ ),
273
+ aliases=_strs(data.get("aliases")),
274
+ requested_version=_opt_str(data.get("requestedVersion")),
275
+ revision=_opt_int(data.get("revision")),
276
+ included=_strs(data.get("included")),
277
+ resolved=_strs(data.get("resolved")),
278
+ terminology=_terminology(data.get("terminology")),
279
+ owner=_opt_str(data.get("owner")),
280
+ shareable=_opt_bool(data.get("shareable")),
281
+ warnings=_strs(data.get("warnings")),
282
+ meta=raw.meta,
283
+ raw=data,
284
+ )
285
+
286
+
287
+ def parse_exclude(raw: RawResponse) -> ExcludeResult:
288
+ """Parse an ``ExcludeResponse``."""
289
+ data = json_object(raw)
290
+ return ExcludeResult(
291
+ fhir_version=_opt_str(data.get("fhirVersion")),
292
+ revision=_opt_int(data.get("revision")),
293
+ excluded=_opt_str(data.get("excluded")),
294
+ included=_strs(data.get("included")),
295
+ warnings=_strs(data.get("warnings")),
296
+ meta=raw.meta,
297
+ raw=data,
298
+ )
299
+
300
+
301
+ def parse_context_access(raw: RawResponse) -> ContextAccessResult:
302
+ """Parse an ``IncludeAccessResponse``."""
303
+ data = json_object(raw)
304
+ return ContextAccessResult(
305
+ fhir_version=_opt_str(data.get("fhirVersion")),
306
+ ig_package=_opt_str(data.get("igPackage")),
307
+ revision=_opt_int(data.get("revision")),
308
+ owner=_opt_str(data.get("owner")),
309
+ shareable=_opt_bool(data.get("shareable")),
310
+ terminology=_terminology(data.get("terminology")),
311
+ warnings=_strs(data.get("warnings")),
312
+ meta=raw.meta,
313
+ raw=data,
314
+ )
315
+
316
+
317
+ def parse_ig_package(raw: RawResponse) -> IgPackageResult:
318
+ """Parse an ``IgRegistrationResponse`` (upload and register)."""
319
+ data = json_object(raw)
320
+ return IgPackageResult(
321
+ name=_opt_str(data.get("name")),
322
+ version=_opt_str(data.get("version")),
323
+ requested_version=_opt_str(data.get("requestedVersion")),
324
+ downloaded=_opt_bool(data.get("downloaded")),
325
+ owner=_opt_str(data.get("owner")),
326
+ shareable=_opt_bool(data.get("shareable")),
327
+ warnings=_strs(data.get("warnings")),
328
+ meta=raw.meta,
329
+ raw=data,
330
+ )
331
+
332
+
333
+ def parse_package_access(raw: RawResponse) -> PackageAccessResult:
334
+ """Parse an ``IgAccessResponse``."""
335
+ data = json_object(raw)
336
+ return PackageAccessResult(
337
+ name=_opt_str(data.get("name")),
338
+ version=_opt_str(data.get("version")),
339
+ owner=_opt_str(data.get("owner")),
340
+ shareable=_opt_bool(data.get("shareable")),
341
+ warnings=_strs(data.get("warnings")),
342
+ meta=raw.meta,
343
+ raw=data,
344
+ )
345
+
346
+
347
+ def parse_dependencies(raw: RawResponse) -> PackageDependencies:
348
+ """Parse the dependencies graph response."""
349
+ data = json_object(raw)
350
+ return PackageDependencies(
351
+ name=_opt_str(data.get("name")),
352
+ version=_opt_str(data.get("version")),
353
+ dependencies=_strs(data.get("dependencies")),
354
+ meta=raw.meta,
355
+ raw=data,
356
+ )
357
+
358
+
359
+ def parse_files(raw: RawResponse) -> PackageFiles:
360
+ """Parse the (deprecated) package file listing."""
361
+ data = json_object(raw)
362
+ return PackageFiles(
363
+ name=_opt_str(data.get("name")),
364
+ version=_opt_str(data.get("version")),
365
+ files=_strs(data.get("files")),
366
+ meta=raw.meta,
367
+ raw=data,
368
+ )
369
+
370
+
371
+ # --------------------------------------------------------------------------- health
372
+
373
+
374
+ def _timestamp(value: Any) -> _dt.datetime | None:
375
+ millis = _opt_int(value)
376
+ return None if millis is None else _dt.datetime.fromtimestamp(millis / 1000, tz=_dt.UTC)
377
+
378
+
379
+ def _obj(value: Any) -> dict[str, Any]:
380
+ return value if isinstance(value, dict) else {} # pyright: ignore[reportUnknownVariableType]
381
+
382
+
383
+ def parse_liveness(raw: RawResponse) -> LivenessReport:
384
+ """Parse ``GET /health/liveness``."""
385
+ data = json_object(raw)
386
+ return LivenessReport(
387
+ status=coerce_enum(HealthStatus, data.get("status")),
388
+ timestamp=_timestamp(data.get("timestamp")),
389
+ meta=raw.meta,
390
+ raw=data,
391
+ )
392
+
393
+
394
+ def _readiness(data: dict[str, Any], raw: RawResponse) -> ReadinessReport:
395
+ versions = {str(k): _obj(v) for k, v in _obj(data.get("versions")).items()}
396
+ return ReadinessReport(
397
+ status=coerce_enum(HealthStatus, data.get("status")),
398
+ timestamp=_timestamp(data.get("timestamp")),
399
+ catalog_revision=_opt_int(data.get("catalogRevision")),
400
+ reasons=_strs(data.get("reasons")),
401
+ versions=versions,
402
+ meta=raw.meta,
403
+ raw=data,
404
+ )
405
+
406
+
407
+ def parse_readiness(raw: RawResponse) -> ReadinessReport:
408
+ """Parse ``GET /health/readiness`` (200 or 503 with a report)."""
409
+ return _readiness(json_object(raw), raw)
410
+
411
+
412
+ def _inactive(value: Any) -> InactiveContexts:
413
+ data = _obj(value)
414
+ items = tuple(
415
+ InactiveContext(
416
+ fhir_version=_opt_str(item.get("fhirVersion")),
417
+ ig_package=_opt_str(item.get("igPackage")),
418
+ ig_packages=_strs(item.get("igPackages")),
419
+ aliases=_strs(item.get("aliases")),
420
+ owner=_opt_str(item.get("owner")),
421
+ reason=_opt_str(item.get("reason")),
422
+ )
423
+ for item in (_obj(x) for x in as_list(data.get("items")))
424
+ )
425
+ return InactiveContexts(
426
+ count=_opt_int(data.get("count")) or 0,
427
+ private=_opt_int(data.get("private")) or 0,
428
+ items=items,
429
+ )
430
+
431
+
432
+ def _allowlist(value: Any) -> dict[str, AllowlistState]:
433
+ return {
434
+ str(version): AllowlistState(
435
+ source=coerce_enum(AllowlistSource, state.get("source")),
436
+ fetched_at=_opt_str(state.get("fetchedAt")),
437
+ registry_last_update=_opt_str(state.get("registryLastUpdate")),
438
+ servers=_opt_int(state.get("servers")),
439
+ reason=_opt_str(state.get("reason")),
440
+ )
441
+ for version, state in ((k, _obj(v)) for k, v in _obj(value).items())
442
+ }
443
+
444
+
445
+ def parse_health(raw: RawResponse) -> HealthReport:
446
+ """Parse ``GET /health`` (200 or 503 with a report)."""
447
+ data = json_object(raw)
448
+ postgres = _obj(data.get("postgres"))
449
+ readiness = data.get("readiness")
450
+ acl = _opt_str(_obj(data.get("security")).get("aclSecurity"))
451
+ fhir_versions = _obj(data.get("fhirVersions"))
452
+ return HealthReport(
453
+ status=coerce_enum(HealthStatus, data.get("status")),
454
+ timestamp=_timestamp(data.get("timestamp")),
455
+ database=DatabaseHealth(
456
+ status=coerce_enum(HealthStatus, postgres.get("status")),
457
+ response_time_ms=_opt_int(postgres.get("responseTime")),
458
+ error=_opt_str(postgres.get("error")),
459
+ ),
460
+ readiness=_readiness(_obj(readiness), raw) if isinstance(readiness, dict) else None,
461
+ served_fhir_versions=tuple(
462
+ v
463
+ for v in (coerce_enum(FhirVersion, x) for x in as_list(fhir_versions.get("served")))
464
+ if v is not None
465
+ ),
466
+ inactive_contexts=_inactive(fhir_versions.get("inactiveContexts")),
467
+ terminology_allowlist=_allowlist(_obj(data.get("terminology")).get("allowlist")),
468
+ acl_enabled=None if acl is None else acl == "enabled",
469
+ meta=raw.meta,
470
+ raw=data,
471
+ )
@@ -0,0 +1,183 @@
1
+ """RFC 9457 problem parsing and HTTP status → SDK error mapping."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Mapping
7
+ from typing import Any, TypeVar, cast
8
+
9
+ from fvs_client._headers import Headers
10
+ from fvs_client.errors import (
11
+ APIError,
12
+ AuthenticationError,
13
+ BadRequestError,
14
+ ConflictError,
15
+ DependencyConflictError,
16
+ InvalidResourceError,
17
+ NotFoundError,
18
+ PermissionDeniedError,
19
+ RateLimitError,
20
+ ServerError,
21
+ ServiceUnavailableError,
22
+ UnknownProfileError,
23
+ )
24
+ from fvs_client.models import (
25
+ Problem,
26
+ ProblemType,
27
+ RateLimitScope,
28
+ RawResponse,
29
+ Severity,
30
+ ValidationIssue,
31
+ _problem_short_name, # pyright: ignore[reportPrivateUsage]
32
+ )
33
+
34
+ _KNOWN_MEMBERS = frozenset(
35
+ {
36
+ "type",
37
+ "title",
38
+ "status",
39
+ "detail",
40
+ "correlationId",
41
+ "issues",
42
+ "unresolvedProfiles",
43
+ "conflicts",
44
+ "scope",
45
+ "limit",
46
+ "retryAfterSeconds",
47
+ }
48
+ )
49
+
50
+ _STATUS_CLASS: dict[int, type[APIError]] = {
51
+ 400: BadRequestError,
52
+ 401: AuthenticationError,
53
+ 403: PermissionDeniedError,
54
+ 404: NotFoundError,
55
+ 405: BadRequestError,
56
+ 406: BadRequestError,
57
+ 409: ConflictError,
58
+ 413: BadRequestError,
59
+ 415: BadRequestError,
60
+ 422: BadRequestError,
61
+ 424: BadRequestError,
62
+ 429: RateLimitError,
63
+ 503: ServiceUnavailableError,
64
+ }
65
+
66
+ _REFINE_400: dict[ProblemType, type[APIError]] = {
67
+ ProblemType.INVALID_RESOURCE: InvalidResourceError,
68
+ ProblemType.UNKNOWN_PROFILE: UnknownProfileError,
69
+ ProblemType.DEPENDENCY_CONFLICT: DependencyConflictError,
70
+ }
71
+
72
+
73
+ def short_name(type_uri: str) -> str:
74
+ """Return the problem short name: the last non-empty path segment of ``type_uri``."""
75
+ return _problem_short_name(type_uri)
76
+
77
+
78
+ def media_type(headers: Mapping[str, str]) -> str:
79
+ """Return the lower-cased media type of ``Content-Type`` without parameters."""
80
+ value = Headers(headers).get("content-type", "")
81
+ return value.split(";", 1)[0].strip().lower()
82
+
83
+
84
+ def _int_or_none(value: Any) -> int | None:
85
+ return value if isinstance(value, int) and not isinstance(value, bool) else None
86
+
87
+
88
+ def _str_or_none(value: Any) -> str | None:
89
+ return value if isinstance(value, str) else None
90
+
91
+
92
+ _E = TypeVar("_E", RateLimitScope, Severity)
93
+
94
+
95
+ def _enum_or_str(cls: type[_E], value: Any) -> _E | str | None:
96
+ if not isinstance(value, str):
97
+ return None
98
+ try:
99
+ return cls(value)
100
+ except ValueError:
101
+ return value
102
+
103
+
104
+ def as_list(value: Any) -> list[Any]:
105
+ """Return ``value`` if it is a JSON array, else an empty list."""
106
+ if isinstance(value, list):
107
+ return value # pyright: ignore[reportUnknownVariableType]
108
+ return []
109
+
110
+
111
+ def parse_issue(item: Any) -> ValidationIssue | None:
112
+ """Parse one ``ValidationMessage`` object; ``None`` if it is not an object."""
113
+ if not isinstance(item, dict):
114
+ return None
115
+ data = cast("dict[str, Any]", item)
116
+ severity = _enum_or_str(Severity, data.get("severity")) or ""
117
+ return ValidationIssue(
118
+ severity=severity,
119
+ location=_str_or_none(data.get("location")),
120
+ message=str(data.get("message", "")),
121
+ )
122
+
123
+
124
+ def parse_problem(headers: Mapping[str, str], content: bytes) -> Problem | None:
125
+ """Parse an RFC 9457 problem body.
126
+
127
+ Accepts ``application/problem+json``, or any JSON object with ``type`` and ``status``.
128
+ Returns ``None`` for anything else (HTML from a proxy, health reports, empty bodies).
129
+ """
130
+ mtype = media_type(headers)
131
+ if not content or not (mtype.endswith("json") or mtype == ""):
132
+ return None
133
+ try:
134
+ decoded: Any = json.loads(content)
135
+ except ValueError:
136
+ return None
137
+ if not isinstance(decoded, dict):
138
+ return None
139
+ data = cast("dict[str, Any]", decoded)
140
+ is_problem_media = mtype == "application/problem+json"
141
+ if not is_problem_media and not ("type" in data and "status" in data):
142
+ return None
143
+ type_uri = _str_or_none(data.get("type")) or "about:blank"
144
+ name = short_name(type_uri)
145
+ issues = tuple(
146
+ i for i in (parse_issue(x) for x in as_list(data.get("issues"))) if i is not None
147
+ )
148
+ profiles = tuple(str(p) for p in as_list(data.get("unresolvedProfiles")))
149
+ return Problem(
150
+ type_uri=type_uri,
151
+ type=ProblemType.from_uri(type_uri) or name,
152
+ title=_str_or_none(data.get("title")) or "",
153
+ status=_int_or_none(data.get("status")) or 0,
154
+ detail=_str_or_none(data.get("detail")),
155
+ correlation_id=_str_or_none(data.get("correlationId")),
156
+ issues=issues,
157
+ unresolved_profiles=profiles,
158
+ conflicts=data.get("conflicts"),
159
+ scope=_enum_or_str(RateLimitScope, data.get("scope")),
160
+ limit=_int_or_none(data.get("limit")),
161
+ retry_after_seconds=_int_or_none(data.get("retryAfterSeconds")),
162
+ extensions={k: v for k, v in data.items() if k not in _KNOWN_MEMBERS},
163
+ )
164
+
165
+
166
+ def error_class(status: int, problem: Problem | None) -> type[APIError]:
167
+ """Pick the error class for ``status``, refined by problem type for 400."""
168
+ if status == 400 and problem is not None and isinstance(problem.type, ProblemType):
169
+ refined = _REFINE_400.get(problem.type)
170
+ if refined is not None:
171
+ return refined
172
+ cls = _STATUS_CLASS.get(status)
173
+ if cls is not None:
174
+ return cls
175
+ if 400 <= status < 500:
176
+ return APIError
177
+ return ServerError
178
+
179
+
180
+ def error_for(raw: RawResponse) -> APIError:
181
+ """Build the typed error for a non-2xx response."""
182
+ problem = parse_problem(raw.headers, raw.content)
183
+ return error_class(raw.status_code, problem)(raw, problem)