epgu-api 0.5.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.
epgu/integration.py ADDED
@@ -0,0 +1,528 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright (c) 2025 yellow444 <yellow444@gmail.com>
3
+ """Клиент планов операций НАШЕГО backend по ключу интеграции.
4
+
5
+ Это не клиент Госуслуг. :class:`~epgu.client.EpguClient` ходит в upstream
6
+ gusmev с маркером ЕСИА; :class:`IntegrationClient` ходит только на явно
7
+ заданный ``base_url`` установки backend и передаёт ключ интеграции в
8
+ ``Authorization: Bearer``. Модель ошибок и авторизации своя.
9
+
10
+ Методы только машинные: ``prepare_plan``, ``get_plan``, ``execute_plan``.
11
+ Одобрения здесь нет и не будет: одобряет человек по сессии в интерфейсе
12
+ установки.
13
+
14
+ Правила транспорта:
15
+
16
+ - свой ``httpx.Client``: без cookie, без переменных окружения и ``.netrc``
17
+ (``trust_env=False``), без перехода по редиректам. Ответ 3xx это ошибка
18
+ :class:`UnexpectedResponse`, ключ на другой адрес не уходит;
19
+ - ключ не попадает в URL, ``repr``, текст исключений и журнал;
20
+ - ``http://`` допускается только явно, ``allow_insecure_http=True``, и только
21
+ для loopback: ``localhost``, ``*.localhost``, ``127.0.0.0/8``, ``[::1]``.
22
+ Удалённый адрес по ``http://`` не принимается ни с каким флагом;
23
+ - ``timeout`` это таймауты httpx на connect, read, write и pool. Read
24
+ действует на каждое ожидание данных из сети, а не на весь ответ, поэтому
25
+ общего срока на запрос нет, в отличие от JS-клиента. Дополнительно, если
26
+ от начала запроса прошло больше ``timeout``, чтение прерывается на
27
+ ближайшей РАСКОДИРОВАННОЙ порции тела. Сжатое тело может долго не давать
28
+ ни одной такой порции, и тогда это ограничение срабатывает позже.
29
+ Любая из этих ошибок у execute даёт :class:`OutcomeUnknown` без повтора;
30
+ - ответ проверяется по контракту: ``plan_id`` совпадает с запрошенным,
31
+ поля нужных типов, статус из известного набора. Ответ execute 200 без
32
+ ``status="succeeded"`` нашего плана это :class:`OutcomeUnknown`;
33
+ - известный ключ вырезается из всех полей ошибки: ``code``, ``title``,
34
+ ``detail``, ``errors`` и списков ``outcome``. Сырое тело сервера к ошибке
35
+ не прикрепляется;
36
+ - повторов нет ни по таймауту, ни по 5xx. После обрыва ``execute_plan``
37
+ нельзя считать, что сервер план не принял: это :class:`OutcomeUnknown`
38
+ без списков вызовов.
39
+
40
+ Пример::
41
+
42
+ with IntegrationClient("https://epgu.example/api", key) as api:
43
+ plan = api.prepare_plan("svc.send", "target-1", payload,
44
+ idempotency_key="order-42-v1")
45
+ # ... человек проверяет и одобряет план в интерфейсе установки ...
46
+ done = api.execute_plan(plan.plan_id, plan.plan_hash)
47
+ """
48
+
49
+ from __future__ import annotations
50
+
51
+ import base64
52
+ import ipaddress
53
+ import re
54
+ import time
55
+ from dataclasses import dataclass, field
56
+ from typing import Any, Dict, Optional, Sequence, Tuple, Type
57
+ from urllib.parse import urlsplit
58
+
59
+ import httpx
60
+
61
+ from .const import USER_AGENT
62
+ from .errors import EpguError
63
+
64
+ PLANS_PATH = "/v1/operations/plans"
65
+ PROBLEM_MEDIA_TYPE = "application/problem+json"
66
+
67
+ _PLAN_ID_RE = re.compile(r"plan_[0-9a-f]{32}")
68
+ _CODE_RE = re.compile(r"[a-z][a-z0-9_]{0,63}")
69
+ _PLAN_STATUSES = frozenset(("planned", "approved", "inflight", "succeeded", "failed",
70
+ "unknown"))
71
+ _SUCCEEDED = "succeeded"
72
+ _CREDENTIAL_RE = re.compile(r"[\x21-\x7e]{16,4096}")
73
+ _REDACTED = "***"
74
+
75
+
76
+ # ошибки
77
+
78
+
79
+ class IntegrationError(EpguError):
80
+ """Базовая ошибка клиента backend. Текст безопасно показывать и писать в журнал."""
81
+
82
+
83
+ class IntegrationConfigError(IntegrationError):
84
+ """Неверный ``base_url``, ключ или аргумент; запрос не отправлялся."""
85
+
86
+
87
+ class TransportError(IntegrationError):
88
+ """Ответа нет: сеть, таймаут, TLS.
89
+
90
+ ``may_have_reached_server`` честно говорит, мог ли запрос дойти. Для
91
+ prepare повтор с тем же ``idempotency_key`` безопасен и решается
92
+ вызывающим; для execute вместо этой ошибки поднимается
93
+ :class:`OutcomeUnknown`.
94
+ """
95
+
96
+ def __init__(self, message: str, *, may_have_reached_server: bool) -> None:
97
+ super().__init__(message)
98
+ self.may_have_reached_server = may_have_reached_server
99
+
100
+
101
+ class UnexpectedResponse(IntegrationError):
102
+ """Ответ не по контракту: редирект, не JSON, не problem+json у ошибки."""
103
+
104
+ def __init__(self, message: str, *, status: int) -> None:
105
+ super().__init__(message)
106
+ self.status = status
107
+
108
+
109
+ class ProblemError(IntegrationError):
110
+ """Ответ backend в формате problem+json (RFC 9457).
111
+
112
+ Attributes:
113
+ status: код HTTP.
114
+ code: машинный код ошибки (``plan_expired``, ``policy_changed``...).
115
+ title, detail: тексты сервера.
116
+ errors: подробности проверки тела (422), если есть.
117
+ """
118
+
119
+ def __init__(self, status: int, code: str, title: str, detail: str,
120
+ errors: Optional[Sequence[Dict[str, Any]]] = None) -> None:
121
+ super().__init__("%s %s: %s" % (status, code, detail or title))
122
+ self.status = status
123
+ self.code = code
124
+ self.title = title
125
+ self.detail = detail
126
+ self.errors = tuple(errors or ())
127
+
128
+
129
+ class InvalidRequest(ProblemError):
130
+ """400 и 422: тело или параметр не того вида."""
131
+
132
+
133
+ class Unauthenticated(ProblemError):
134
+ """401: ключ неверный, отозван или истёк."""
135
+
136
+
137
+ class Forbidden(ProblemError):
138
+ """403: у ключа нет нужного права (``insufficient_scope``)."""
139
+
140
+
141
+ class PlanNotFound(ProblemError):
142
+ """404: плана нет или он чужой."""
143
+
144
+
145
+ class Conflict(ProblemError):
146
+ """409: контекст, хеш, состояние плана, политика или идемпотентность."""
147
+
148
+
149
+ class PlanExpired(ProblemError):
150
+ """410: срок плана истёк."""
151
+
152
+
153
+ class ServiceUnavailable(ProblemError):
154
+ """503: исполнитель не настроен или операция не допускается к исполнению."""
155
+
156
+
157
+ class OutcomeUnknown(ProblemError):
158
+ """Исход execute неизвестен. Повтор не выполняется: нужна ручная сверка.
159
+
160
+ ``completed_calls`` и ``uncertain_calls`` берутся только из поля
161
+ ``outcome`` ответа сервера (502). Если сервер его не прислал или ответа
162
+ не было вовсе, оба равны ``None``: частичный результат неизвестен, и это
163
+ не то же самое, что пустые списки. ``status`` равен ``None``, если
164
+ ответа не было.
165
+ """
166
+
167
+ def __init__(self, plan_id: str, *, status: Optional[int], code: str, title: str,
168
+ detail: str, completed_calls: Optional[Tuple[str, ...]] = None,
169
+ uncertain_calls: Optional[Tuple[str, ...]] = None) -> None:
170
+ super().__init__(status or 0, code, title, detail)
171
+ self.status = status # type: ignore[assignment]
172
+ self.plan_id = plan_id
173
+ self.completed_calls = completed_calls
174
+ self.uncertain_calls = uncertain_calls
175
+
176
+ @property
177
+ def partial_known(self) -> bool:
178
+ return self.completed_calls is not None and self.uncertain_calls is not None
179
+
180
+
181
+ _BY_STATUS: Dict[int, Type[ProblemError]] = {
182
+ 400: InvalidRequest,
183
+ 401: Unauthenticated,
184
+ 403: Forbidden,
185
+ 404: PlanNotFound,
186
+ 409: Conflict,
187
+ 410: PlanExpired,
188
+ 422: InvalidRequest,
189
+ 503: ServiceUnavailable,
190
+ }
191
+
192
+
193
+ # ответы
194
+
195
+
196
+ @dataclass(frozen=True)
197
+ class Plan:
198
+ """План операции, как его отдаёт backend (``PlanOut``)."""
199
+
200
+ plan_id: str
201
+ plan_hash: str
202
+ status: str
203
+ expires_at: str
204
+ preview: Dict[str, Any]
205
+ result: Optional[Dict[str, Any]] = None
206
+ error_code: Optional[str] = None
207
+ steps: Tuple[Dict[str, Any], ...] = ()
208
+ # True для нового плана (201), False для повтора по ключу идемпотентности (200),
209
+ # None для get_plan.
210
+ created: Optional[bool] = None
211
+ raw: Dict[str, Any] = field(default_factory=dict, repr=False, compare=False)
212
+
213
+
214
+ @dataclass(frozen=True)
215
+ class ExecuteResult:
216
+ plan_id: str
217
+ status: str
218
+ result: Optional[Dict[str, Any]] = None
219
+
220
+
221
+ # клиент
222
+
223
+
224
+ def _is_loopback(host: str) -> bool:
225
+ if host == "localhost" or host.endswith(".localhost"):
226
+ return True
227
+ try:
228
+ return ipaddress.ip_address(host).is_loopback
229
+ except ValueError:
230
+ return False
231
+
232
+
233
+ def _check_base_url(base_url: Any, allow_insecure_http: bool) -> str:
234
+ if not isinstance(base_url, str) or not base_url:
235
+ raise IntegrationConfigError("base_url: нужен адрес backend установки")
236
+ parts = urlsplit(base_url)
237
+ if parts.scheme not in ("https", "http") or not parts.hostname:
238
+ raise IntegrationConfigError("base_url: нужен абсолютный адрес https://")
239
+ if parts.scheme == "http" and not allow_insecure_http:
240
+ raise IntegrationConfigError(
241
+ "base_url: http:// только явно, allow_insecure_http=True для разработки")
242
+ if parts.scheme == "http" and not _is_loopback(parts.hostname):
243
+ raise IntegrationConfigError(
244
+ "base_url: http:// только для loopback (localhost, 127.0.0.0/8, ::1)")
245
+ if parts.username or parts.password or parts.query or parts.fragment:
246
+ raise IntegrationConfigError("base_url: без учётных данных, query и fragment")
247
+ return base_url.rstrip("/")
248
+
249
+
250
+ def _check_plan_id(plan_id: Any) -> str:
251
+ if not isinstance(plan_id, str) or not _PLAN_ID_RE.fullmatch(plan_id):
252
+ raise IntegrationConfigError("plan_id: ожидается plan_ и 32 hex-символа")
253
+ return plan_id
254
+
255
+
256
+ class IntegrationClient:
257
+ """Машинный клиент планов операций backend установки.
258
+
259
+ Args:
260
+ base_url: адрес backend, например ``https://epgu.example/api``.
261
+ credential: секрет ключа интеграции. Хранится только в памяти объекта.
262
+ timeout: таймауты httpx (connect, read, write, pool), секунды. Не общий
263
+ срок запроса, см. описание модуля.
264
+ allow_insecure_http: разрешить ``http://`` на loopback для локальной
265
+ разработки. Удалённый адрес по ``http://`` не принимается.
266
+ transport: транспорт ``httpx`` для тестов. Клиент ``httpx`` при этом
267
+ всё равно свой: чужая cookie-сессия и чужие заголовки не наследуются.
268
+ """
269
+
270
+ def __init__(self, base_url: str, credential: str, *, timeout: float = 30.0,
271
+ allow_insecure_http: bool = False,
272
+ transport: Optional[httpx.BaseTransport] = None) -> None:
273
+ self.base_url = _check_base_url(base_url, allow_insecure_http)
274
+ if not isinstance(credential, str) or not _CREDENTIAL_RE.fullmatch(credential):
275
+ raise IntegrationConfigError("credential: нужен секрет ключа интеграции")
276
+ self._credential = credential
277
+ self._timeout = float(timeout)
278
+ self._client = httpx.Client(
279
+ timeout=timeout, follow_redirects=False, trust_env=False, transport=transport,
280
+ headers={"User-Agent": USER_AGENT, "Accept": "application/json"},
281
+ )
282
+
283
+ def __repr__(self) -> str:
284
+ return "IntegrationClient(base_url=%r)" % self.base_url
285
+
286
+ def close(self) -> None:
287
+ self._client.close()
288
+
289
+ def __enter__(self) -> "IntegrationClient":
290
+ return self
291
+
292
+ def __exit__(self, *exc: Any) -> None:
293
+ self.close()
294
+
295
+ # методы
296
+
297
+ def prepare_plan(self, capability_id: str, target: str, payload: bytes, *,
298
+ idempotency_key: str,
299
+ attachments: Sequence[Tuple[str, bytes]] = ()) -> Plan:
300
+ """Подготовить план. Исполнитель не вызывается, план ждёт одобрения человеком.
301
+
302
+ Повтор с тем же ``idempotency_key`` и тем же телом возвращает тот же
303
+ план (``created=False``). Ключ при повторе менять нельзя: так
304
+ появится второй план.
305
+ """
306
+ if not isinstance(payload, (bytes, bytearray)):
307
+ raise IntegrationConfigError("payload: нужны байты")
308
+ body = {
309
+ "capability_id": capability_id,
310
+ "target": target,
311
+ "payload_b64": base64.b64encode(bytes(payload)).decode("ascii"),
312
+ "attachments": [
313
+ {"name": name, "content_b64": base64.b64encode(bytes(content)).decode("ascii")}
314
+ for name, content in attachments
315
+ ],
316
+ "idempotency_key": idempotency_key,
317
+ }
318
+ response = self._send("POST", PLANS_PATH, body)
319
+ data = self._json(response, (200, 201))
320
+ return self._plan(data, created=response.status_code == 201, plan_id=None)
321
+
322
+ def get_plan(self, plan_id: str) -> Plan:
323
+ """Свой план со статусом, результатом и журналом шагов."""
324
+ path = "%s/%s" % (PLANS_PATH, _check_plan_id(plan_id))
325
+ return self._plan(self._json(self._send("GET", path), (200,)), created=None,
326
+ plan_id=plan_id)
327
+
328
+ def execute_plan(self, plan_id: str, plan_hash: str) -> ExecuteResult:
329
+ """Исполнить одобренный план. Повтора нет ни при каком исходе.
330
+
331
+ Raises:
332
+ OutcomeUnknown: 502 или нет ответа. Сверьте план через
333
+ :meth:`get_plan`; ошибка этого чтения не отменяет неизвестный исход.
334
+ """
335
+ path = "%s/%s/execute" % (PLANS_PATH, _check_plan_id(plan_id))
336
+ try:
337
+ response = self._send("POST", path, {"plan_hash": plan_hash})
338
+ except TransportError as err:
339
+ raise OutcomeUnknown(
340
+ plan_id, status=None, code="transport_error",
341
+ title="Ответ на execute не получен",
342
+ detail="%s; сервер мог принять запрос, повтор не выполняется" % err,
343
+ ) from None
344
+ status = response.status_code
345
+ if status == 200:
346
+ # Успех только наш: тот же plan_id, status=succeeded, result объект
347
+ # или null. Иначе исход неизвестен, ответ не доказывает исполнение.
348
+ try:
349
+ data = self._json(response, (200,))
350
+ except UnexpectedResponse:
351
+ data = {}
352
+ result = data.get("result")
353
+ if (data.get("plan_id") == plan_id and data.get("status") == _SUCCEEDED
354
+ and (result is None or isinstance(result, dict))):
355
+ return ExecuteResult(plan_id=plan_id, status=_SUCCEEDED, result=result)
356
+ if status == 502:
357
+ raise self._unknown(plan_id, response)
358
+ # Отказ до исполнения бывает только по контракту: 4xx или 503 с problem+json.
359
+ # Всё остальное (500, 504 прокси, редирект, чужое тело) не доказывает, что
360
+ # сервер план не исполнил.
361
+ if 400 <= status < 500 or status == 503:
362
+ try:
363
+ self._problem_body(response)
364
+ except UnexpectedResponse:
365
+ pass
366
+ else:
367
+ self._json(response, (200,))
368
+ raise OutcomeUnknown(plan_id, status=status, code="unexpected_response",
369
+ title="Ответ на execute не по контракту",
370
+ detail="ответ %s; сервер мог исполнить план, повтор не "
371
+ "выполняется" % status)
372
+
373
+ # транспорт
374
+
375
+ def _send(self, method: str, path: str, body: Optional[Dict[str, Any]] = None
376
+ ) -> httpx.Response:
377
+ headers = {"Authorization": "Bearer " + self._credential}
378
+ # httpx сохраняет Set-Cookie ответов; ключ интеграции cookie не пользуется.
379
+ self._client.cookies.clear()
380
+ request = self._client.build_request(method, self.base_url + path, json=body,
381
+ headers=headers)
382
+ request.headers.pop("Cookie", None)
383
+ # Таймауты httpx действуют на каждую операцию чтения, а не на весь ответ.
384
+ # Сверх них: проверка прошедшего времени между раскодированными порциями
385
+ # тела. Это не общий срок: декодер может долго не выдавать ни одной порции.
386
+ deadline = time.monotonic() + self._timeout
387
+ try:
388
+ streamed = self._client.send(request, stream=True)
389
+ try:
390
+ chunks = []
391
+ for chunk in streamed.iter_bytes():
392
+ chunks.append(chunk)
393
+ if time.monotonic() > deadline:
394
+ raise TransportError("таймаут чтения ответа",
395
+ may_have_reached_server=True)
396
+ finally:
397
+ streamed.close()
398
+ self._client.cookies.clear()
399
+ # Тело уже раскодировано iter_bytes: заголовки сжатия и длины не переносятся.
400
+ kept = [(k, v) for k, v in streamed.headers.multi_items()
401
+ if k.lower() not in ("content-encoding", "content-length")]
402
+ return httpx.Response(streamed.status_code, headers=kept,
403
+ content=b"".join(chunks), request=request)
404
+ except httpx.TimeoutException as err:
405
+ reached = not isinstance(err, (httpx.ConnectTimeout, httpx.PoolTimeout))
406
+ raise TransportError("таймаут запроса (%s)" % type(err).__name__,
407
+ may_have_reached_server=reached) from None
408
+ except httpx.ConnectError:
409
+ raise TransportError("нет соединения с backend",
410
+ may_have_reached_server=False) from None
411
+ except httpx.TransportError as err:
412
+ raise TransportError("ошибка транспорта (%s)" % type(err).__name__,
413
+ may_have_reached_server=True) from None
414
+
415
+ def _clean(self, text: Any) -> str:
416
+ value = text if isinstance(text, str) else ""
417
+ return value.replace(self._credential, _REDACTED)
418
+
419
+ def _code(self, code: str) -> str:
420
+ """Машинный код сервера, только если это код, а не произвольный текст."""
421
+ if self._credential in code or not _CODE_RE.fullmatch(code):
422
+ return "unrecognized_code"
423
+ return code
424
+
425
+ def _scrub(self, value: Any, depth: int = 0) -> Any:
426
+ """Копия подробностей 422 без ключа: только JSON-значения, строки очищены."""
427
+ if depth > 8:
428
+ return None
429
+ if isinstance(value, str):
430
+ return self._clean(value)
431
+ if isinstance(value, dict):
432
+ return {self._clean(str(k)): self._scrub(v, depth + 1) for k, v in value.items()}
433
+ if isinstance(value, list):
434
+ return [self._scrub(item, depth + 1) for item in value]
435
+ if value is None or isinstance(value, (bool, int, float)):
436
+ return value
437
+ return None
438
+
439
+ def _errors(self, errors: Any) -> Tuple[Dict[str, Any], ...]:
440
+ if not isinstance(errors, list):
441
+ return ()
442
+ return tuple(self._scrub(item) for item in errors if isinstance(item, dict))
443
+
444
+ def _problem_body(self, response: httpx.Response) -> Dict[str, Any]:
445
+ media = response.headers.get("content-type", "").split(";")[0].strip().lower()
446
+ if media != PROBLEM_MEDIA_TYPE:
447
+ raise UnexpectedResponse(
448
+ "ответ %s без problem+json" % response.status_code, status=response.status_code)
449
+ try:
450
+ data = response.json()
451
+ except ValueError:
452
+ raise UnexpectedResponse("problem+json не разбирается",
453
+ status=response.status_code) from None
454
+ if not isinstance(data, dict) or not isinstance(data.get("code"), str):
455
+ raise UnexpectedResponse("problem+json без code", status=response.status_code)
456
+ return data
457
+
458
+ def _json(self, response: httpx.Response, ok: Tuple[int, ...]) -> Dict[str, Any]:
459
+ status = response.status_code
460
+ if 300 <= status < 400:
461
+ raise UnexpectedResponse("редирект %s не выполняется" % status, status=status)
462
+ if status not in ok:
463
+ data = self._problem_body(response)
464
+ kind = _BY_STATUS.get(status, ProblemError)
465
+ raise kind(status, self._code(data["code"]), self._clean(data.get("title")),
466
+ self._clean(data.get("detail")), self._errors(data.get("errors")))
467
+ try:
468
+ data = response.json()
469
+ except ValueError:
470
+ raise UnexpectedResponse("ответ %s не JSON" % status, status=status) from None
471
+ if not isinstance(data, dict):
472
+ raise UnexpectedResponse("ответ %s не объект" % status, status=status)
473
+ return data
474
+
475
+ def _unknown(self, plan_id: str, response: httpx.Response) -> OutcomeUnknown:
476
+ try:
477
+ data = self._problem_body(response)
478
+ except UnexpectedResponse:
479
+ return OutcomeUnknown(plan_id, status=502, code="outcome_unknown",
480
+ title="Результат внешней операции неизвестен",
481
+ detail="ответ 502 не по контракту")
482
+ completed = uncertain = None
483
+ outcome = data.get("outcome")
484
+ if isinstance(outcome, dict) and outcome.get("plan_id") == plan_id:
485
+ done, open_ = outcome.get("completed_calls"), outcome.get("uncertain_calls")
486
+ if (isinstance(done, list) and isinstance(open_, list)
487
+ and all(isinstance(item, str) for item in done + open_)):
488
+ completed = tuple(self._clean(item) for item in done)
489
+ uncertain = tuple(self._clean(item) for item in open_)
490
+ return OutcomeUnknown(plan_id, status=502, code=self._code(data["code"]),
491
+ title=self._clean(data.get("title")),
492
+ detail=self._clean(data.get("detail")),
493
+ completed_calls=completed, uncertain_calls=uncertain)
494
+
495
+ @staticmethod
496
+ def _plan(data: Dict[str, Any], *, created: Optional[bool], plan_id: Optional[str]) -> Plan:
497
+ """План по контракту ``PlanOut``. ``plan_id`` для get: ответ о том же плане."""
498
+
499
+ def bad(what: str) -> UnexpectedResponse:
500
+ return UnexpectedResponse("план не по контракту: %s" % what, status=200)
501
+
502
+ got = data.get("plan_id")
503
+ if not isinstance(got, str) or not _PLAN_ID_RE.fullmatch(got):
504
+ raise bad("plan_id")
505
+ if plan_id is not None and got != plan_id:
506
+ raise bad("plan_id не тот, что запрошен")
507
+ for key in ("plan_hash", "expires_at"):
508
+ if not isinstance(data.get(key), str) or not data[key]:
509
+ raise bad(key)
510
+ if data.get("status") not in _PLAN_STATUSES:
511
+ raise bad("status")
512
+ if not isinstance(data.get("preview"), dict):
513
+ raise bad("preview")
514
+ result, error_code = data.get("result"), data.get("error_code")
515
+ if result is not None and not isinstance(result, dict):
516
+ raise bad("result")
517
+ if error_code is not None and not isinstance(error_code, str):
518
+ raise bad("error_code")
519
+ steps = data.get("steps", [])
520
+ if not isinstance(steps, list) or not all(
521
+ isinstance(s, dict) and isinstance(s.get("name"), str)
522
+ and isinstance(s.get("state"), str) for s in steps):
523
+ raise bad("steps")
524
+ return Plan(
525
+ plan_id=got, plan_hash=data["plan_hash"], status=data["status"],
526
+ expires_at=data["expires_at"], preview=data["preview"], result=result,
527
+ error_code=error_code, steps=tuple(steps), created=created, raw=data,
528
+ )