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,412 @@
1
+ """``cloudsprite visualizer validate | preview | publish``: author visualizer templates locally.
2
+
3
+ Exit codes: 0 success; 1 a blocked template, a refused publish or any command error;
4
+ 2 usage errors (argparse).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ import os
12
+ import sys
13
+ import tempfile
14
+ from collections.abc import Callable
15
+ from pathlib import Path
16
+ from typing import TYPE_CHECKING, Any, TextIO
17
+
18
+ from cloudsprite._exceptions import APIError, CloudSpriteError, ValidationError
19
+ from cloudsprite._visualizer import (
20
+ BUMP_PARTS,
21
+ SOURCE_MAX_BYTES,
22
+ Semver,
23
+ check_source,
24
+ has_blocking,
25
+ highest_semver,
26
+ manifest_version,
27
+ parse_manifest,
28
+ set_manifest_version,
29
+ )
30
+
31
+ if TYPE_CHECKING:
32
+ from cloudsprite._context import Client
33
+ from cloudsprite._visualizer_preview import PreviewServer
34
+
35
+ DEFAULT_PORT = 8765
36
+ _READ_CAP = SOURCE_MAX_BYTES * 8 # refuse absurd files before decoding; the 1 MiB rule is the findings' job
37
+
38
+
39
+ def connect_client() -> Client:
40
+ """A connected default ``Client`` (credentials and scope from config)."""
41
+ from cloudsprite._context import Client
42
+
43
+ cs = Client()
44
+ cs.connect()
45
+ return cs
46
+
47
+
48
+ def add_parser(sub: Any) -> None:
49
+ """Register the ``visualizer`` command group on the top-level subparsers."""
50
+ viz = sub.add_parser(
51
+ "visualizer",
52
+ help="Validate, preview and publish visualizer templates",
53
+ description="Author visualizer templates (CTS 0.1) locally: validate, preview on real or sample data, publish.",
54
+ )
55
+ actions = viz.add_subparsers(dest="visualizer_command", metavar="{validate,preview,publish}")
56
+
57
+ validate = actions.add_parser(
58
+ "validate",
59
+ help="Check a template file with the local rules and the API reviewer",
60
+ description="Run basic offline manifest checks, then the API's static reviewer. Exit 1 on a blocking finding.",
61
+ )
62
+ validate.add_argument("file", help="Template HTML file")
63
+ validate.add_argument("--offline", action="store_true", help="Only run the local checks (no API call)")
64
+ validate.add_argument("--json", action="store_true", help="Print one JSON document instead of text")
65
+
66
+ preview = actions.add_parser(
67
+ "preview",
68
+ help="Serve a local, sandboxed preview of a template",
69
+ description=(
70
+ "Render the template with the real cs runtime in a sandboxed iframe on http://127.0.0.1, "
71
+ "against sample data (default), a data file, or a dataset downloaded through the SDK. "
72
+ "Reload the page to pick up edits. Stop with Ctrl-C."
73
+ ),
74
+ )
75
+ preview.add_argument("file", help="Template HTML file")
76
+ source = preview.add_mutually_exclusive_group()
77
+ source.add_argument("--dataset", metavar="ID", help="Download this dataset's traces and preview on them")
78
+ source.add_argument("--data", metavar="FILE", help='JSON file: {"channels": [{"label", "x": [...], "y": [...]}]}')
79
+ source.add_argument(
80
+ "--sample",
81
+ choices=("sparameters", "time-domain"),
82
+ help="Synthetic data (default: chosen from the manifest's accepts.domains)",
83
+ )
84
+ preview.add_argument(
85
+ "--port", type=int, default=DEFAULT_PORT, help=f"Port on 127.0.0.1 (default {DEFAULT_PORT}; 0 = any)"
86
+ )
87
+ preview.add_argument(
88
+ "--surface",
89
+ default="interactive",
90
+ help="Initial surface (interactive, compact, thumbnail, print, public, export)",
91
+ )
92
+ preview.add_argument("--theme", default="light", choices=("light", "dark"), help="Initial theme")
93
+ preview.add_argument("--width", type=int, help="Frame width in px (default: per surface)")
94
+ preview.add_argument("--height", type=int, help="Frame height in px (default: per surface)")
95
+ preview.add_argument("--open", action="store_true", help="Open the preview in your browser")
96
+ preview.add_argument("--no-validate", action="store_true", help="Skip the API reviewer panel")
97
+
98
+ publish = actions.add_parser(
99
+ "publish",
100
+ help="Publish a template as a new team template or a new semver version",
101
+ description=(
102
+ "Validate, then create the template (visibility team) or save a strictly higher semver version. "
103
+ "A file the reviewer blocks, or a version that does not increase, is refused. "
104
+ "Listing a template for the whole organisation is requested in the app."
105
+ ),
106
+ )
107
+ publish.add_argument("file", help="Template HTML file")
108
+ publish.add_argument("--bump", choices=BUMP_PARTS, help="Raise the manifest version from the highest published one")
109
+ publish.add_argument("--readme", metavar="FILE", help="README.md to store with the template")
110
+ publish.add_argument("--name", help="Package name (@org/slug or a bare name); default: the manifest name")
111
+ publish.add_argument("--change-note", default="", help="Short note recorded with the version")
112
+ publish.add_argument("--dry-run", action="store_true", help="Check everything and print what would be published")
113
+
114
+
115
+ def run(args: argparse.Namespace, *, client_factory: Callable[[], Client] | None = None) -> int:
116
+ """Dispatch a parsed ``visualizer`` command; returns the process exit code."""
117
+ factory = client_factory or connect_client
118
+ command = getattr(args, "visualizer_command", None)
119
+ handlers: dict[str, Callable[..., int]] = {"validate": run_validate, "preview": run_preview, "publish": run_publish}
120
+ if command not in handlers:
121
+ print("usage: cloudsprite visualizer {validate,preview,publish} ...", file=sys.stderr)
122
+ return 1
123
+ try:
124
+ return handlers[command](args, factory)
125
+ except CloudSpriteError as exc:
126
+ _print_error(exc)
127
+ return 1
128
+
129
+
130
+ # --------------------------------------------------------------------------- shared
131
+
132
+
133
+ def _print_error(exc: CloudSpriteError) -> None:
134
+ print(f"Error: {exc}", file=sys.stderr)
135
+ body = getattr(exc, "response_body", None)
136
+ findings = body.get("findings") if isinstance(body, dict) else None
137
+ if isinstance(findings, list):
138
+ for finding in findings:
139
+ if isinstance(finding, dict):
140
+ print(f" {_finding_line(finding)}", file=sys.stderr)
141
+
142
+
143
+ def _finding_line(finding: dict[str, Any], file: str | None = None) -> str:
144
+ severity = str(finding.get("severity") or "block")
145
+ rule = str(finding.get("rule", ""))
146
+ where = ""
147
+ if finding.get("line"):
148
+ where = f"{file}:{finding['line']}: " if file else f"line {finding['line']}: "
149
+ elif finding.get("pointer"):
150
+ where = f"{finding['pointer']}: "
151
+ return f"{severity:<5} {rule:<11} {where}{finding.get('message', '')}"
152
+
153
+
154
+ def _read_text(path_text: str, what: str = "template") -> str:
155
+ path = Path(path_text)
156
+ try:
157
+ if path.stat().st_size > _READ_CAP:
158
+ raise ValidationError(f"{path} is too large to be a {what}")
159
+ return path.read_text(encoding="utf-8")
160
+ except (OSError, UnicodeDecodeError) as exc:
161
+ raise ValidationError(f"Cannot read {what} {path}: {exc}") from None
162
+
163
+
164
+ def _print_findings(findings: list[dict[str, Any]], file: str, out: TextIO) -> None:
165
+ for finding in findings:
166
+ print(_finding_line(finding, file), file=out)
167
+
168
+
169
+ def _reviewer_report(cs: Client, source: str) -> tuple[dict[str, Any] | None, list[dict[str, Any]], str]:
170
+ """``(report, findings, note)``: the API verdict, or the findings of a manifest it could not parse."""
171
+ try:
172
+ report = cs.visualizer_templates.validate(source)
173
+ except APIError as exc:
174
+ body = exc.response_body if isinstance(exc.response_body, dict) else {}
175
+ findings = [f for f in body.get("findings", []) if isinstance(f, dict)]
176
+ if exc.status_code in (400, 413) and findings:
177
+ return None, [{**f, "severity": "block"} for f in findings], ""
178
+ raise
179
+ return report, [f for f in report.get("findings", []) if isinstance(f, dict)], ""
180
+
181
+
182
+ # --------------------------------------------------------------------------- validate
183
+
184
+
185
+ def run_validate(args: argparse.Namespace, client_factory: Callable[[], Client], out: TextIO | None = None) -> int:
186
+ """``validate``: local checks, then the reviewer unless ``--offline`` or a local blocker."""
187
+ out = out or sys.stdout
188
+ source = _read_text(args.file)
189
+ local = check_source(source)
190
+ report: dict[str, Any] | None = None
191
+ reviewer: list[dict[str, Any]] = []
192
+ skipped = ""
193
+ if args.offline:
194
+ skipped = "offline: the API reviewer was not run"
195
+ elif has_blocking(local):
196
+ skipped = "the API reviewer was not run: fix the blocking local findings first"
197
+ else:
198
+ report, reviewer, _ = _reviewer_report(client_factory(), source)
199
+ seen = {f.get("rule") for f in reviewer}
200
+ shown = [f for f in local if f.get("rule") not in seen] + reviewer
201
+ can_publish = (
202
+ (not has_blocking(shown)) if report is None else bool(report.get("can_publish")) and not has_blocking(local)
203
+ )
204
+ if args.json:
205
+ json.dump(
206
+ {
207
+ "file": args.file,
208
+ "findings": shown,
209
+ "reviewer": report,
210
+ "reviewer_run": report is not None or bool(reviewer),
211
+ "can_publish": can_publish,
212
+ "note": skipped,
213
+ },
214
+ out,
215
+ indent=2,
216
+ )
217
+ out.write("\n")
218
+ return 0 if can_publish else 1
219
+ _print_findings(shown, args.file, out)
220
+ if skipped:
221
+ print(f"note: {skipped}", file=out)
222
+ verdict = report.get("verdict") if report else ("block" if has_blocking(shown) else "pass")
223
+ print(f"{args.file}: {verdict}" + (" (can publish)" if can_publish else " (cannot publish)"), file=out)
224
+ return 0 if can_publish else 1
225
+
226
+
227
+ # --------------------------------------------------------------------------- publish
228
+
229
+
230
+ def _atomic_write(path: Path, text: str) -> None:
231
+ fd, tmp = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
232
+ try:
233
+ with os.fdopen(fd, "w", encoding="utf-8", newline="") as handle:
234
+ handle.write(text)
235
+ try:
236
+ os.chmod(tmp, path.stat().st_mode & 0o777)
237
+ except OSError:
238
+ pass
239
+ os.replace(tmp, path)
240
+ except BaseException:
241
+ try:
242
+ os.unlink(tmp)
243
+ except OSError:
244
+ pass
245
+ raise
246
+
247
+
248
+ def run_publish(args: argparse.Namespace, client_factory: Callable[[], Client], out: TextIO | None = None) -> int:
249
+ """``publish``: refuse blocked files and non-increasing versions, then create or add a version."""
250
+ out = out or sys.stdout
251
+ source = _read_text(args.file)
252
+ local = check_source(source)
253
+ _print_findings([f for f in local if f.get("severity") != "info"], args.file, out)
254
+ if has_blocking(local):
255
+ print(f"{args.file}: blocked by local checks; nothing published", file=sys.stderr)
256
+ return 1
257
+ readme = _read_text(args.readme, "README") if args.readme else None
258
+
259
+ cs = client_factory()
260
+ templates = cs.visualizer_templates
261
+ manifest, _ = parse_manifest(source)
262
+ name = args.name or str((manifest or {}).get("name") or "")
263
+ existing = templates.find(name, own=True) # publish matches inside your own tenant, never official templates
264
+ published = [str(v.get("semver", "")) for v in templates.versions(existing.id)] if existing else []
265
+ highest = highest_semver(published)
266
+ current = manifest_version(source)
267
+ bumped = False
268
+ if args.bump:
269
+ if existing is None:
270
+ print(f"note: {name!r} is not published yet; --bump ignored, publishing version {current}", file=out)
271
+ else:
272
+ floor = (
273
+ Semver.parse(highest)
274
+ if highest and Semver.parse(current) <= Semver.parse(highest)
275
+ else Semver.parse(current)
276
+ )
277
+ try:
278
+ new_version = str(floor.bump(args.bump))
279
+ except ValueError as exc:
280
+ raise ValidationError(str(exc)) from None
281
+ try:
282
+ source = set_manifest_version(source, new_version)
283
+ except ValueError as exc:
284
+ raise ValidationError(str(exc)) from None
285
+ current, bumped = new_version, True
286
+ elif highest and Semver.parse(current) <= Semver.parse(highest):
287
+ print(
288
+ f"Error: version {current} must be greater than the highest published version {highest}; "
289
+ "edit the manifest or use --bump patch|minor|major",
290
+ file=sys.stderr,
291
+ )
292
+ return 1
293
+
294
+ target = existing.package_name if existing else (name if name.startswith("@") else f"(new) {name}")
295
+ if args.dry_run:
296
+ print(
297
+ f"dry run: would publish {target} version {current}" + (f" (bumped from {highest})" if bumped else ""),
298
+ file=out,
299
+ )
300
+ return 0
301
+
302
+ expected = existing.current_version["version"] if existing and existing.current_version else None
303
+ result = templates.publish(
304
+ source,
305
+ name=args.name,
306
+ readme=readme,
307
+ change_note=args.change_note,
308
+ expected_version=expected,
309
+ validate=True,
310
+ )
311
+ if bumped:
312
+ _atomic_write(Path(args.file).resolve(), source) # follow a symlink instead of replacing it
313
+ print(f"Updated {args.file}: manifest version is now {current}", file=out)
314
+ version = result.version
315
+ verb = "Created" if result.created else "Published new version of"
316
+ print(
317
+ f"{verb} {result.template.package_name}@{version.get('semver')} "
318
+ f"(revision {version.get('version')}, status {version.get('status')}, review {version.get('review_status')})",
319
+ file=out,
320
+ )
321
+ if str(version.get("status")) in {"blocked", "suspect"}:
322
+ print(
323
+ "warning: the reviewer held this version; run `cloudsprite visualizer validate` for the findings",
324
+ file=sys.stderr,
325
+ )
326
+ print("Visibility: team. Listing the template for your organisation is requested in the app.", file=out)
327
+ return 0
328
+
329
+
330
+ # --------------------------------------------------------------------------- preview
331
+
332
+
333
+ def build_preview_server(args: argparse.Namespace, cs: Client, out: TextIO | None = None) -> PreviewServer:
334
+ """Assemble (but do not start serving) the preview server for parsed ``preview`` arguments."""
335
+ from cloudsprite import _visualizer_preview as pv
336
+
337
+ out = out or sys.stdout
338
+ path = Path(args.file)
339
+ source = _read_text(args.file)
340
+ manifest, _ = parse_manifest(source)
341
+ local = check_source(source)
342
+ _print_findings([f for f in local if f.get("severity") != "info"], args.file, out)
343
+
344
+ if args.surface not in pv.SURFACES:
345
+ raise ValidationError(f"--surface must be one of {', '.join(pv.SURFACES)}")
346
+ size = (args.width, args.height) if args.width and args.height else None
347
+ if (args.width or args.height) and size is None:
348
+ raise ValidationError("pass both --width and --height")
349
+ if size and not all(64 <= d <= 4000 for d in size):
350
+ raise ValidationError("--width and --height must be between 64 and 4000")
351
+
352
+ if args.dataset:
353
+ data = pv.dataset_data(cs, args.dataset)
354
+ elif args.data:
355
+ data = pv.file_data(Path(args.data))
356
+ else:
357
+ data = pv.sample_data(args.sample or pv.default_sample_kind(manifest))
358
+
359
+ origin = pv.usercontent_origin(cs.client._config.base_url)
360
+ try:
361
+ lib_manifest: dict[str, Any] | None = cs.visualizer_templates.lib_manifest()
362
+ except CloudSpriteError as exc:
363
+ lib_manifest = None
364
+ print(f"note: could not read the lib manifest ({exc}); libraries load without a hash check", file=sys.stderr)
365
+ cache_dir = Path.home() / ".cloudsprite" / "cache" / "visualizer-lib"
366
+ libs = pv.LibraryCache(origin, lib_manifest, cache_dir=cache_dir, warn=lambda m: print(m, file=sys.stderr))
367
+
368
+ reviewer: list[dict[str, Any]] | None = None
369
+ note = "skipped (--no-validate)" if args.no_validate else ""
370
+ if not args.no_validate:
371
+ if has_blocking(local):
372
+ note = "not run: the template has blocking local findings"
373
+ else:
374
+ try:
375
+ _, reviewer, _ = _reviewer_report(cs, source)
376
+ except CloudSpriteError as exc:
377
+ note = f"unavailable: {exc}"
378
+ return pv.PreviewServer(
379
+ path,
380
+ data,
381
+ libs,
382
+ port=args.port,
383
+ size=size,
384
+ reviewer=reviewer,
385
+ reviewer_note=note,
386
+ default_surface=args.surface,
387
+ default_theme=args.theme,
388
+ )
389
+
390
+
391
+ def run_preview(args: argparse.Namespace, client_factory: Callable[[], Client], out: TextIO | None = None) -> int:
392
+ """``preview``: serve until interrupted."""
393
+ out = out or sys.stdout
394
+ cs = client_factory()
395
+ try:
396
+ server = build_preview_server(args, cs, out)
397
+ except OSError as exc:
398
+ print(f"Error: cannot start the preview server on port {args.port}: {exc}", file=sys.stderr)
399
+ return 1
400
+ print(f"Previewing {args.file} on {server.data.label}", file=out)
401
+ print(f" {server.url} (Ctrl-C to stop; reload the page after editing the file)", file=out)
402
+ if args.open:
403
+ import webbrowser
404
+
405
+ webbrowser.open(server.url)
406
+ try:
407
+ server.serve_forever()
408
+ except KeyboardInterrupt:
409
+ pass
410
+ finally:
411
+ server.server_close()
412
+ return 0