cloudsprite 0.11.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.
Files changed (70) hide show
  1. cloudsprite/__init__.py +451 -0
  2. cloudsprite/_antenna.py +83 -0
  3. cloudsprite/_auth.py +295 -0
  4. cloudsprite/_client.py +502 -0
  5. cloudsprite/_config.py +203 -0
  6. cloudsprite/_consent.py +104 -0
  7. cloudsprite/_context.py +945 -0
  8. cloudsprite/_exceptions.py +136 -0
  9. cloudsprite/_figure_models.py +158 -0
  10. cloudsprite/_figure_validation.py +168 -0
  11. cloudsprite/_filter_foster.py +165 -0
  12. cloudsprite/_filter_synthesis.py +400 -0
  13. cloudsprite/_filtering.py +134 -0
  14. cloudsprite/_impedance_matching.py +262 -0
  15. cloudsprite/_interpolation.py +47 -0
  16. cloudsprite/_lineage.py +775 -0
  17. cloudsprite/_link_budget.py +99 -0
  18. cloudsprite/_logging.py +53 -0
  19. cloudsprite/_mixed_mode.py +49 -0
  20. cloudsprite/_monte_carlo.py +193 -0
  21. cloudsprite/_noise_figure.py +44 -0
  22. cloudsprite/_pagination.py +130 -0
  23. cloudsprite/_parsers.py +75 -0
  24. cloudsprite/_publish.py +162 -0
  25. cloudsprite/_redact.py +179 -0
  26. cloudsprite/_response.py +63 -0
  27. cloudsprite/_resultset.py +65 -0
  28. cloudsprite/_rf_network.py +111 -0
  29. cloudsprite/_run_config.py +46 -0
  30. cloudsprite/_script_runner.py +217 -0
  31. cloudsprite/_script_workspace.py +271 -0
  32. cloudsprite/_sparameter_metrics.py +75 -0
  33. cloudsprite/_tdr.py +283 -0
  34. cloudsprite/_trace.py +112 -0
  35. cloudsprite/_version.py +23 -0
  36. cloudsprite/_visualizer.py +380 -0
  37. cloudsprite/_visualizer_cli.py +412 -0
  38. cloudsprite/_visualizer_preview.py +864 -0
  39. cloudsprite/_work_context.py +116 -0
  40. cloudsprite/_ws.py +577 -0
  41. cloudsprite/cli.py +300 -0
  42. cloudsprite/py.typed +0 -0
  43. cloudsprite/resources/__init__.py +1 -0
  44. cloudsprite/resources/_base.py +293 -0
  45. cloudsprite/resources/_models.py +50 -0
  46. cloudsprite/resources/cloudscripts.py +173 -0
  47. cloudsprite/resources/datasets.py +431 -0
  48. cloudsprite/resources/figures.py +282 -0
  49. cloudsprite/resources/instruments.py +295 -0
  50. cloudsprite/resources/notebooks.py +183 -0
  51. cloudsprite/resources/orbs.py +99 -0
  52. cloudsprite/resources/parameters.py +77 -0
  53. cloudsprite/resources/projects.py +182 -0
  54. cloudsprite/resources/related.py +125 -0
  55. cloudsprite/resources/reports.py +992 -0
  56. cloudsprite/resources/search.py +245 -0
  57. cloudsprite/resources/shares.py +229 -0
  58. cloudsprite/resources/sprites.py +15 -0
  59. cloudsprite/resources/tags.py +107 -0
  60. cloudsprite/resources/teams.py +86 -0
  61. cloudsprite/resources/traces.py +147 -0
  62. cloudsprite/resources/usage.py +152 -0
  63. cloudsprite/resources/visualizer_templates.py +466 -0
  64. cloudsprite/resources/workflows.py +59 -0
  65. cloudsprite-0.11.0.dist-info/METADATA +358 -0
  66. cloudsprite-0.11.0.dist-info/RECORD +70 -0
  67. cloudsprite-0.11.0.dist-info/WHEEL +5 -0
  68. cloudsprite-0.11.0.dist-info/entry_points.txt +3 -0
  69. cloudsprite-0.11.0.dist-info/licenses/LICENSE +21 -0
  70. cloudsprite-0.11.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,466 @@
1
+ """Visualizer templates: a registry of sandboxed HTML visualizers (CTS 0.1).
2
+
3
+ A template is one HTML file with a JSON manifest. Teams publish immutable
4
+ semver versions to the registry, install templates from other teams in their
5
+ organisation, and deprecate versions that should no longer be used. The API's
6
+ static reviewer checks every saved version; ``validate`` runs the same review
7
+ on a draft without saving anything.
8
+
9
+ Typical flow::
10
+
11
+ findings = cs.visualizer_templates.validate(source)
12
+ result = cs.visualizer_templates.publish(source, readme=readme_text)
13
+ result.version["semver"]
14
+
15
+ ``cloudsprite visualizer validate | preview | publish`` wraps these calls for
16
+ local authoring.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import builtins
22
+ from dataclasses import dataclass
23
+ from typing import TYPE_CHECKING, Any
24
+ from urllib.parse import quote
25
+
26
+ from cloudsprite._exceptions import ValidationError, validate_id
27
+ from cloudsprite._visualizer import (
28
+ README_MAX_BYTES,
29
+ SOURCE_MAX_BYTES,
30
+ Semver,
31
+ normalize_slug,
32
+ )
33
+ from cloudsprite.resources._base import Resource
34
+
35
+ if TYPE_CHECKING:
36
+ from cloudsprite._client import HTTPClient
37
+
38
+ _PAGE = 200
39
+ _CREATE_VISIBILITIES = ("private", "team") # org listing is requested in the app, never through the SDK
40
+ _SURFACES = ("interactive", "compact", "thumbnail", "print", "public", "export")
41
+ _TARGET_TYPES = ("dataset", "notebook")
42
+
43
+
44
+ def _object(value: Any) -> dict[str, Any]:
45
+ if not isinstance(value, dict):
46
+ raise ValidationError("Unexpected visualizer template API response; expected an object")
47
+ return value
48
+
49
+
50
+ def _items(value: Any) -> list[dict[str, Any]]:
51
+ if not isinstance(value, list) or any(not isinstance(item, dict) for item in value):
52
+ raise ValidationError("Unexpected visualizer template API response; expected an array of objects")
53
+ return value
54
+
55
+
56
+ def _source(source: str) -> str:
57
+ if not isinstance(source, str) or not source.strip():
58
+ raise ValidationError("source must be the template's HTML text")
59
+ if len(source.encode("utf-8", "surrogatepass")) > SOURCE_MAX_BYTES:
60
+ raise ValidationError(f"source is larger than the {SOURCE_MAX_BYTES}-byte template limit")
61
+ return source
62
+
63
+
64
+ def _readme(readme: str | None) -> str | None:
65
+ if readme is None:
66
+ return None
67
+ if not isinstance(readme, str):
68
+ raise ValidationError("readme must be a string")
69
+ if len(readme.encode("utf-8", "surrogatepass")) > README_MAX_BYTES:
70
+ raise ValidationError(f"readme is larger than {README_MAX_BYTES} bytes")
71
+ return readme
72
+
73
+
74
+ def _revision(value: int, name: str = "version") -> int:
75
+ if type(value) is not int or value < 1:
76
+ raise ValidationError(f"{name} must be a positive integer revision number")
77
+ return value
78
+
79
+
80
+ def _optional_revision(value: int | None, name: str) -> int | None:
81
+ return None if value is None else _revision(value, name)
82
+
83
+
84
+ class VisualizerTemplate(Resource):
85
+ """A registry template: package name, status, current version and (on ``get``) README."""
86
+
87
+ @property
88
+ def package_name(self) -> str:
89
+ """Registry package name, ``@<org>/<slug>``."""
90
+ return str(self._data["package_name"])
91
+
92
+ @property
93
+ def status(self) -> str:
94
+ """Lifecycle status such as ``active`` or ``deprecated``."""
95
+ return str(self._data["status"])
96
+
97
+ @property
98
+ def visibility(self) -> str:
99
+ """``private`` (creator), ``team`` or ``org`` (only while listed)."""
100
+ return str(self._data["visibility"])
101
+
102
+ @property
103
+ def current_version(self) -> dict[str, Any] | None:
104
+ """The newest saved version (``version`` revision number, ``semver``, ``status``), if any."""
105
+ value = self._data.get("current_version")
106
+ return value if isinstance(value, dict) else None
107
+
108
+ @property
109
+ def readme(self) -> str:
110
+ """README text; only present on templates fetched with ``get``."""
111
+ return str(self._data.get("readme", ""))
112
+
113
+ @property
114
+ def payload(self) -> dict[str, Any]:
115
+ """The complete API response for this template."""
116
+ return self._data
117
+
118
+
119
+ @dataclass(frozen=True)
120
+ class PublishResult:
121
+ """Outcome of ``publish``: whether the template was created, and the saved version."""
122
+
123
+ created: bool
124
+ template: VisualizerTemplate
125
+ version: dict[str, Any]
126
+
127
+
128
+ class VisualizerTemplateCollection:
129
+ """Visualizer template registry operations for the current team."""
130
+
131
+ def __init__(self, client: HTTPClient) -> None:
132
+ self._client = client
133
+
134
+ # ------------------------------------------------------------------ reads
135
+
136
+ def list(
137
+ self,
138
+ *,
139
+ q: str | None = None,
140
+ scope: str | None = None,
141
+ visibility: str | None = None,
142
+ status: str | None = None,
143
+ trashed: bool = False,
144
+ ) -> builtins.list[VisualizerTemplate]:
145
+ """List the templates you can see, following offset pagination.
146
+
147
+ ``q`` matches name, package name, description and tags. ``scope`` is
148
+ ``official`` or ``team``; ``visibility`` is ``private``, ``team`` or ``org``.
149
+ """
150
+ params: dict[str, Any] = {"offset": 0, "limit": _PAGE}
151
+ for key, value in (("q", q), ("scope", scope), ("visibility", visibility), ("status", status)):
152
+ if value is not None:
153
+ params[key] = value
154
+ if trashed:
155
+ params["trashed"] = True
156
+ result: builtins.list[VisualizerTemplate] = []
157
+ while True:
158
+ page = _items(self._client.get("/api/visualizer-templates/", params=params))
159
+ result.extend(VisualizerTemplate(self._client, item) for item in page)
160
+ if len(page) < _PAGE:
161
+ return result
162
+ params["offset"] += len(page)
163
+
164
+ def get(self, template_id: str) -> VisualizerTemplate:
165
+ """Fetch one template including its README."""
166
+ template_id = validate_id(template_id, "template_id")
167
+ return VisualizerTemplate(self._client, _object(self._client.get(f"/api/visualizer-templates/{template_id}/")))
168
+
169
+ def find(self, name: str, *, own: bool = False) -> VisualizerTemplate | None:
170
+ """Look a template up by package name (``@org/slug``) or bare name; ``None`` when absent.
171
+
172
+ A bare name is normalised to a slug the way the registry does. Raises
173
+ ``ValidationError`` when the name has no slug characters or a bare slug matches more than one
174
+ package. By default every template you can see is searched, official ones included. With
175
+ ``own=True`` only your own team's and org's templates are searched (the official registry is
176
+ excluded), which is the set ``publish`` matches against.
177
+ """
178
+ if not isinstance(name, str) or not name.strip():
179
+ raise ValidationError("name must be a package name such as '@org/my-template' or a template name")
180
+ text = name.strip()
181
+ scoped = text.startswith("@") and "/" in text
182
+ try:
183
+ slug = normalize_slug(text.split("/", 1)[1] if scoped else text)
184
+ except ValueError as exc:
185
+ raise ValidationError(str(exc)) from None
186
+ matches = []
187
+ for template in self.list(q=slug, scope="team" if own else None):
188
+ if own and template.payload.get("scope") == "official":
189
+ continue
190
+ package = template.package_name
191
+ if (scoped and package == text) or (not scoped and package.rsplit("/", 1)[-1] == slug):
192
+ matches.append(template)
193
+ if len(matches) > 1:
194
+ raise ValidationError(f"{name!r} matches several packages: " + ", ".join(t.package_name for t in matches))
195
+ return matches[0] if matches else None
196
+
197
+ def versions(self, template_id: str) -> builtins.list[dict[str, Any]]:
198
+ """List every saved version (``version`` revision number, ``semver``, ``status``, ``review_status``)."""
199
+ template_id = validate_id(template_id, "template_id")
200
+ params: dict[str, Any] = {"offset": 0, "limit": _PAGE}
201
+ result: builtins.list[dict[str, Any]] = []
202
+ while True:
203
+ page = _items(self._client.get(f"/api/visualizer-templates/{template_id}/versions/", params=params))
204
+ result.extend(page)
205
+ if len(page) < _PAGE:
206
+ return result
207
+ params["offset"] += len(page)
208
+
209
+ def get_version(self, template_id: str, version: int | str) -> dict[str, Any]:
210
+ """Fetch one version with its parsed manifest; ``version`` is a revision number or semver string."""
211
+ template_id = validate_id(template_id, "template_id")
212
+ number = self._number(template_id, version)
213
+ return _object(self._client.get(f"/api/visualizer-templates/{template_id}/versions/{number}/"))
214
+
215
+ def source(self, template_id: str, version: int | str) -> str:
216
+ """Fetch the HTML source of one version; ``version`` is a revision number or semver string."""
217
+ template_id = validate_id(template_id, "template_id")
218
+ number = self._number(template_id, version)
219
+ data = _object(self._client.get(f"/api/visualizer-templates/{template_id}/versions/{number}/source/"))
220
+ return str(data["source"])
221
+
222
+ def review(self, template_id: str, version: int | str) -> dict[str, Any]:
223
+ """Fetch the latest static review (verdict, findings) of one saved version."""
224
+ template_id = validate_id(template_id, "template_id")
225
+ number = self._number(template_id, version)
226
+ return _object(self._client.get(f"/api/visualizer-templates/{template_id}/versions/{number}/review/"))
227
+
228
+ def starters(self, engine: str | None = None) -> dict[str, Any]:
229
+ """Fetch the starter templates (``items`` with ``source``), optionally for one engine."""
230
+ params = {"engine": engine} if engine else None
231
+ return _object(self._client.get("/api/visualizer-templates/starters/", params=params))
232
+
233
+ def lib_manifest(self) -> dict[str, Any]:
234
+ """Fetch the allow-listed runtime libraries (``libs`` with id, version, sha256, sri)."""
235
+ return _object(self._client.get("/api/visualizer-templates/lib-manifest/"))
236
+
237
+ def installed(self) -> builtins.list[dict[str, Any]]:
238
+ """List the templates installed for your organisation."""
239
+ return _items(self._client.get("/api/visualizer-templates/installed/"))
240
+
241
+ def resolve(self, target_type: str, target_id: str, *, surface: str = "interactive") -> dict[str, Any]:
242
+ """Explain which visualizer the registry would pick for a dataset or notebook.
243
+
244
+ Returns the resolution, ranked candidates and an explanation. This reads
245
+ assignments and installs; it changes nothing.
246
+ """
247
+ if target_type not in _TARGET_TYPES:
248
+ raise ValidationError(f"target_type must be one of {', '.join(_TARGET_TYPES)}")
249
+ if surface not in _SURFACES:
250
+ raise ValidationError(f"surface must be one of {', '.join(_SURFACES)}")
251
+ target_id = validate_id(target_id, "target_id")
252
+ body = {"target_type": target_type, "target_id": target_id, "surface": surface}
253
+ return _object(self._client.post("/api/visualizer-templates/resolve/", json=body))
254
+
255
+ # ----------------------------------------------------------------- checks
256
+
257
+ def validate(self, source: str) -> dict[str, Any]:
258
+ """Run the static reviewer on a draft; nothing is saved.
259
+
260
+ Returns ``verdict`` (``pass``, ``warn``, ``block`` or ``suspect``),
261
+ ``can_publish``, ``findings`` (each with ``rule``, ``severity``,
262
+ ``message``, ``line``) and ``metrics``. A manifest the reviewer cannot
263
+ parse raises ``APIError`` with the findings in ``response_body``.
264
+ """
265
+ return _object(self._client.post("/api/visualizer-templates/validate/", json={"source": _source(source)}))
266
+
267
+ # ----------------------------------------------------------------- writes
268
+
269
+ def create(
270
+ self,
271
+ source: str,
272
+ *,
273
+ slug: str | None = None,
274
+ name: str | None = None,
275
+ description: str | None = None,
276
+ tags: builtins.list[str] | None = None,
277
+ when_to_use: str = "",
278
+ readme: str = "",
279
+ visibility: str = "team",
280
+ change_note: str = "",
281
+ ) -> VisualizerTemplate:
282
+ """Create a template with its first version from HTML source.
283
+
284
+ ``visibility`` is ``team`` (default) or ``private``; listing a template
285
+ for the whole organisation is requested in the app. ``slug``, ``name``
286
+ and ``description`` default to the manifest values.
287
+ """
288
+ if visibility not in _CREATE_VISIBILITIES:
289
+ raise ValidationError(f"visibility must be one of {', '.join(_CREATE_VISIBILITIES)}")
290
+ body: dict[str, Any] = {
291
+ "source": _source(source),
292
+ "tags": list(tags or []),
293
+ "when_to_use": when_to_use,
294
+ "readme": _readme(readme) or "",
295
+ "visibility": visibility,
296
+ "change_note": change_note,
297
+ "created_via": "sdk",
298
+ }
299
+ for key, value in (("slug", slug), ("name", name), ("description", description)):
300
+ if value is not None:
301
+ body[key] = value
302
+ return VisualizerTemplate(self._client, _object(self._client.post("/api/visualizer-templates/", json=body)))
303
+
304
+ def new_version(
305
+ self,
306
+ template_id: str,
307
+ source: str,
308
+ *,
309
+ change_note: str = "",
310
+ expected_version: int | None = None,
311
+ ) -> dict[str, Any]:
312
+ """Save a new immutable version; its manifest ``version`` must beat every earlier one.
313
+
314
+ ``expected_version`` is the revision you edited; a stale value fails with a conflict.
315
+ """
316
+ template_id = validate_id(template_id, "template_id")
317
+ body: dict[str, Any] = {"source": _source(source), "change_note": change_note}
318
+ body["expected_version"] = _optional_revision(expected_version, "expected_version")
319
+ return _object(self._client.post(f"/api/visualizer-templates/{template_id}/versions/", json=body))
320
+
321
+ def publish(
322
+ self,
323
+ source: str,
324
+ *,
325
+ template_id: str | None = None,
326
+ name: str | None = None,
327
+ readme: str | None = None,
328
+ change_note: str = "",
329
+ expected_version: int | None = None,
330
+ validate: bool = True,
331
+ ) -> PublishResult:
332
+ """Publish a template version, creating the template when the name is new.
333
+
334
+ Without ``template_id`` the registry matches ``name`` (``@org/slug`` or a
335
+ bare name; default: the manifest name) to a package in your organisation
336
+ and saves a new semver version, or creates the template with visibility
337
+ ``team``. With ``template_id`` it adds a version to that template. The
338
+ manifest ``version`` must be strictly greater than every earlier version.
339
+
340
+ With ``validate=True`` (default) the draft is reviewed first and a file the
341
+ reviewer blocks raises ``ValidationError`` (findings in ``response_body``)
342
+ instead of being saved as a blocked version.
343
+ """
344
+ if template_id is not None and name is not None:
345
+ raise ValidationError("pass template_id or name, not both")
346
+ source = _source(source)
347
+ readme = _readme(readme)
348
+ if template_id is not None:
349
+ template_id = validate_id(template_id, "template_id")
350
+ if validate:
351
+ self._require_publishable(source)
352
+ body: dict[str, Any] = {"source": source, "change_note": change_note}
353
+ body["expected_version"] = _optional_revision(expected_version, "expected_version")
354
+ if readme is not None:
355
+ body["readme"] = readme
356
+ if template_id is not None:
357
+ data = _object(self._client.post(f"/api/visualizer-templates/{template_id}/publish/", json=body))
358
+ else:
359
+ body["created_via"] = "sdk"
360
+ if name is not None:
361
+ body["name"] = name
362
+ data = _object(self._client.post("/api/visualizer-templates/publish/", json=body))
363
+ return PublishResult(
364
+ created=bool(data.get("created")),
365
+ template=VisualizerTemplate(self._client, _object(data["template"])),
366
+ version=_object(data["version"]),
367
+ )
368
+
369
+ def _require_publishable(self, source: str) -> None:
370
+ report = self.validate(source)
371
+ if not report.get("can_publish"):
372
+ blocking = [f for f in report.get("findings", []) if f.get("severity") == "block"]
373
+ lines = "; ".join(f"{f.get('rule')}: {f.get('message')}" for f in blocking) or "blocked by the reviewer"
374
+ raise ValidationError(f"The reviewer blocked this template: {lines}", response_body=report)
375
+
376
+ def fork(self, template_id: str, *, version: int | None = None, slug: str | None = None) -> VisualizerTemplate:
377
+ """Copy a template (one version, default the current one) into your team as a new template."""
378
+ template_id = validate_id(template_id, "template_id")
379
+ body: dict[str, Any] = {"version": _optional_revision(version, "version")}
380
+ if slug is not None:
381
+ body["slug"] = slug
382
+ return VisualizerTemplate(
383
+ self._client, _object(self._client.post(f"/api/visualizer-templates/{template_id}/fork/", json=body))
384
+ )
385
+
386
+ def delete(self, template_id: str) -> None:
387
+ """Move a template to the trash (idempotent). Requires update rights on it."""
388
+ template_id = validate_id(template_id, "template_id")
389
+ self._client.delete(f"/api/visualizer-templates/{template_id}/")
390
+
391
+ # ----------------------------------------------------- install, deprecate
392
+
393
+ def install(self, template_id: str, *, version_range: str = "", confirm_deprecated: bool = False) -> dict[str, Any]:
394
+ """Install a template for your organisation so teams can assign it (manager or above).
395
+
396
+ ``version_range`` is a semver range such as ``^1`` (empty: follow ``latest``). Installing
397
+ a deprecated template needs ``confirm_deprecated=True``.
398
+ """
399
+ template_id = validate_id(template_id, "template_id")
400
+ body = {"version_range": version_range, "confirm_deprecated": bool(confirm_deprecated)}
401
+ return _object(self._client.post(f"/api/visualizer-templates/{template_id}/install/", json=body))
402
+
403
+ def uninstall(self, template_id: str, *, remove_assignments: bool = False, migrate_to: str | None = None) -> None:
404
+ """Uninstall a template; ``migrate_to`` moves its assignments to another template id first."""
405
+ template_id = validate_id(template_id, "template_id")
406
+ flag = "true" if remove_assignments else "false"
407
+ move = "" if migrate_to is None else "&migrate_to=" + quote(validate_id(migrate_to, "migrate_to"), safe="")
408
+ # HTTPClient.delete takes no params argument, so the query string rides on the path.
409
+ self._client.delete(f"/api/visualizer-templates/{template_id}/install/?remove_assignments={flag}{move}")
410
+
411
+ def deprecate(
412
+ self,
413
+ template_id: str,
414
+ message: str,
415
+ *,
416
+ version: int | str | None = None,
417
+ replaced_by: str | None = None,
418
+ ) -> VisualizerTemplate | dict[str, Any]:
419
+ """Deprecate a whole template, or one version (revision number or semver string).
420
+
421
+ ``replaced_by`` (template deprecation only) names the replacement template id.
422
+ Returns the template, or the version when ``version`` is given.
423
+ """
424
+ template_id = validate_id(template_id, "template_id")
425
+ if not isinstance(message, str) or not message.strip():
426
+ raise ValidationError("message must explain the deprecation")
427
+ if version is not None:
428
+ if replaced_by is not None:
429
+ raise ValidationError("replaced_by applies to a whole template, not one version")
430
+ number = self._number(template_id, version)
431
+ return _object(
432
+ self._client.post(
433
+ f"/api/visualizer-templates/{template_id}/versions/{number}/deprecate/", json={"message": message}
434
+ )
435
+ )
436
+ body: dict[str, Any] = {"message": message, "replaced_by": replaced_by}
437
+ return VisualizerTemplate(
438
+ self._client, _object(self._client.post(f"/api/visualizer-templates/{template_id}/deprecate/", json=body))
439
+ )
440
+
441
+ def clear_deprecation(
442
+ self, template_id: str, *, version: int | str | None = None
443
+ ) -> VisualizerTemplate | dict[str, Any]:
444
+ """Remove a deprecation from a template, or from one version (revision number or semver)."""
445
+ template_id = validate_id(template_id, "template_id")
446
+ if version is not None:
447
+ number = self._number(template_id, version)
448
+ return _object(self._client.delete(f"/api/visualizer-templates/{template_id}/versions/{number}/deprecate/"))
449
+ return VisualizerTemplate(
450
+ self._client, _object(self._client.delete(f"/api/visualizer-templates/{template_id}/deprecate/"))
451
+ )
452
+
453
+ # ---------------------------------------------------------------- helpers
454
+
455
+ def _number(self, template_id: str, version: int | str) -> int:
456
+ """A revision number, resolving a semver string through the version list."""
457
+ if isinstance(version, str):
458
+ try:
459
+ wanted = str(Semver.parse(version))
460
+ except ValueError as exc:
461
+ raise ValidationError(str(exc)) from None
462
+ for row in self.versions(template_id):
463
+ if row.get("semver") == wanted:
464
+ return _revision(int(row["version"]))
465
+ raise ValidationError(f"Template has no version {wanted}")
466
+ return _revision(version)
@@ -0,0 +1,59 @@
1
+ """Workflow and workflow-run resources (beta).
2
+
3
+ Read-only run inspection plus enough workflow identity to list runs.
4
+ Create/enable/disable stay out of this first slice.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from cloudsprite.resources._base import Resource, ResourceCollection
10
+
11
+
12
+ class WorkflowRun(Resource):
13
+ """One execution of a workflow (beta)."""
14
+
15
+ @property
16
+ def workflow_id(self) -> str:
17
+ """Owning workflow UUID."""
18
+ return str(self._data.get("workflow_id", ""))
19
+
20
+ @property
21
+ def status(self) -> str:
22
+ """Run status (queued, running, succeeded, failed, …)."""
23
+ return str(self._data.get("status", ""))
24
+
25
+
26
+ class Workflow(Resource):
27
+ """A project-scoped automation workflow (beta).
28
+
29
+ This slice exposes identity + ``runs``. Mutating workflow CRUD is next.
30
+
31
+ Example::
32
+
33
+ wf = project.workflows["nightly-sweep"]
34
+ for run in wf.runs:
35
+ print(run.status)
36
+ """
37
+
38
+ @property
39
+ def project_id(self) -> str:
40
+ """Owning project UUID."""
41
+ return str(self._data.get("project_id", ""))
42
+
43
+ @property
44
+ def is_enabled(self) -> bool:
45
+ """True when triggers may fire."""
46
+ return bool(self._data.get("is_enabled", False))
47
+
48
+ @property
49
+ def runs(self) -> ResourceCollection[WorkflowRun]:
50
+ """Runs of this workflow.
51
+
52
+ Server: ``GET /api/workflows/{id}/runs/``.
53
+ """
54
+ return ResourceCollection(
55
+ self._client,
56
+ f"/api/workflows/{self.id}/runs/",
57
+ WorkflowRun,
58
+ name_field="id",
59
+ )