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
cloudsprite/_config.py ADDED
@@ -0,0 +1,203 @@
1
+ """Configuration loading: explicit → env var → TOML config file.
2
+
3
+ Supports three-tier credential resolution and enforces security defaults
4
+ (HTTPS-only connections unless explicitly overridden for local development).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import stat
11
+ import tempfile
12
+ import tomllib
13
+ from pathlib import Path
14
+ from typing import Any, cast
15
+
16
+ from cloudsprite._exceptions import AuthError, ValidationError
17
+
18
+ DEFAULT_BASE_URL = "https://api.cloudsprite.io"
19
+ CONFIG_DIR_NAME = ".cloudsprite"
20
+ CONFIG_FILE_NAME = "config"
21
+
22
+ # Owner-only modes: no group/other read/write/execute bits.
23
+ _INSECURE_BITS = stat.S_IRWXG | stat.S_IRWXO # 0o077
24
+
25
+ _NO_API_KEY_MESSAGE = """No API key found.
26
+
27
+ Set up credentials using one of these methods:
28
+
29
+ 1. Run: cloudsprite init
30
+ 2. Set environment variable: export CLOUDSPRITE_API_KEY=csk_your_key
31
+ 3. Pass directly: cs.connect(api_key="csk_your_key")
32
+
33
+ Get your API key at https://cloudsprite.io/settings/api-keys"""
34
+
35
+
36
+ def _posix_mode_insecure(path: Path) -> bool:
37
+ """True if path is group- or world-accessible (POSIX only)."""
38
+ if os.name == "nt":
39
+ return False
40
+ mode = path.stat().st_mode
41
+ return bool(mode & _INSECURE_BITS)
42
+
43
+
44
+ def _check_config_permissions(config_path: Path) -> None:
45
+ """Refuse to load a config file (or parent dir) that is group/world accessible.
46
+
47
+ POSIX only — Windows has no meaningful file mode bits for this check.
48
+ """
49
+ if os.name == "nt":
50
+ return
51
+
52
+ config_dir = config_path.parent
53
+ if config_dir.exists() and _posix_mode_insecure(config_dir):
54
+ mode = stat.S_IMODE(config_dir.stat().st_mode)
55
+ raise AuthError(
56
+ f"Config directory has insecure permissions ({oct(mode)}): {config_dir}\n"
57
+ "The directory must not be group- or world-accessible because it holds "
58
+ "API credentials.\n"
59
+ f"Fix with: chmod 700 {config_dir}"
60
+ )
61
+
62
+ if _posix_mode_insecure(config_path):
63
+ mode = stat.S_IMODE(config_path.stat().st_mode)
64
+ raise AuthError(
65
+ f"Config file has insecure permissions ({oct(mode)}): {config_path}\n"
66
+ "A world- or group-readable config can leak your API key.\n"
67
+ f"Fix with: chmod 600 {config_path}"
68
+ )
69
+
70
+
71
+ class Config:
72
+ """SDK configuration with three-tier credential resolution.
73
+
74
+ Security:
75
+ - API key is stored as a private attribute (_api_key)
76
+ - HTTPS is enforced by default; http:// requires allow_insecure=True
77
+ - Config file permissions are validated on load (POSIX: refuse if
78
+ group/world accessible; no-op on Windows)
79
+ """
80
+
81
+ def __init__(
82
+ self,
83
+ api_key: str | None = None,
84
+ base_url: str | None = None,
85
+ allow_insecure: bool = False,
86
+ ):
87
+ self._explicit_key = api_key
88
+ self._explicit_url = base_url
89
+ self._allow_insecure = allow_insecure
90
+ self._file_config = self._load_config_file()
91
+
92
+ self._api_key = self._resolve_api_key()
93
+ self.base_url = self._resolve_base_url()
94
+
95
+ # Enforce HTTPS unless explicitly allowed for local dev
96
+ if not self._allow_insecure and self.base_url.startswith("http://"):
97
+ # Allow localhost/127.0.0.1 for local development
98
+ host = self.base_url.replace("http://", "").split("/")[0].split(":")[0]
99
+ if host not in ("localhost", "127.0.0.1", "0.0.0.0"):
100
+ raise ValidationError(
101
+ f"Insecure connection rejected: {self.base_url}\n"
102
+ "CloudSprite requires HTTPS for all connections. "
103
+ "Use allow_insecure=True only for local development."
104
+ )
105
+
106
+ @property
107
+ def api_key(self) -> str | None:
108
+ """API key (read-only property to prevent accidental exposure)."""
109
+ return self._api_key
110
+
111
+ def require_api_key(self) -> str:
112
+ if not self._api_key:
113
+ raise AuthError(_NO_API_KEY_MESSAGE)
114
+ return self._api_key
115
+
116
+ @property
117
+ def org(self) -> str | None:
118
+ """Default org (tenant) slug from the config file, if set."""
119
+ raw = self._file_config.get("org")
120
+ if raw is None or raw == "":
121
+ return None
122
+ return str(raw)
123
+
124
+ @property
125
+ def team(self) -> str | None:
126
+ """Default team slug from the config file, if set."""
127
+ raw = self._file_config.get("team")
128
+ if raw is None or raw == "":
129
+ return None
130
+ return str(raw)
131
+
132
+ def _resolve_api_key(self) -> str | None:
133
+ if self._explicit_key:
134
+ return self._explicit_key
135
+ env_key = os.environ.get("CLOUDSPRITE_API_KEY")
136
+ if env_key:
137
+ return env_key
138
+ return self._file_config.get("api_key")
139
+
140
+ def _resolve_base_url(self) -> str:
141
+ if self._explicit_url:
142
+ return self._explicit_url.rstrip("/")
143
+ env_url = os.environ.get("CS_API_BASE_URL") or os.environ.get("CLOUDSPRITE_BASE_URL")
144
+ if env_url:
145
+ return env_url.rstrip("/")
146
+ file_url = self._file_config.get("base_url")
147
+ if file_url:
148
+ return str(file_url).rstrip("/")
149
+ return DEFAULT_BASE_URL
150
+
151
+ def _load_config_file(self) -> dict[str, Any]:
152
+ config_path = Path.home() / CONFIG_DIR_NAME / CONFIG_FILE_NAME
153
+ if not config_path.exists():
154
+ return {}
155
+ _check_config_permissions(config_path)
156
+ with open(config_path, "rb") as f:
157
+ data = tomllib.load(f)
158
+ default = data.get("default", {})
159
+ return cast(dict[str, Any], default if isinstance(default, dict) else {})
160
+
161
+
162
+ def write_secure_file(path: Path, content: str) -> None:
163
+ """Write *content* to *path* without ever exposing wider-than-0600 perms.
164
+
165
+ Creates a temp file in the same directory with mode 0600 (POSIX), writes,
166
+ then atomically replaces the destination. On Windows, mode bits are ignored
167
+ by the OS; we still use the same atomic replace path.
168
+ """
169
+ directory = path.parent
170
+ fd = None
171
+ tmp_name = None
172
+ try:
173
+ # O_EXCL prevents clobbering an existing temp name; mode 0o600 is set
174
+ # at creation time so the file never exists at umask defaults.
175
+ fd, tmp_name = tempfile.mkstemp(
176
+ prefix=f".{path.name}.",
177
+ suffix=".tmp",
178
+ dir=directory,
179
+ )
180
+ if os.name != "nt":
181
+ os.fchmod(fd, 0o600)
182
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
183
+ fd = None # ownership transferred to the file object
184
+ f.write(content)
185
+ f.flush()
186
+ os.fsync(f.fileno())
187
+ os.replace(tmp_name, path)
188
+ tmp_name = None
189
+ if os.name != "nt":
190
+ # Ensure final path is 0600 even if replace preserved an older mode
191
+ # on some platforms (defensive; replace normally keeps source mode).
192
+ path.chmod(0o600)
193
+ finally:
194
+ if fd is not None:
195
+ try:
196
+ os.close(fd)
197
+ except OSError:
198
+ pass
199
+ if tmp_name is not None:
200
+ try:
201
+ os.unlink(tmp_name)
202
+ except OSError:
203
+ pass
@@ -0,0 +1,104 @@
1
+ """One-time consent for uploading CloudScript source, stored in the user config.
2
+
3
+ The answer lives in ``~/.cloudsprite/config`` (the file ``cloudsprite init`` writes)::
4
+
5
+ [privacy]
6
+ upload_source = true
7
+
8
+ Resolution order, first match wins (see ``_lineage.LineageTracker``):
9
+
10
+ 1. ``cs.cloudscript(upload_source=True/False)``
11
+ 2. ``CLOUDSPRITE_NO_TELEMETRY`` or ``CLOUDSPRITE_NO_SOURCE_UPLOAD`` set: no upload
12
+ 3. ``CLOUDSPRITE_UPLOAD_SOURCE`` (``1/true/yes/on`` or ``0/false/no/off``)
13
+ 4. A CloudSprite cloud run (``CS_RUN_TOKEN`` set by the script runner): upload
14
+ 5. The stored answer
15
+ 6. Interactive session: ask once, store the answer
16
+ 7. Otherwise: no upload and one notice per process
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import os
22
+ import re
23
+ import sys
24
+ import tomllib
25
+ from pathlib import Path
26
+
27
+ from cloudsprite._config import CONFIG_DIR_NAME, CONFIG_FILE_NAME, write_secure_file
28
+
29
+ ENV_UPLOAD_SOURCE = "CLOUDSPRITE_UPLOAD_SOURCE"
30
+ PROMPT = "Upload this script's source to CloudSprite for run lineage? [y/N] "
31
+
32
+ _TRUE = ("1", "true", "yes", "on")
33
+ _FALSE = ("0", "false", "no", "off")
34
+ _SECTION_RE = re.compile(r"(?ms)^\[privacy\][ \t]*\n.*?(?=^\[|\Z)")
35
+
36
+
37
+ def config_path() -> Path:
38
+ return Path.home() / CONFIG_DIR_NAME / CONFIG_FILE_NAME
39
+
40
+
41
+ def env_choice() -> bool | None:
42
+ """``CLOUDSPRITE_UPLOAD_SOURCE`` as a bool, or None when unset or not a recognised value."""
43
+ value = os.environ.get(ENV_UPLOAD_SOURCE, "").strip().lower()
44
+ if value in _TRUE:
45
+ return True
46
+ if value in _FALSE:
47
+ return False
48
+ return None
49
+
50
+
51
+ def stored_answer(path: Path | None = None) -> bool | None:
52
+ """The saved yes/no, or None when there is none (or the file cannot be read)."""
53
+ try:
54
+ with open(path or config_path(), "rb") as f:
55
+ section = tomllib.load(f).get("privacy")
56
+ except (OSError, tomllib.TOMLDecodeError):
57
+ return None
58
+ value = section.get("upload_source") if isinstance(section, dict) else None
59
+ return value if isinstance(value, bool) else None
60
+
61
+
62
+ def store_answer(value: bool, path: Path | None = None) -> Path:
63
+ """Save the answer under ``[privacy]``, keeping every other line of the file. Raises OSError."""
64
+ target = path or config_path()
65
+ block = f"[privacy]\nupload_source = {'true' if value else 'false'}\n"
66
+ try:
67
+ text = target.read_text(encoding="utf-8")
68
+ except FileNotFoundError:
69
+ text = ""
70
+ if _SECTION_RE.search(text):
71
+ text = _SECTION_RE.sub(lambda _m: block + "\n", text, count=1).rstrip("\n") + "\n"
72
+ else:
73
+ text = (text.rstrip("\n") + "\n\n" if text.strip() else "") + block
74
+ target.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
75
+ write_secure_file(target, text)
76
+ return target
77
+
78
+
79
+ def privacy_block(path: Path) -> str:
80
+ """The existing ``[privacy]`` section of *path* (for carrying over on ``init --force``), or ''."""
81
+ try:
82
+ match = _SECTION_RE.search(path.read_text(encoding="utf-8"))
83
+ except OSError:
84
+ return ""
85
+ return "\n" + match.group(0).rstrip("\n") + "\n" if match else ""
86
+
87
+
88
+ def is_interactive() -> bool:
89
+ """True only for a person at a terminal: stdin and stdout are TTYs and no CI marker is set."""
90
+ if os.environ.get("CI", "").strip().lower() in _TRUE:
91
+ return False
92
+ try:
93
+ return bool(sys.stdin and sys.stdin.isatty() and sys.stdout and sys.stdout.isatty())
94
+ except (AttributeError, ValueError, OSError):
95
+ return False
96
+
97
+
98
+ def ask() -> bool | None:
99
+ """Ask once. True for yes, False for anything else; None when no answer can be read."""
100
+ try:
101
+ answer = input(PROMPT)
102
+ except (EOFError, OSError):
103
+ return None
104
+ return answer.strip().lower() in ("y", "yes")