deposit-python 2.0.1__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.
deposit/_paging.py ADDED
@@ -0,0 +1,645 @@
1
+ """Lazy, bounded iteration over revision-bound portable query pages."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ from typing import Any, Iterator
8
+ from collections.abc import Mapping as MappingABC, Sequence as SequenceABC
9
+ from types import MappingProxyType
10
+
11
+ from .errors import DepositError
12
+
13
+
14
+ class QueryPage(dict):
15
+ """Portable page payload; revision and scope remain opaque server cursor state."""
16
+
17
+
18
+ class QueryIterator:
19
+ """Fetch pages only when needed; closing never replays or restarts a cursor."""
20
+
21
+ def __init__(self, store, querystr: str, parameters: dict[str, Any], page_size: int):
22
+ self._store = store
23
+ self._querystr = querystr
24
+ self._parameters = parameters
25
+ self._page_size = page_size
26
+ self._cursor: str | None = None
27
+ self._seen_cursors: set[str] = set()
28
+ self._rows: list[dict[str, Any]] = []
29
+ self._row_index = 0
30
+ self._columns = None
31
+ self._first = True
32
+ self._closed = False
33
+ self._finished = False
34
+
35
+ @property
36
+ def closed(self) -> bool:
37
+ return self._closed
38
+
39
+ def __iter__(self):
40
+ return self
41
+
42
+ def __next__(self):
43
+ if self._closed or self._finished:
44
+ raise StopIteration
45
+ while self._row_index >= len(self._rows):
46
+ if not self._first and self._cursor is None:
47
+ self._finished = True
48
+ self.close()
49
+ raise StopIteration
50
+ cursor = None if self._first else self._cursor
51
+ try:
52
+ page = self._store.get_query_page(
53
+ self._querystr, parameters=self._parameters, page_size=self._page_size, cursor=cursor
54
+ )
55
+ self._validate_page(page)
56
+ except BaseException:
57
+ self.close()
58
+ raise
59
+ self._first = False
60
+ self._rows = page["rows"]
61
+ self._row_index = 0
62
+ self._cursor = page["nextCursor"]
63
+ if self._cursor is not None:
64
+ if self._cursor in self._seen_cursors:
65
+ self.close()
66
+ raise DepositError("INVALID_RESPONSE", "Query page cursor repeated")
67
+ self._seen_cursors.add(self._cursor)
68
+ if not self._rows and self._cursor is None:
69
+ self._finished = True
70
+ self.close()
71
+ raise StopIteration
72
+ row = self._rows[self._row_index]
73
+ self._row_index += 1
74
+ return row
75
+
76
+ def _validate_page(self, page):
77
+ if not isinstance(page, dict) or set(page) != {"columns", "rows", "nextCursor"}:
78
+ raise DepositError("INVALID_RESPONSE", "Query iterator received an invalid page")
79
+ columns = tuple((column["name"], column["type"]) for column in page["columns"])
80
+ if self._columns is None:
81
+ self._columns = columns
82
+ elif self._columns != columns:
83
+ raise DepositError("REVISION_CONFLICT", "Query page schema changed during iteration")
84
+
85
+ def materialize(self, *, max_items: int = 10_000) -> list[dict[str, Any]]:
86
+ if type(max_items) is not int or max_items < 0:
87
+ raise ValueError("max_items must be a nonnegative integer")
88
+ output = []
89
+ try:
90
+ for item in self:
91
+ if len(output) >= max_items:
92
+ raise ValueError(f"Query materialization exceeds max_items={max_items}")
93
+ output.append(item)
94
+ except BaseException:
95
+ self.close()
96
+ raise
97
+ return output
98
+
99
+ def close(self):
100
+ self._closed = True
101
+ self._rows = []
102
+ self._row_index = 0
103
+
104
+ def __enter__(self):
105
+ if self._closed:
106
+ raise RuntimeError("Query iterator is closed")
107
+ return self
108
+
109
+ def __exit__(self, exc_type, exc, traceback):
110
+ self.close()
111
+
112
+
113
+ class EntityPageIterator:
114
+ """Lazy consumer for one catalogued Domain *Page procedure."""
115
+
116
+ def __init__(self, store, procedure: str, selection, *, page_size: int = 200, transform=None, prepare=None,
117
+ expected_revision: int | None = None):
118
+ if type(page_size) is not int or not 1 <= page_size <= 1000:
119
+ raise ValueError("page_size must be an integer from 1 through 1000")
120
+ self._store = store
121
+ self._procedure = procedure
122
+ self._selection = selection
123
+ self._page_size = page_size
124
+ self._transform = transform or (lambda value, revision: value)
125
+ self._prepare = prepare
126
+ self._revision = expected_revision
127
+ self._cursor = None
128
+ self._seen_cursors = set()
129
+ self._items = []
130
+ self._index = 0
131
+ self._first = True
132
+ self._closed = False
133
+
134
+ @property
135
+ def closed(self) -> bool:
136
+ return self._closed
137
+
138
+ @property
139
+ def revision(self) -> int | None:
140
+ """Checked Namespace revision, retained even after the final page closes."""
141
+ return self._revision
142
+
143
+ def __iter__(self):
144
+ return self
145
+
146
+ def __next__(self):
147
+ if self._closed:
148
+ raise StopIteration
149
+ while self._index >= len(self._items):
150
+ if not self._first and self._cursor is None:
151
+ self.close()
152
+ raise StopIteration
153
+ options = {"pageSize": self._page_size}
154
+ if not self._first:
155
+ options["cursor"] = self._cursor
156
+ try:
157
+ page, revision = self._store._checked_entity_page(
158
+ self._procedure, self._selection, options, expected_revision=self._revision
159
+ )
160
+ self._validate_page(page)
161
+ items = page["items"]
162
+ if items and self._prepare is not None:
163
+ items = self._prepare(items, revision)
164
+ except BaseException:
165
+ self.close()
166
+ raise
167
+ self._first = False
168
+ self._revision = revision
169
+ self._items = items
170
+ self._index = 0
171
+ self._cursor = page["nextCursor"]
172
+ if self._cursor is not None:
173
+ if self._cursor in self._seen_cursors:
174
+ self.close()
175
+ raise DepositError("INVALID_RESPONSE", "Entity page cursor repeated")
176
+ self._seen_cursors.add(self._cursor)
177
+ if not self._items and self._cursor is None:
178
+ self.close()
179
+ raise StopIteration
180
+ item = self._items[self._index]
181
+ self._index += 1
182
+ try:
183
+ return self._transform(item, self._revision)
184
+ except BaseException:
185
+ self.close()
186
+ raise
187
+
188
+ def _validate_page(self, page):
189
+ if (not isinstance(page, dict) or not isinstance(page.get("items"), list)
190
+ or "nextCursor" not in page):
191
+ raise DepositError("INVALID_RESPONSE", "Entity page returned invalid items")
192
+ cursor = page.get("nextCursor")
193
+ if cursor is not None and (not isinstance(cursor, str) or not cursor):
194
+ raise DepositError("INVALID_RESPONSE", "Entity page returned an invalid cursor")
195
+ if any(not isinstance(item, dict) for item in page["items"]):
196
+ raise DepositError("INVALID_RESPONSE", "Entity page contains an invalid item")
197
+
198
+ def materialize(self, *, max_items: int = 10_000):
199
+ if type(max_items) is not int or max_items < 0:
200
+ raise ValueError("max_items must be a nonnegative integer")
201
+ result = []
202
+ try:
203
+ for item in self:
204
+ if len(result) >= max_items:
205
+ raise ValueError(f"Page materialization exceeds max_items={max_items}")
206
+ result.append(item)
207
+ except BaseException:
208
+ self.close()
209
+ raise
210
+ return result
211
+
212
+ def close(self):
213
+ self._closed = True
214
+ self._items = []
215
+ self._index = 0
216
+
217
+ def __enter__(self):
218
+ if self._closed:
219
+ raise RuntimeError("Entity page iterator is closed")
220
+ return self
221
+
222
+ def __exit__(self, exc_type, exc, traceback):
223
+ self.close()
224
+
225
+
226
+ _MAX_SAFE_INTEGER = (1 << 63) - 1
227
+ _PAGE_LIMIT = 256
228
+ _PAGE_BYTES = 512 * 1024
229
+ _ENTRY_BYTES = 32 * 1024
230
+ _TEXT_BYTES = 16 * 1024
231
+
232
+
233
+ def _nonnegative_long(value):
234
+ return type(value) is int and 0 <= value <= _MAX_SAFE_INTEGER
235
+
236
+
237
+ def _encoded_size(value):
238
+ return len(json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))
239
+
240
+
241
+ def _invalid_result(message):
242
+ return DepositError("INVALID_RESPONSE", message)
243
+
244
+
245
+ class ImportResult(MappingABC):
246
+ """Immutable result envelope with collections read on demand from the Server."""
247
+
248
+ _FIELDS = ("format", "resultId", "leaseId", "leaseExpiresAt", "operationId", "kind",
249
+ "state", "namespaceId", "planId", "revision", "expiresAt", "collections")
250
+
251
+ def __init__(self, request, envelope: dict[str, Any], *, plan_observation=None):
252
+ if not valid_import_result_envelope(envelope):
253
+ raise _invalid_result("Invalid import result envelope")
254
+ if plan_observation is not None and not _valid_plan_observation(plan_observation, envelope):
255
+ raise _invalid_result("Import plan observation does not match its immutable result")
256
+ self._request = request
257
+ immutable = dict(envelope)
258
+ immutable["collections"] = MappingProxyType({
259
+ key: MappingProxyType(dict(value)) for key, value in envelope["collections"].items()
260
+ })
261
+ self._envelope = MappingProxyType(immutable)
262
+ self._plan_observation = (None if plan_observation is None
263
+ else MappingProxyType(dict(plan_observation)))
264
+ self._closed = False
265
+
266
+ def _check_open(self):
267
+ if self._closed:
268
+ raise RuntimeError("ImportResult is closed")
269
+
270
+ def _read(self, suffix, *arguments):
271
+ request = self._request
272
+ if request is None:
273
+ self._check_open()
274
+ return request("deposit.get.importResult" + suffix, self.result_id,
275
+ self._envelope["leaseId"], *arguments)
276
+
277
+ def _entries(self, collection, count=None):
278
+ position = 0
279
+ cursor = None
280
+ while True:
281
+ page = self._read("Page", collection, cursor, _PAGE_LIMIT)
282
+ if (not isinstance(page, dict) or set(page) != {"resultId", "collection", "entries", "nextCursor"}
283
+ or page["resultId"] != self.result_id or page["collection"] != collection
284
+ or not isinstance(page["entries"], list) or len(page["entries"]) > _PAGE_LIMIT):
285
+ raise _invalid_result("Invalid import result page")
286
+ entries = page["entries"]
287
+ sizes = [_encoded_size(entry) for entry in entries]
288
+ if any(size > _ENTRY_BYTES for size in sizes) or sum(sizes) > _PAGE_BYTES:
289
+ raise _invalid_result("Import result page exceeds its byte bounds")
290
+ position += len(entries)
291
+ cursor = page["nextCursor"]
292
+ if cursor is not None and (
293
+ not isinstance(cursor, dict)
294
+ or set(cursor) != {"resultId", "leaseId", "collection", "position", "integrity"}
295
+ or cursor["resultId"] != self.result_id or cursor["leaseId"] != self._envelope["leaseId"]
296
+ or cursor["collection"] != collection or not _nonnegative_long(cursor["position"])
297
+ or cursor["position"] != position or not entries
298
+ or not isinstance(cursor["integrity"], str) or not cursor["integrity"]
299
+ ):
300
+ raise _invalid_result("Invalid import result cursor")
301
+ if count is not None and (position > count or (cursor is None) != (position == count)):
302
+ raise _invalid_result("Import result collection count differs from its descriptor")
303
+ for entry in entries:
304
+ self._check_open()
305
+ yield entry
306
+ if cursor is None:
307
+ return
308
+
309
+ @property
310
+ def result_id(self):
311
+ return self._envelope["resultId"]
312
+
313
+ @property
314
+ def operation_id(self):
315
+ return self._envelope["operationId"]
316
+
317
+ @property
318
+ def state(self):
319
+ return self._envelope["state"]
320
+
321
+ @property
322
+ def plan_observation(self):
323
+ """The separately observed current plan lifecycle, if this is an inspection result."""
324
+ return self._plan_observation
325
+
326
+ @property
327
+ def plan_state(self):
328
+ return None if self._plan_observation is None else self._plan_observation["state"]
329
+
330
+ @property
331
+ def plan_id(self):
332
+ return self._envelope["planId"]
333
+
334
+ def __getitem__(self, key):
335
+ if self._closed:
336
+ raise RuntimeError("ImportResult is closed")
337
+ if key == "plan" and self._plan_observation is not None:
338
+ return self._plan_observation
339
+ if key == "plan":
340
+ raise KeyError(key)
341
+ if key in self._envelope:
342
+ return self._envelope[key]
343
+ descriptor = self._envelope["collections"].get(key)
344
+ if descriptor is None:
345
+ raise KeyError(key)
346
+ return _lazy_collection(key, descriptor["kind"], descriptor["count"], self)
347
+
348
+ def __iter__(self):
349
+ plan = ("plan",) if self._plan_observation is not None else ()
350
+ return iter((*self._FIELDS, *plan, *self._envelope["collections"].keys()))
351
+
352
+ def __len__(self):
353
+ return len(self._FIELDS) + (self._plan_observation is not None) + len(self._envelope["collections"])
354
+
355
+ def close(self):
356
+ """Close this view. The Server lease expires at its fixed deadline."""
357
+ self._closed = True
358
+ self._request = None
359
+
360
+ @property
361
+ def closed(self):
362
+ return self._closed
363
+
364
+ def __enter__(self):
365
+ if self._closed:
366
+ raise RuntimeError("ImportResult is closed")
367
+ return self
368
+
369
+ def __exit__(self, exc_type, exc, traceback):
370
+ self.close()
371
+
372
+
373
+ class CloneResult(ImportResult):
374
+ """Receipt-bound lazy result for a full Namespace clone."""
375
+
376
+ @property
377
+ def namespace_id(self):
378
+ return self._envelope["namespaceId"]
379
+
380
+ @property
381
+ def name(self):
382
+ return self["metadata"]["name"]
383
+
384
+ @property
385
+ def identity_mappings(self):
386
+ return self["identityMappings"]
387
+
388
+ @property
389
+ def resource_mapping(self):
390
+ return self["resourceMapping"]
391
+
392
+
393
+ def _lazy_collection(collection, kind, count, owner):
394
+ if kind == "mapping":
395
+ return LazyResultMapping(collection, count, owner)
396
+ return LazyResultSequence(collection, count, owner)
397
+
398
+
399
+ class _LazyResultBase:
400
+ def __init__(self, collection, count, owner):
401
+ self._collection = collection
402
+ self._count = count
403
+ self._owner = owner
404
+
405
+ def _entries(self):
406
+ return self._owner._entries(self._collection, self._count)
407
+
408
+
409
+ class LazyResultSequence(_LazyResultBase, SequenceABC):
410
+ """Indexable, bounded-page sequence backed by remote pages."""
411
+
412
+ def __len__(self):
413
+ return self._count
414
+
415
+ def __iter__(self):
416
+ for descriptor in self._entries():
417
+ yield _decode_import_value(descriptor, self._owner)
418
+
419
+ def __getitem__(self, index):
420
+ if isinstance(index, slice):
421
+ raise TypeError("Lazy result sequences do not materialize slices")
422
+ if type(index) is not int:
423
+ raise TypeError("Import result sequence indices must be integers")
424
+ resolved = index + self._count if index < 0 else index
425
+ if not 0 <= resolved < self._count:
426
+ raise IndexError(index)
427
+ for position, value in enumerate(self):
428
+ if position == resolved:
429
+ return value
430
+ raise IndexError(index)
431
+
432
+
433
+ class LazyResultMapping(_LazyResultBase, MappingABC):
434
+ """Read-only mapping whose entries are decoded one bounded page at a time."""
435
+
436
+ def __len__(self):
437
+ return self._count
438
+
439
+ def _pairs(self):
440
+ for entry in self._entries():
441
+ if isinstance(entry, dict) and set(entry) == {"key", "value"}:
442
+ key, value = entry["key"], entry["value"]
443
+ else:
444
+ raise DepositError("INVALID_RESPONSE", "Import mapping entry is invalid")
445
+ decoded_key = _decode_import_value(key, self._owner)
446
+ if not isinstance(decoded_key, (str, LazyText)):
447
+ raise _invalid_result("Invalid import mapping key")
448
+ yield decoded_key, _decode_import_value(value, self._owner)
449
+
450
+ def __iter__(self):
451
+ for key, _value in self._pairs():
452
+ yield key
453
+
454
+ def items(self):
455
+ return self._pairs()
456
+
457
+ def __getitem__(self, key):
458
+ if isinstance(key, str) and len(key.encode("utf-8")) <= _TEXT_BYTES:
459
+ response = self._owner._read("Entry", self._collection, key)
460
+ if (not isinstance(response, dict) or type(response.get("found")) is not bool
461
+ or response.get("resultId") != self._owner.result_id
462
+ or response.get("collection") != self._collection):
463
+ raise _invalid_result("Invalid import mapping lookup")
464
+ fields = {"resultId", "collection", "found"}
465
+ if response["found"] and set(response) == fields | {"value"}:
466
+ if _encoded_size(response["value"]) > _ENTRY_BYTES:
467
+ raise _invalid_result("Import mapping lookup exceeds its byte bound")
468
+ return _decode_import_value(response["value"], self._owner)
469
+ if not response["found"] and set(response) == fields:
470
+ raise KeyError(key)
471
+ raise _invalid_result("Invalid import mapping lookup")
472
+ for actual_key, value in self._pairs():
473
+ if actual_key == key:
474
+ return value
475
+ raise KeyError(key)
476
+
477
+
478
+ def _decode_import_value(descriptor: Any, owner: ImportResult):
479
+ if not isinstance(descriptor, dict) or not isinstance(descriptor.get("type"), str):
480
+ raise _invalid_result("Invalid import result descriptor")
481
+ kind = descriptor["type"]
482
+ if kind == "scalar" and set(descriptor) == {"type", "value"}:
483
+ value = descriptor["value"]
484
+ if (value is None or isinstance(value, (str, bool))
485
+ or type(value) is int and -_MAX_SAFE_INTEGER - 1 <= value <= _MAX_SAFE_INTEGER
486
+ or type(value) is float and math.isfinite(value)):
487
+ return value
488
+ collection = descriptor.get("collection")
489
+ if isinstance(collection, str) and 0 < len(collection) <= 512:
490
+ if (kind in {"mapping", "sequence"} and set(descriptor) == {"type", "collection", "count"}
491
+ and _nonnegative_long(descriptor["count"])):
492
+ return _lazy_collection(collection, kind, descriptor["count"], owner)
493
+ if (kind == "text" and set(descriptor) == {"type", "collection", "bytes"}
494
+ and _nonnegative_long(descriptor["bytes"])):
495
+ return LazyText(collection, descriptor["bytes"], owner)
496
+ raise _invalid_result("Invalid import result descriptor")
497
+
498
+
499
+ class LazyText:
500
+ """Chunk-readable UTF-8 text that never joins the complete value implicitly."""
501
+
502
+ def __init__(self, collection, byte_count, owner):
503
+ self._collection = collection
504
+ self._byte_count = byte_count
505
+ self._owner = owner
506
+ self._chunks = None
507
+ self._pending = ""
508
+
509
+ def __len__(self):
510
+ return self._byte_count
511
+
512
+ def iter_chunks(self) -> Iterator[str]:
513
+ total = 0
514
+ for descriptor in self._owner._entries(self._collection):
515
+ value = _decode_import_value(descriptor, self._owner)
516
+ if not isinstance(value, str):
517
+ raise _invalid_result("Invalid import text chunk")
518
+ size = len(value.encode("utf-8"))
519
+ total += size
520
+ if not 0 < size <= _TEXT_BYTES or total > self._byte_count:
521
+ raise _invalid_result("Import text exceeds its descriptor bounds")
522
+ yield value
523
+ if total != self._byte_count:
524
+ raise _invalid_result("Import text length differs from its descriptor")
525
+
526
+ def read(self, size: int) -> str:
527
+ if type(size) is not int or size < 0:
528
+ raise ValueError("LazyText.read requires a nonnegative character count")
529
+ if self._owner.closed:
530
+ raise RuntimeError("ImportResult is closed")
531
+ if size == 0:
532
+ return ""
533
+ if self._chunks is None:
534
+ self._chunks = iter(self.iter_chunks())
535
+ output = []
536
+ remaining = size
537
+ while remaining and self._pending:
538
+ part = self._pending[:remaining]
539
+ output.append(part)
540
+ self._pending = self._pending[len(part):]
541
+ remaining -= len(part)
542
+ while remaining:
543
+ try:
544
+ self._pending = next(self._chunks)
545
+ except StopIteration:
546
+ break
547
+ part = self._pending[:remaining]
548
+ output.append(part)
549
+ self._pending = self._pending[len(part):]
550
+ remaining -= len(part)
551
+ return "".join(output)
552
+
553
+ def __iter__(self):
554
+ return self.iter_chunks()
555
+
556
+ def __eq__(self, other):
557
+ if not isinstance(other, str):
558
+ return NotImplemented
559
+ offset = 0
560
+ for chunk in self.iter_chunks():
561
+ if other[offset:offset + len(chunk)] != chunk:
562
+ return False
563
+ offset += len(chunk)
564
+ return offset == len(other)
565
+
566
+
567
+ def valid_import_result_envelope(value: Any, *, leased: bool = True) -> bool:
568
+ fields = {
569
+ "format", "resultId", "operationId", "kind", "state", "namespaceId",
570
+ "planId", "revision", "expiresAt", "collections",
571
+ }
572
+ if leased:
573
+ fields.update({"leaseId", "leaseExpiresAt"})
574
+ if not isinstance(value, dict) or set(value) != fields:
575
+ return False
576
+ if leased and (not isinstance(value["leaseId"], str) or not 0 < len(value["leaseId"]) <= 2048
577
+ or not _nonnegative_long(value["leaseExpiresAt"])):
578
+ return False
579
+ if (value["format"] != "deposit.import-result"
580
+ or not isinstance(value["resultId"], str) or not value["resultId"]
581
+ or (not isinstance(value["operationId"], str) or not value["operationId"])
582
+ or not isinstance(value["kind"], str) or value["kind"] not in {"analysis", "apply", "clone"}
583
+ or not isinstance(value["state"], str) or not value["state"]
584
+ or not isinstance(value["namespaceId"], str) or not value["namespaceId"]
585
+ or (value["planId"] is not None and not isinstance(value["planId"], str))
586
+ or type(value["revision"]) is not int or not 0 <= value["revision"] <= _MAX_SAFE_INTEGER
587
+ or type(value["expiresAt"]) is not int or not 0 <= value["expiresAt"] <= _MAX_SAFE_INTEGER
588
+ or not isinstance(value["collections"], dict)):
589
+ return False
590
+ if value["kind"] == "apply" and value["state"] != "APPLIED":
591
+ return False
592
+ if value["kind"] == "analysis" and (value["state"], value["planId"] is not None) not in {
593
+ ("PLAN_READY", True), ("IMPORT_CONFLICT", False),
594
+ }:
595
+ return False
596
+ if value["kind"] == "clone" and (
597
+ value["state"] != "COMMITTED" or value["planId"] is not None
598
+ or set(value["collections"]) != {"mapping", "identityMappings", "resourceMapping", "metadata"}
599
+ or any(not isinstance(value["collections"].get(key), dict)
600
+ for key in value["collections"])
601
+ or any(value["collections"][key].get("kind") != "mapping"
602
+ for key in value["collections"])
603
+ ):
604
+ return False
605
+ for name, descriptor in value["collections"].items():
606
+ if (not isinstance(name, str) or not name or len(name) > 256
607
+ or name in fields or name in {"plan", "leaseId", "leaseExpiresAt"}
608
+ or not isinstance(descriptor, dict) or set(descriptor) != {"kind", "count"}
609
+ or not isinstance(descriptor["kind"], str) or descriptor["kind"] not in {"sequence", "mapping"}
610
+ or type(descriptor["count"]) is not int
611
+ or not 0 <= descriptor["count"] <= _MAX_SAFE_INTEGER):
612
+ return False
613
+ return True
614
+
615
+
616
+ def _valid_plan_observation(value: Any, envelope: dict[str, Any] | None = None) -> bool:
617
+ if (not isinstance(value, dict)
618
+ or set(value) != {"planId", "namespaceId", "state", "targetRevision", "expiresAt"}
619
+ or not isinstance(value["planId"], str) or not value["planId"]
620
+ or not isinstance(value["namespaceId"], str) or not value["namespaceId"]
621
+ or not isinstance(value["state"], str) or value["state"] not in {"ready", "applied", "cancelled", "expired"}
622
+ or type(value["targetRevision"]) is not int
623
+ or not 0 <= value["targetRevision"] <= _MAX_SAFE_INTEGER
624
+ or type(value["expiresAt"]) is not int or not 0 <= value["expiresAt"] <= _MAX_SAFE_INTEGER):
625
+ return False
626
+ return (envelope is None or (value["planId"] == envelope["planId"]
627
+ and value["namespaceId"] == envelope["namespaceId"]
628
+ and value["targetRevision"] == envelope["revision"]))
629
+
630
+
631
+ def valid_import_plan_wrapper(value: Any, *, plan_id: str | None = None,
632
+ namespace_id: str | None = None) -> bool:
633
+ if (not isinstance(value, dict) or set(value) != {"plan", "analysisResult"}
634
+ or not valid_import_result_envelope(value.get("analysisResult"))
635
+ or not _valid_plan_observation(value.get("plan"), value["analysisResult"])):
636
+ return False
637
+ envelope, plan = value["analysisResult"], value["plan"]
638
+ if (envelope["kind"] != "analysis" or envelope["state"] != "PLAN_READY"
639
+ or envelope["revision"] != plan["targetRevision"]):
640
+ return False
641
+ if plan_id is not None and plan["planId"] != plan_id:
642
+ return False
643
+ if namespace_id is not None and plan["namespaceId"] != namespace_id:
644
+ return False
645
+ return True