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.
- cloudsprite/__init__.py +451 -0
- cloudsprite/_antenna.py +83 -0
- cloudsprite/_auth.py +295 -0
- cloudsprite/_client.py +502 -0
- cloudsprite/_config.py +203 -0
- cloudsprite/_consent.py +104 -0
- cloudsprite/_context.py +945 -0
- cloudsprite/_exceptions.py +136 -0
- cloudsprite/_figure_models.py +158 -0
- cloudsprite/_figure_validation.py +168 -0
- cloudsprite/_filter_foster.py +165 -0
- cloudsprite/_filter_synthesis.py +400 -0
- cloudsprite/_filtering.py +134 -0
- cloudsprite/_impedance_matching.py +262 -0
- cloudsprite/_interpolation.py +47 -0
- cloudsprite/_lineage.py +775 -0
- cloudsprite/_link_budget.py +99 -0
- cloudsprite/_logging.py +53 -0
- cloudsprite/_mixed_mode.py +49 -0
- cloudsprite/_monte_carlo.py +193 -0
- cloudsprite/_noise_figure.py +44 -0
- cloudsprite/_pagination.py +130 -0
- cloudsprite/_parsers.py +75 -0
- cloudsprite/_publish.py +162 -0
- cloudsprite/_redact.py +179 -0
- cloudsprite/_response.py +63 -0
- cloudsprite/_resultset.py +65 -0
- cloudsprite/_rf_network.py +111 -0
- cloudsprite/_run_config.py +46 -0
- cloudsprite/_script_runner.py +217 -0
- cloudsprite/_script_workspace.py +271 -0
- cloudsprite/_sparameter_metrics.py +75 -0
- cloudsprite/_tdr.py +283 -0
- cloudsprite/_trace.py +112 -0
- cloudsprite/_version.py +23 -0
- cloudsprite/_visualizer.py +380 -0
- cloudsprite/_visualizer_cli.py +412 -0
- cloudsprite/_visualizer_preview.py +864 -0
- cloudsprite/_work_context.py +116 -0
- cloudsprite/_ws.py +577 -0
- cloudsprite/cli.py +300 -0
- cloudsprite/py.typed +0 -0
- cloudsprite/resources/__init__.py +1 -0
- cloudsprite/resources/_base.py +293 -0
- cloudsprite/resources/_models.py +50 -0
- cloudsprite/resources/cloudscripts.py +173 -0
- cloudsprite/resources/datasets.py +431 -0
- cloudsprite/resources/figures.py +282 -0
- cloudsprite/resources/instruments.py +295 -0
- cloudsprite/resources/notebooks.py +183 -0
- cloudsprite/resources/orbs.py +99 -0
- cloudsprite/resources/parameters.py +77 -0
- cloudsprite/resources/projects.py +182 -0
- cloudsprite/resources/related.py +125 -0
- cloudsprite/resources/reports.py +992 -0
- cloudsprite/resources/search.py +245 -0
- cloudsprite/resources/shares.py +229 -0
- cloudsprite/resources/sprites.py +15 -0
- cloudsprite/resources/tags.py +107 -0
- cloudsprite/resources/teams.py +86 -0
- cloudsprite/resources/traces.py +147 -0
- cloudsprite/resources/usage.py +152 -0
- cloudsprite/resources/visualizer_templates.py +466 -0
- cloudsprite/resources/workflows.py +59 -0
- cloudsprite-0.11.0.dist-info/METADATA +358 -0
- cloudsprite-0.11.0.dist-info/RECORD +70 -0
- cloudsprite-0.11.0.dist-info/WHEEL +5 -0
- cloudsprite-0.11.0.dist-info/entry_points.txt +3 -0
- cloudsprite-0.11.0.dist-info/licenses/LICENSE +21 -0
- cloudsprite-0.11.0.dist-info/top_level.txt +1 -0
cloudsprite/_context.py
ADDED
|
@@ -0,0 +1,945 @@
|
|
|
1
|
+
"""Client: connection state, team/project defaults, resource roots.
|
|
2
|
+
|
|
3
|
+
``Client`` is the primary API object. Construction is cold — no network I/O in ``__init__``.
|
|
4
|
+
Credentials resolve on the first API call or via explicit ``.connect()``.
|
|
5
|
+
|
|
6
|
+
The module-level convenience API (``cs.connect``, ``cs.projects``, …)
|
|
7
|
+
delegates to a process-default ``Client``. Library code must accept a ``Client``
|
|
8
|
+
explicitly rather than reaching for that default — there is a lint gate in
|
|
9
|
+
``tests/test_client_surface.py`` enforcing it.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import atexit
|
|
15
|
+
import logging
|
|
16
|
+
import os
|
|
17
|
+
import threading
|
|
18
|
+
import weakref
|
|
19
|
+
from collections.abc import Callable
|
|
20
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
21
|
+
from contextlib import AbstractContextManager
|
|
22
|
+
from typing import TYPE_CHECKING, Any, cast
|
|
23
|
+
|
|
24
|
+
from cloudsprite import _work_context
|
|
25
|
+
from cloudsprite._auth import AuthManager
|
|
26
|
+
from cloudsprite._client import HTTPClient
|
|
27
|
+
from cloudsprite._config import Config
|
|
28
|
+
from cloudsprite._exceptions import CloudSpriteError, ValidationError
|
|
29
|
+
from cloudsprite.resources._base import ResourceCollection
|
|
30
|
+
from cloudsprite.resources.teams import Team
|
|
31
|
+
|
|
32
|
+
if TYPE_CHECKING:
|
|
33
|
+
from cloudsprite._lineage import LineageTracker
|
|
34
|
+
from cloudsprite.resources.cloudscripts import CloudScriptCollection
|
|
35
|
+
from cloudsprite.resources.datasets import Dataset
|
|
36
|
+
from cloudsprite.resources.figures import FigureCollection
|
|
37
|
+
from cloudsprite.resources.instruments import Instrument
|
|
38
|
+
from cloudsprite.resources.orbs import Orb
|
|
39
|
+
from cloudsprite.resources.parameters import ParameterKey, ParameterTemplate
|
|
40
|
+
from cloudsprite.resources.projects import Project
|
|
41
|
+
from cloudsprite.resources.reports import ReportCollection
|
|
42
|
+
from cloudsprite.resources.search import SearchResult
|
|
43
|
+
from cloudsprite.resources.shares import ShareLinkCollection
|
|
44
|
+
from cloudsprite.resources.tags import TagCollection
|
|
45
|
+
from cloudsprite.resources.visualizer_templates import VisualizerTemplateCollection
|
|
46
|
+
from cloudsprite.resources.workflows import Workflow, WorkflowRun
|
|
47
|
+
|
|
48
|
+
logger = logging.getLogger(__name__)
|
|
49
|
+
|
|
50
|
+
# Clients that registered an atexit pool shutdown. Weak so closed/GC'd clients drop.
|
|
51
|
+
_ATEXIT_CLIENTS: weakref.WeakSet[Client] = weakref.WeakSet()
|
|
52
|
+
_ATEXIT_REGISTERED = False
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _atexit_close_clients() -> None:
|
|
56
|
+
"""Shut down thread pools for any live Client at process exit."""
|
|
57
|
+
for client in list(_ATEXIT_CLIENTS):
|
|
58
|
+
try:
|
|
59
|
+
client.close()
|
|
60
|
+
except Exception: # pragma: no cover - interpreter teardown is hostile
|
|
61
|
+
# Never raise from atexit; log at debug since handlers run after
|
|
62
|
+
# logging may already be torn down.
|
|
63
|
+
logger.debug("client close failed during atexit", exc_info=True)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _ensure_atexit() -> None:
|
|
67
|
+
global _ATEXIT_REGISTERED
|
|
68
|
+
if not _ATEXIT_REGISTERED:
|
|
69
|
+
atexit.register(_atexit_close_clients)
|
|
70
|
+
_ATEXIT_REGISTERED = True
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _env_slug(name: str) -> str | None:
|
|
74
|
+
return os.environ.get(name, "").strip() or None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class _RunProjectCollection(ResourceCollection["Project"]):
|
|
78
|
+
"""Projects under a run token: only the run's own project, seeded from the manifest.
|
|
79
|
+
|
|
80
|
+
Run tokens cannot call ``GET /api/projects/``; the manifest ids stand in for it.
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
def __init__(
|
|
84
|
+
self,
|
|
85
|
+
client: HTTPClient,
|
|
86
|
+
path: str,
|
|
87
|
+
resource_class: type[Project],
|
|
88
|
+
check: Callable[[str], None],
|
|
89
|
+
item: dict[str, Any],
|
|
90
|
+
) -> None:
|
|
91
|
+
super().__init__(client, path, resource_class, name_field="title")
|
|
92
|
+
self._check = check
|
|
93
|
+
self._items = [item]
|
|
94
|
+
|
|
95
|
+
def _exact_match(self, key: str) -> Project:
|
|
96
|
+
self._check(key)
|
|
97
|
+
return super()._exact_match(key)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class Client:
|
|
101
|
+
"""CloudSprite session: auth, team/project defaults, and resource roots.
|
|
102
|
+
|
|
103
|
+
Construction performs **no network I/O**. Pass credentials (or rely on
|
|
104
|
+
env/config) and call methods — auth runs on first API use, or call
|
|
105
|
+
:meth:`connect` explicitly.
|
|
106
|
+
|
|
107
|
+
Example::
|
|
108
|
+
|
|
109
|
+
from cloudsprite import Client
|
|
110
|
+
|
|
111
|
+
with Client(api_key="csk_...", org="acme", team="rf-lab") as cs:
|
|
112
|
+
for p in cs.projects:
|
|
113
|
+
print(p.name)
|
|
114
|
+
|
|
115
|
+
Two clients with different teams are fully isolated (headers, caches,
|
|
116
|
+
lineage, thread pools). Concurrent ``set_team`` on one client is
|
|
117
|
+
unsupported; prefer one Client per thread or logical session.
|
|
118
|
+
"""
|
|
119
|
+
|
|
120
|
+
def __init__(
|
|
121
|
+
self,
|
|
122
|
+
*,
|
|
123
|
+
api_key: str | None = None,
|
|
124
|
+
base_url: str | None = None,
|
|
125
|
+
email: str | None = None,
|
|
126
|
+
password: str | None = None,
|
|
127
|
+
allow_insecure: bool = False,
|
|
128
|
+
org: str | None = None,
|
|
129
|
+
team: str | None = None,
|
|
130
|
+
project: str | None = None,
|
|
131
|
+
) -> None:
|
|
132
|
+
# Cold construct — credentials stored for lazy connect.
|
|
133
|
+
self._pending_api_key = api_key
|
|
134
|
+
self._pending_base_url = base_url
|
|
135
|
+
self._pending_email = email
|
|
136
|
+
self._pending_password = password
|
|
137
|
+
self._pending_allow_insecure = allow_insecure
|
|
138
|
+
# Reentrant: connect() resolves the team slug, which issues a request
|
|
139
|
+
# that runs the header provider, which can re-enter this client.
|
|
140
|
+
# Created before _reset_session_state and never replaced by it.
|
|
141
|
+
self._connect_lock = threading.RLock()
|
|
142
|
+
self._work_scope = _work_context.WorkScope()
|
|
143
|
+
# Declare session fields once with full types, then reset.
|
|
144
|
+
self._param_post_pool: ThreadPoolExecutor | None
|
|
145
|
+
self._config: Config | None
|
|
146
|
+
self._auth: AuthManager | None
|
|
147
|
+
self._http: HTTPClient | None
|
|
148
|
+
self._connected: bool
|
|
149
|
+
self._closed: bool
|
|
150
|
+
self._org_slug: str | None
|
|
151
|
+
self._team_slug: str | None
|
|
152
|
+
self._project_slug: str | None
|
|
153
|
+
self._lineage: LineageTracker | None
|
|
154
|
+
self._project_id_cache: dict[str, str]
|
|
155
|
+
self._team_id_cache: dict[str, str]
|
|
156
|
+
self._org_id_cache: dict[str, str]
|
|
157
|
+
self._team_org_cache: dict[str, str]
|
|
158
|
+
self._run_scoped: bool
|
|
159
|
+
self._run_project: tuple[str, str] | None
|
|
160
|
+
self._reset_session_state()
|
|
161
|
+
# Constructor args win, then env (set by the script runner from the run
|
|
162
|
+
# manifest), then ~/.cloudsprite/config at connect. Read here, not at
|
|
163
|
+
# connect: scoped roots like ``cs.projects`` check the team before
|
|
164
|
+
# connecting, and an explicit ``set_team`` still overrides afterwards.
|
|
165
|
+
self._org_slug = org if org is not None else _env_slug("CLOUDSPRITE_ORG")
|
|
166
|
+
self._team_slug = team if team is not None else _env_slug("CLOUDSPRITE_TEAM")
|
|
167
|
+
self._project_slug = project if project is not None else _env_slug("CLOUDSPRITE_PROJECT")
|
|
168
|
+
self._seed_run_scope()
|
|
169
|
+
_ensure_atexit()
|
|
170
|
+
_ATEXIT_CLIENTS.add(self)
|
|
171
|
+
|
|
172
|
+
def _seed_run_scope(self) -> None:
|
|
173
|
+
"""Seed id caches from the run manifest ids (``CLOUDSPRITE_*_ID``), skipping lookups.
|
|
174
|
+
|
|
175
|
+
Run tokens cannot list ``/api/tenants/``, ``/api/teams/`` or ``/api/projects/``,
|
|
176
|
+
so the script runner passes the ids it already has. Seeds are keyed by the
|
|
177
|
+
env slugs, so a constructor override of the slug falls back to normal lookup.
|
|
178
|
+
"""
|
|
179
|
+
self._run_scoped = False
|
|
180
|
+
self._run_project = None
|
|
181
|
+
if not os.environ.get("CS_RUN_TOKEN", "").strip():
|
|
182
|
+
return
|
|
183
|
+
for slug_env, id_env, cache in (
|
|
184
|
+
("CLOUDSPRITE_ORG", "CLOUDSPRITE_ORG_ID", self._org_id_cache),
|
|
185
|
+
("CLOUDSPRITE_TEAM", "CLOUDSPRITE_TEAM_ID", self._team_id_cache),
|
|
186
|
+
):
|
|
187
|
+
slug, scope_id = _env_slug(slug_env), _env_slug(id_env)
|
|
188
|
+
if slug and scope_id:
|
|
189
|
+
cache[slug] = scope_id
|
|
190
|
+
cache[scope_id] = scope_id
|
|
191
|
+
project_slug, project_id = _env_slug("CLOUDSPRITE_PROJECT"), _env_slug("CLOUDSPRITE_PROJECT_ID")
|
|
192
|
+
if project_slug and project_id:
|
|
193
|
+
self._project_id_cache[project_slug] = project_id
|
|
194
|
+
self._project_id_cache[project_id] = project_id
|
|
195
|
+
self._run_project = (project_slug, project_id)
|
|
196
|
+
self._run_scoped = bool(self._run_project or _env_slug("CLOUDSPRITE_TEAM_ID"))
|
|
197
|
+
|
|
198
|
+
def _check_run_project(self, key: str) -> None:
|
|
199
|
+
"""Under a run token only the run's own project is reachable."""
|
|
200
|
+
if self._run_project is not None and key not in self._run_project:
|
|
201
|
+
raise ValidationError(
|
|
202
|
+
f"Project {key!r} is not available: run tokens can only access the run's own project "
|
|
203
|
+
f"({self._run_project[0]!r})."
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
def _reset_session_state(self) -> None:
|
|
207
|
+
"""Clear connection and caches. Shuts down any prior param thread pool."""
|
|
208
|
+
existing_pool = getattr(self, "_param_post_pool", None)
|
|
209
|
+
if existing_pool is not None:
|
|
210
|
+
existing_pool.shutdown(wait=False)
|
|
211
|
+
self._param_post_pool = None
|
|
212
|
+
self._config = None
|
|
213
|
+
self._auth = None
|
|
214
|
+
self._http = None
|
|
215
|
+
self._connected = False
|
|
216
|
+
self._closed = False
|
|
217
|
+
self._org_slug = None
|
|
218
|
+
self._team_slug = None
|
|
219
|
+
self._project_slug = None
|
|
220
|
+
self._lineage = None
|
|
221
|
+
self._project_id_cache = {}
|
|
222
|
+
self._team_id_cache = {}
|
|
223
|
+
self._org_id_cache = {}
|
|
224
|
+
self._team_org_cache = {}
|
|
225
|
+
|
|
226
|
+
# ------------------------------------------------------------------
|
|
227
|
+
# Lifecycle
|
|
228
|
+
# ------------------------------------------------------------------
|
|
229
|
+
|
|
230
|
+
def close(self) -> None:
|
|
231
|
+
"""Shut down the param thread pool, close the transport, mark closed.
|
|
232
|
+
|
|
233
|
+
Further API calls raise :class:`~cloudsprite.CloudSpriteError` — including
|
|
234
|
+
calls through resource handles captured *before* the close, which hold the
|
|
235
|
+
transport directly. Safe to call more than once.
|
|
236
|
+
"""
|
|
237
|
+
if self._closed:
|
|
238
|
+
return
|
|
239
|
+
pool = self._param_post_pool
|
|
240
|
+
if pool is not None:
|
|
241
|
+
pool.shutdown(wait=False)
|
|
242
|
+
self._param_post_pool = None
|
|
243
|
+
# Close the transport before dropping the reference: collections captured
|
|
244
|
+
# earlier still point at it, and would otherwise keep working (and leak
|
|
245
|
+
# the socket) after the owner was closed.
|
|
246
|
+
if self._http is not None:
|
|
247
|
+
self._http.close()
|
|
248
|
+
self._connected = False
|
|
249
|
+
self._http = None
|
|
250
|
+
self._auth = None
|
|
251
|
+
# Don't leave credentials on a dead object.
|
|
252
|
+
self._pending_api_key = None
|
|
253
|
+
self._pending_password = None
|
|
254
|
+
self._closed = True
|
|
255
|
+
_ATEXIT_CLIENTS.discard(self)
|
|
256
|
+
|
|
257
|
+
def __enter__(self) -> Client:
|
|
258
|
+
return self
|
|
259
|
+
|
|
260
|
+
def __exit__(self, *exc: object) -> None:
|
|
261
|
+
self.close()
|
|
262
|
+
|
|
263
|
+
def _check_open(self) -> None:
|
|
264
|
+
if self._closed:
|
|
265
|
+
raise CloudSpriteError("Client is closed. Create a new Client() to continue.")
|
|
266
|
+
|
|
267
|
+
# ------------------------------------------------------------------
|
|
268
|
+
# Connection
|
|
269
|
+
# ------------------------------------------------------------------
|
|
270
|
+
|
|
271
|
+
@property
|
|
272
|
+
def is_connected(self) -> bool:
|
|
273
|
+
"""True when authenticated and not closed."""
|
|
274
|
+
return self._connected and not self._closed
|
|
275
|
+
|
|
276
|
+
@property
|
|
277
|
+
def param_post_pool(self) -> ThreadPoolExecutor:
|
|
278
|
+
"""Lazily-created thread pool shared across publish() parameter POSTs."""
|
|
279
|
+
self._check_open()
|
|
280
|
+
if self._param_post_pool is None:
|
|
281
|
+
self._param_post_pool = ThreadPoolExecutor(max_workers=8, thread_name_prefix="cloudsprite-publish")
|
|
282
|
+
return self._param_post_pool
|
|
283
|
+
|
|
284
|
+
@property
|
|
285
|
+
def org_slug(self) -> str | None:
|
|
286
|
+
"""Default org (tenant) slug for scoped requests, or None if unset."""
|
|
287
|
+
return self._org_slug
|
|
288
|
+
|
|
289
|
+
@property
|
|
290
|
+
def team_slug(self) -> str | None:
|
|
291
|
+
"""Default team slug for scoped requests, or None if unset."""
|
|
292
|
+
return self._team_slug
|
|
293
|
+
|
|
294
|
+
@property
|
|
295
|
+
def project_slug(self) -> str | None:
|
|
296
|
+
"""Default project slug for scoped requests, or None if unset."""
|
|
297
|
+
return self._project_slug
|
|
298
|
+
|
|
299
|
+
@property
|
|
300
|
+
def client(self) -> HTTPClient:
|
|
301
|
+
"""Authenticated HTTP transport (lazy-connects if needed)."""
|
|
302
|
+
self._ensure_connected()
|
|
303
|
+
assert self._http is not None
|
|
304
|
+
return self._http
|
|
305
|
+
|
|
306
|
+
def _ensure_connected(self) -> None:
|
|
307
|
+
"""Authenticate on first use if not already connected (lazy auth).
|
|
308
|
+
|
|
309
|
+
Double-checked locking. Because lazy auth makes *first read* the auth trigger,
|
|
310
|
+
an unguarded version turns ordinary notebook fan-out
|
|
311
|
+
(``ThreadPoolExecutor`` over ``cs.projects``) into one auth POST and one
|
|
312
|
+
HTTPClient per thread — minting N tokens, orphaning N-1 sessions, and
|
|
313
|
+
potentially tripping our own 429 handling. Concurrent first read is
|
|
314
|
+
supported; concurrent ``set_team`` on one client is not.
|
|
315
|
+
"""
|
|
316
|
+
self._check_open()
|
|
317
|
+
if self._connected and self._http is not None:
|
|
318
|
+
return
|
|
319
|
+
with self._connect_lock:
|
|
320
|
+
# Re-check: another thread may have connected while we waited.
|
|
321
|
+
if self._connected and self._http is not None:
|
|
322
|
+
return
|
|
323
|
+
self.connect(
|
|
324
|
+
api_key=self._pending_api_key,
|
|
325
|
+
base_url=self._pending_base_url,
|
|
326
|
+
email=self._pending_email,
|
|
327
|
+
password=self._pending_password,
|
|
328
|
+
allow_insecure=self._pending_allow_insecure,
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
def connect(
|
|
332
|
+
self,
|
|
333
|
+
api_key: str | None = None,
|
|
334
|
+
base_url: str | None = None,
|
|
335
|
+
email: str | None = None,
|
|
336
|
+
password: str | None = None,
|
|
337
|
+
allow_insecure: bool | None = None,
|
|
338
|
+
) -> None:
|
|
339
|
+
"""Authenticate with the CloudSprite API.
|
|
340
|
+
|
|
341
|
+
Supports API key (default) or Cognito email/password. Credentials
|
|
342
|
+
fall back to values passed to the constructor, then env/config.
|
|
343
|
+
|
|
344
|
+
Args:
|
|
345
|
+
api_key: API key string (resolves from env/config if omitted).
|
|
346
|
+
base_url: Override the API base URL.
|
|
347
|
+
email: Cognito email for user login.
|
|
348
|
+
password: Cognito password for user login.
|
|
349
|
+
allow_insecure: Allow http:// connections (local dev only). ``None``
|
|
350
|
+
means "inherit whatever the constructor was given"; pass
|
|
351
|
+
``False`` to explicitly turn a constructor ``True`` back off.
|
|
352
|
+
"""
|
|
353
|
+
self._check_open()
|
|
354
|
+
# Explicit kwargs win; otherwise fall back to constructor-pending values.
|
|
355
|
+
if api_key is None:
|
|
356
|
+
api_key = self._pending_api_key
|
|
357
|
+
if base_url is None:
|
|
358
|
+
base_url = self._pending_base_url
|
|
359
|
+
if email is None:
|
|
360
|
+
email = self._pending_email
|
|
361
|
+
if password is None:
|
|
362
|
+
password = self._pending_password
|
|
363
|
+
# None sentinel, not falsy: with `if not allow_insecure` an explicit
|
|
364
|
+
# False could not override a constructor True — the flag became sticky
|
|
365
|
+
# and the connection stayed insecure without saying so.
|
|
366
|
+
if allow_insecure is None:
|
|
367
|
+
allow_insecure = self._pending_allow_insecure
|
|
368
|
+
|
|
369
|
+
self._pending_base_url = base_url
|
|
370
|
+
self._pending_email = email
|
|
371
|
+
self._pending_allow_insecure = allow_insecure
|
|
372
|
+
|
|
373
|
+
run_token = os.environ.get("CS_RUN_TOKEN", "").strip()
|
|
374
|
+
run_base = os.environ.get("CS_API_BASE_URL", "").strip() or None
|
|
375
|
+
if run_token:
|
|
376
|
+
resolved_base = base_url or run_base
|
|
377
|
+
insecure = bool(allow_insecure) or bool(resolved_base and resolved_base.startswith("http://"))
|
|
378
|
+
self._config = Config(api_key=None, base_url=resolved_base, allow_insecure=insecure)
|
|
379
|
+
self._auth = AuthManager(self._config)
|
|
380
|
+
self._auth.authenticate_run_token(run_token)
|
|
381
|
+
else:
|
|
382
|
+
self._config = Config(api_key=api_key, base_url=base_url, allow_insecure=allow_insecure)
|
|
383
|
+
self._auth = AuthManager(self._config)
|
|
384
|
+
|
|
385
|
+
if email and password:
|
|
386
|
+
self._auth.authenticate_cognito(email, password)
|
|
387
|
+
else:
|
|
388
|
+
self._config.require_api_key()
|
|
389
|
+
self._auth.authenticate()
|
|
390
|
+
|
|
391
|
+
# Drop the plaintext password now that it has been exchanged for tokens.
|
|
392
|
+
# Nothing re-reads it: refresh uses the refresh token, and re-connecting
|
|
393
|
+
# with Cognito means passing it again. The API key legitimately stays,
|
|
394
|
+
# but it lives on Config (behind a read-only property) rather than here.
|
|
395
|
+
self._pending_password = None
|
|
396
|
+
|
|
397
|
+
self._http = HTTPClient(self._config, self._auth)
|
|
398
|
+
self._http.set_header_provider(self._request_headers)
|
|
399
|
+
# Owner back-link so internal modules (ws / publish / lineage) resolve
|
|
400
|
+
# team/lineage/pool without importing the process-default client.
|
|
401
|
+
self._http.set_owner(self)
|
|
402
|
+
self._connected = True
|
|
403
|
+
self._apply_config_defaults()
|
|
404
|
+
|
|
405
|
+
def _apply_config_defaults(self) -> None:
|
|
406
|
+
"""Fill org/team from ~/.cloudsprite/config when the caller did not set them."""
|
|
407
|
+
config = self._config
|
|
408
|
+
if config is None:
|
|
409
|
+
return
|
|
410
|
+
if self._org_slug is None:
|
|
411
|
+
org = config.org
|
|
412
|
+
if org:
|
|
413
|
+
self._org_slug = org
|
|
414
|
+
if self._team_slug is None:
|
|
415
|
+
team = config.team
|
|
416
|
+
if team:
|
|
417
|
+
self._team_slug = team
|
|
418
|
+
|
|
419
|
+
def _list_orgs(self) -> list[dict[str, Any]]:
|
|
420
|
+
payload = self.client.get("/api/tenants/") or []
|
|
421
|
+
if isinstance(payload, dict):
|
|
422
|
+
payload = payload.get("results") or []
|
|
423
|
+
if not isinstance(payload, list):
|
|
424
|
+
return []
|
|
425
|
+
return [item for item in payload if isinstance(item, dict)]
|
|
426
|
+
|
|
427
|
+
def _ensure_org(self) -> None:
|
|
428
|
+
"""If no org is set and the key belongs to exactly one, use it.
|
|
429
|
+
|
|
430
|
+
Prod listTeams 400s without tenant context. User API keys are
|
|
431
|
+
tenant-scoped; a unique membership is enough to proceed. Multiple
|
|
432
|
+
orgs stay unset so the caller must ``set_org`` / ``cloudsprite init``.
|
|
433
|
+
Transport errors are swallowed so unit tests that do not mock
|
|
434
|
+
``/api/tenants/`` keep working.
|
|
435
|
+
"""
|
|
436
|
+
if self._org_slug:
|
|
437
|
+
return
|
|
438
|
+
try:
|
|
439
|
+
tenants = self._list_orgs()
|
|
440
|
+
except Exception:
|
|
441
|
+
logger.debug("org autoselect skipped", exc_info=True)
|
|
442
|
+
return
|
|
443
|
+
if len(tenants) != 1:
|
|
444
|
+
return
|
|
445
|
+
slug = tenants[0].get("slug")
|
|
446
|
+
if not isinstance(slug, str) or not slug:
|
|
447
|
+
return
|
|
448
|
+
self._org_slug = slug
|
|
449
|
+
tid = tenants[0].get("id")
|
|
450
|
+
if isinstance(tid, str) and tid:
|
|
451
|
+
self._org_id_cache[slug] = tid
|
|
452
|
+
|
|
453
|
+
def set_org(self, slug: str) -> None:
|
|
454
|
+
"""Set the default org (tenant) for subsequent queries and WebSockets."""
|
|
455
|
+
self._check_open()
|
|
456
|
+
if slug != self._org_slug:
|
|
457
|
+
self._team_id_cache.clear()
|
|
458
|
+
self._project_id_cache.clear()
|
|
459
|
+
self._org_slug = slug
|
|
460
|
+
|
|
461
|
+
def set_team(self, slug: str) -> None:
|
|
462
|
+
"""Set the default team for subsequent queries."""
|
|
463
|
+
self._check_open()
|
|
464
|
+
if slug != self._team_slug:
|
|
465
|
+
self._project_id_cache.clear()
|
|
466
|
+
self._team_slug = slug
|
|
467
|
+
|
|
468
|
+
def _clear_scope(self) -> None:
|
|
469
|
+
"""Drop org/team/project defaults (used by ``cloudsprite init`` rediscovery)."""
|
|
470
|
+
self._check_open()
|
|
471
|
+
self._org_slug = None
|
|
472
|
+
self._team_slug = None
|
|
473
|
+
self._project_slug = None
|
|
474
|
+
|
|
475
|
+
def set_project(self, slug: str) -> None:
|
|
476
|
+
"""Set the default project for subsequent queries."""
|
|
477
|
+
self._check_open()
|
|
478
|
+
self._project_slug = slug
|
|
479
|
+
|
|
480
|
+
def resolve_project_id(self, slug: str) -> str:
|
|
481
|
+
"""Resolve a project slug to its UUID, caching the result for the session."""
|
|
482
|
+
if slug in self._project_id_cache:
|
|
483
|
+
return self._project_id_cache[slug]
|
|
484
|
+
self._check_run_project(slug)
|
|
485
|
+
# Exact slug → single Project (not ResultSet); cast for the union return.
|
|
486
|
+
from cloudsprite.resources.projects import Project
|
|
487
|
+
|
|
488
|
+
project_obj = cast(Project, self.projects[slug])
|
|
489
|
+
project_id = project_obj.id
|
|
490
|
+
self._project_id_cache[slug] = project_id
|
|
491
|
+
return project_id
|
|
492
|
+
|
|
493
|
+
def resolve_org_id(self, slug: str) -> str:
|
|
494
|
+
"""Resolve an org (tenant) slug (or UUID) to its UUID, caching the result."""
|
|
495
|
+
if slug in self._org_id_cache:
|
|
496
|
+
return self._org_id_cache[slug]
|
|
497
|
+
tenants = self.client.get("/api/tenants/") or []
|
|
498
|
+
if isinstance(tenants, dict):
|
|
499
|
+
tenants = tenants.get("results") or []
|
|
500
|
+
for tenant in tenants:
|
|
501
|
+
if not isinstance(tenant, dict):
|
|
502
|
+
continue
|
|
503
|
+
if tenant.get("slug") == slug or tenant.get("id") == slug:
|
|
504
|
+
tid = tenant.get("id")
|
|
505
|
+
if isinstance(tid, str):
|
|
506
|
+
self._org_id_cache[slug] = tid
|
|
507
|
+
return tid
|
|
508
|
+
raise ValidationError(f"Org {slug!r} not found. Check cs.set_org() / Client(org=...).")
|
|
509
|
+
|
|
510
|
+
def resolve_team_id(self, slug: str) -> str:
|
|
511
|
+
"""Resolve a team slug (or UUID) to its UUID, caching the result."""
|
|
512
|
+
if slug in self._team_id_cache:
|
|
513
|
+
return self._team_id_cache[slug]
|
|
514
|
+
team_obj = cast(Team, self.teams[slug])
|
|
515
|
+
team_id = team_obj.id
|
|
516
|
+
self._team_id_cache[slug] = team_id
|
|
517
|
+
return team_id
|
|
518
|
+
|
|
519
|
+
def _request_headers(self) -> dict[str, str] | None:
|
|
520
|
+
"""Headers added to every API request: scope (org/team) plus the work context.
|
|
521
|
+
|
|
522
|
+
Under a run token (server run) no work-context header is sent: the API takes the
|
|
523
|
+
context from the run token and ignores the header there.
|
|
524
|
+
"""
|
|
525
|
+
headers = dict(self._scope_headers() or {})
|
|
526
|
+
ctx = self.current_work_context()
|
|
527
|
+
if ctx is not None:
|
|
528
|
+
headers[_work_context.HEADER_NAME] = ctx.header_value()
|
|
529
|
+
explicit = self._work_scope.explicit()
|
|
530
|
+
lineage = self._lineage
|
|
531
|
+
if explicit is not None and lineage is not None and lineage.is_tracking:
|
|
532
|
+
lineage.observe_work(explicit) # the run report is sent at exit, after the block has ended
|
|
533
|
+
return headers or None
|
|
534
|
+
|
|
535
|
+
def explicit_work_context(self) -> _work_context.WorkContext | None:
|
|
536
|
+
"""Context of the active ``with work_context`` block only (None under a run token)."""
|
|
537
|
+
return None if _work_context.under_run_token() else self._work_scope.explicit()
|
|
538
|
+
|
|
539
|
+
def current_work_context(self) -> _work_context.WorkContext | None:
|
|
540
|
+
"""Work context in force for this client now (None under a run token)."""
|
|
541
|
+
if _work_context.under_run_token():
|
|
542
|
+
return None
|
|
543
|
+
return self._work_scope.current()
|
|
544
|
+
|
|
545
|
+
def _scope_headers(self) -> dict[str, str] | None:
|
|
546
|
+
"""Return X-Tenant-ID / X-Team-ID when defaults are set.
|
|
547
|
+
|
|
548
|
+
Re-entrancy safe: resolving a slug hits the API, which also goes through
|
|
549
|
+
the HTTPClient header provider. While resolving, return cache hits only
|
|
550
|
+
so we never recurse.
|
|
551
|
+
"""
|
|
552
|
+
if getattr(self, "_resolving_scope_headers", False):
|
|
553
|
+
headers: dict[str, str] = {}
|
|
554
|
+
if self._org_slug and self._org_slug in self._org_id_cache:
|
|
555
|
+
headers["X-Tenant-ID"] = self._org_id_cache[self._org_slug]
|
|
556
|
+
if self._team_slug and self._team_slug in self._team_id_cache:
|
|
557
|
+
headers["X-Team-ID"] = self._team_id_cache[self._team_slug]
|
|
558
|
+
return headers or None
|
|
559
|
+
|
|
560
|
+
self._resolving_scope_headers = True
|
|
561
|
+
try:
|
|
562
|
+
headers = {}
|
|
563
|
+
# Run tokens can't list tenants; with no seeded org id (older API) send
|
|
564
|
+
# no tenant header rather than fail every request on the lookup.
|
|
565
|
+
if self._org_slug and (self._org_slug in self._org_id_cache or not self._run_scoped):
|
|
566
|
+
headers["X-Tenant-ID"] = self.resolve_org_id(self._org_slug)
|
|
567
|
+
# Resolving a team slug lists /api/teams/, which 400s without tenant
|
|
568
|
+
# context. A stale config team (or init rediscovery) must not turn
|
|
569
|
+
# GET /api/tenants/ into a team lookup.
|
|
570
|
+
if self._team_slug and (
|
|
571
|
+
self._team_slug in self._team_id_cache or (self._org_slug and not self._run_scoped)
|
|
572
|
+
):
|
|
573
|
+
headers["X-Team-ID"] = self.resolve_team_id(self._team_slug)
|
|
574
|
+
return headers or None
|
|
575
|
+
finally:
|
|
576
|
+
self._resolving_scope_headers = False
|
|
577
|
+
|
|
578
|
+
# ------------------------------------------------------------------
|
|
579
|
+
# Resource roots
|
|
580
|
+
# ------------------------------------------------------------------
|
|
581
|
+
|
|
582
|
+
@property
|
|
583
|
+
def teams(self) -> ResourceCollection[Team]:
|
|
584
|
+
"""Collection of teams visible to the authenticated user."""
|
|
585
|
+
self._ensure_org()
|
|
586
|
+
return ResourceCollection(self.client, "/api/teams/", Team, name_field="name")
|
|
587
|
+
|
|
588
|
+
def _require_team(self) -> None:
|
|
589
|
+
"""Scoped collections require a default team (X-Team-ID is injected by HTTPClient)."""
|
|
590
|
+
if not self._team_slug:
|
|
591
|
+
raise ValidationError("Call cs.set_team() first, or use cs.teams['slug'] for team-scoped access")
|
|
592
|
+
|
|
593
|
+
@property
|
|
594
|
+
def projects(self) -> ResourceCollection[Project]:
|
|
595
|
+
"""Projects in the default team (requires ``set_team``)."""
|
|
596
|
+
from cloudsprite.resources.projects import Project
|
|
597
|
+
|
|
598
|
+
self._require_team()
|
|
599
|
+
assert self._team_slug is not None
|
|
600
|
+
team_id = self.resolve_team_id(self._team_slug)
|
|
601
|
+
if self._run_project is not None:
|
|
602
|
+
slug, project_id = self._run_project
|
|
603
|
+
return _RunProjectCollection(
|
|
604
|
+
self.client,
|
|
605
|
+
f"/api/projects/?team_id={team_id}",
|
|
606
|
+
Project,
|
|
607
|
+
self._check_run_project,
|
|
608
|
+
{"id": project_id, "slug": slug, "title": slug},
|
|
609
|
+
)
|
|
610
|
+
return ResourceCollection(
|
|
611
|
+
self.client,
|
|
612
|
+
f"/api/projects/?team_id={team_id}",
|
|
613
|
+
Project,
|
|
614
|
+
name_field="title", # ProjectSchema uses title
|
|
615
|
+
)
|
|
616
|
+
|
|
617
|
+
@property
|
|
618
|
+
def datasets(self) -> ResourceCollection[Dataset]:
|
|
619
|
+
"""Datasets in the default project (requires ``set_project``)."""
|
|
620
|
+
from cloudsprite.resources.datasets import Dataset
|
|
621
|
+
|
|
622
|
+
if not self._project_slug:
|
|
623
|
+
raise ValidationError("Call cs.set_project() first, or use cs.projects['name'].datasets")
|
|
624
|
+
project_id = self.resolve_project_id(self._project_slug)
|
|
625
|
+
return ResourceCollection(
|
|
626
|
+
self.client,
|
|
627
|
+
f"/api/datasets/?project_id={project_id}&include_parameters=true",
|
|
628
|
+
Dataset,
|
|
629
|
+
name_field="title", # DatasetSchema uses title
|
|
630
|
+
)
|
|
631
|
+
|
|
632
|
+
@property
|
|
633
|
+
def figures(self) -> FigureCollection:
|
|
634
|
+
"""Publish and manage figures on explicit dataset or notebook targets."""
|
|
635
|
+
from cloudsprite.resources.figures import FigureCollection
|
|
636
|
+
|
|
637
|
+
self._require_team()
|
|
638
|
+
return FigureCollection(self.client)
|
|
639
|
+
|
|
640
|
+
@property
|
|
641
|
+
def visualizer_templates(self) -> VisualizerTemplateCollection:
|
|
642
|
+
"""Visualizer template registry: list, publish versions, install and deprecate templates."""
|
|
643
|
+
from cloudsprite.resources.visualizer_templates import VisualizerTemplateCollection
|
|
644
|
+
|
|
645
|
+
self._require_team()
|
|
646
|
+
return VisualizerTemplateCollection(self.client)
|
|
647
|
+
|
|
648
|
+
@property
|
|
649
|
+
def shares(self) -> ShareLinkCollection:
|
|
650
|
+
"""Share links for datasets, notebooks and figures (requires ``set_team`` for team-wide listing)."""
|
|
651
|
+
from cloudsprite.resources.shares import ShareLinkCollection
|
|
652
|
+
|
|
653
|
+
self._require_team()
|
|
654
|
+
return ShareLinkCollection(self.client)
|
|
655
|
+
|
|
656
|
+
@property
|
|
657
|
+
def reports(self) -> ReportCollection:
|
|
658
|
+
"""Reports in the default project (requires ``set_team``; ``set_project`` for listing).
|
|
659
|
+
|
|
660
|
+
``list(project)``, ``get``, ``create``, team/trash lists and backlinks
|
|
661
|
+
do not require ``set_project``. Bracket listing uses the default project.
|
|
662
|
+
"""
|
|
663
|
+
from cloudsprite.resources.reports import Report, ReportCollection
|
|
664
|
+
|
|
665
|
+
self._require_team()
|
|
666
|
+
if self._project_slug:
|
|
667
|
+
project_id = self.resolve_project_id(self._project_slug)
|
|
668
|
+
return ReportCollection(
|
|
669
|
+
self.client,
|
|
670
|
+
f"/api/reports/?project_id={project_id}",
|
|
671
|
+
Report,
|
|
672
|
+
name_field="title",
|
|
673
|
+
)
|
|
674
|
+
return ReportCollection(self.client, "/api/reports/", Report, name_field="title")
|
|
675
|
+
|
|
676
|
+
@property
|
|
677
|
+
def cloudscripts(self) -> CloudScriptCollection:
|
|
678
|
+
"""CloudScripts in the default project (beta; requires ``set_project``)."""
|
|
679
|
+
from cloudsprite.resources.cloudscripts import CloudScript, CloudScriptCollection
|
|
680
|
+
|
|
681
|
+
if not self._project_slug:
|
|
682
|
+
raise ValidationError("Call cs.set_project() first, or use cs.projects['name'].cloudscripts")
|
|
683
|
+
project_id = self.resolve_project_id(self._project_slug)
|
|
684
|
+
return CloudScriptCollection(
|
|
685
|
+
self.client,
|
|
686
|
+
f"/api/scripts/?project_id={project_id}",
|
|
687
|
+
CloudScript,
|
|
688
|
+
name_field="name",
|
|
689
|
+
)
|
|
690
|
+
|
|
691
|
+
# Legacy name kept as a true alias (same object).
|
|
692
|
+
sprites = cloudscripts
|
|
693
|
+
|
|
694
|
+
@property
|
|
695
|
+
def workflows(self) -> ResourceCollection[Workflow]:
|
|
696
|
+
"""Workflows in the default project (beta; requires ``set_project``)."""
|
|
697
|
+
from cloudsprite.resources.workflows import Workflow
|
|
698
|
+
|
|
699
|
+
if not self._project_slug:
|
|
700
|
+
raise ValidationError("Call cs.set_project() first, or use cs.projects['name'].workflows")
|
|
701
|
+
project_id = self.resolve_project_id(self._project_slug)
|
|
702
|
+
return ResourceCollection(
|
|
703
|
+
self.client,
|
|
704
|
+
f"/api/workflows/?project_id={project_id}",
|
|
705
|
+
Workflow,
|
|
706
|
+
name_field="name",
|
|
707
|
+
)
|
|
708
|
+
|
|
709
|
+
def workflow_run(self, run_id: str) -> WorkflowRun:
|
|
710
|
+
"""Fetch a workflow run by id (beta).
|
|
711
|
+
|
|
712
|
+
Server: ``GET /api/workflow-runs/{id}/``.
|
|
713
|
+
"""
|
|
714
|
+
from cloudsprite.resources.workflows import WorkflowRun
|
|
715
|
+
|
|
716
|
+
payload = self.client.get(f"/api/workflow-runs/{run_id}/")
|
|
717
|
+
if not isinstance(payload, dict):
|
|
718
|
+
raise ValidationError("Unexpected workflow-run response")
|
|
719
|
+
return WorkflowRun(self.client, payload)
|
|
720
|
+
|
|
721
|
+
@property
|
|
722
|
+
def instruments(self) -> ResourceCollection[Instrument]:
|
|
723
|
+
"""Instruments in the default team (requires ``set_team``)."""
|
|
724
|
+
from cloudsprite.resources.instruments import Instrument
|
|
725
|
+
|
|
726
|
+
self._require_team()
|
|
727
|
+
return ResourceCollection(
|
|
728
|
+
self.client,
|
|
729
|
+
"/api/instruments/",
|
|
730
|
+
Instrument,
|
|
731
|
+
name_field="name",
|
|
732
|
+
)
|
|
733
|
+
|
|
734
|
+
@property
|
|
735
|
+
def tags(self) -> TagCollection:
|
|
736
|
+
"""Tags of the default team (requires ``set_team``).
|
|
737
|
+
|
|
738
|
+
Example:
|
|
739
|
+
>>> cs.tags.create("base") # idempotent on (team, name)
|
|
740
|
+
>>> cs.tags["base"].id
|
|
741
|
+
"""
|
|
742
|
+
from cloudsprite.resources.tags import Tag, TagCollection
|
|
743
|
+
|
|
744
|
+
self._require_team()
|
|
745
|
+
assert self._team_slug is not None
|
|
746
|
+
team_id = self.resolve_team_id(self._team_slug)
|
|
747
|
+
return TagCollection(self.client, f"/api/tags/?team_id={team_id}", Tag, name_field="name")
|
|
748
|
+
|
|
749
|
+
@property
|
|
750
|
+
def orbs(self) -> ResourceCollection[Orb]:
|
|
751
|
+
"""Orbs in the default team (requires ``set_team``)."""
|
|
752
|
+
from cloudsprite.resources.orbs import Orb
|
|
753
|
+
|
|
754
|
+
self._require_team()
|
|
755
|
+
return ResourceCollection(
|
|
756
|
+
self.client,
|
|
757
|
+
"/api/orbs/",
|
|
758
|
+
Orb,
|
|
759
|
+
name_field="name",
|
|
760
|
+
)
|
|
761
|
+
|
|
762
|
+
@property
|
|
763
|
+
def parameter_keys(self) -> ResourceCollection[ParameterKey]:
|
|
764
|
+
"""Parameter key definitions for the default team."""
|
|
765
|
+
from cloudsprite.resources.parameters import ParameterKey
|
|
766
|
+
|
|
767
|
+
self._require_team()
|
|
768
|
+
return ResourceCollection(
|
|
769
|
+
self.client,
|
|
770
|
+
# Server route is /api/parameters/ — there is no /keys/ segment.
|
|
771
|
+
# Verified against the live OpenAPI spec.
|
|
772
|
+
"/api/parameters/",
|
|
773
|
+
ParameterKey,
|
|
774
|
+
name_field="title", # ParameterKeySchema uses title
|
|
775
|
+
)
|
|
776
|
+
|
|
777
|
+
@property
|
|
778
|
+
def parameter_templates(self) -> ResourceCollection[ParameterTemplate]:
|
|
779
|
+
"""Parameter templates for the default team."""
|
|
780
|
+
from cloudsprite.resources.parameters import ParameterTemplate
|
|
781
|
+
|
|
782
|
+
self._require_team()
|
|
783
|
+
return ResourceCollection(
|
|
784
|
+
self.client,
|
|
785
|
+
# Server mounts this as its own router: /api/parameter-templates/,
|
|
786
|
+
# not a sub-path of /api/parameters/. Verified against the spec.
|
|
787
|
+
"/api/parameter-templates/",
|
|
788
|
+
ParameterTemplate,
|
|
789
|
+
name_field="name",
|
|
790
|
+
)
|
|
791
|
+
|
|
792
|
+
@property
|
|
793
|
+
def supported_models(self) -> list[Any]:
|
|
794
|
+
"""List all supported instrument models in the catalog."""
|
|
795
|
+
# /api/instruments/models/supported/ does not exist. The catalog router
|
|
796
|
+
# is the sibling of manufacturers below: /api/instruments/catalog/models/.
|
|
797
|
+
return cast(list[Any], self.client.get("/api/instruments/catalog/models/"))
|
|
798
|
+
|
|
799
|
+
@property
|
|
800
|
+
def manufacturers(self) -> list[Any]:
|
|
801
|
+
"""List all instrument manufacturers in the catalog."""
|
|
802
|
+
return cast(list[Any], self.client.get("/api/instruments/catalog/manufacturers/"))
|
|
803
|
+
|
|
804
|
+
def search(self, query: str, **kwargs: Any) -> list[SearchResult]:
|
|
805
|
+
"""Search resources globally (projects, datasets, notebooks, …).
|
|
806
|
+
|
|
807
|
+
Accepts ``limit``. ``type`` and ``project_id`` raise ValidationError;
|
|
808
|
+
use collection list filters or filter results by ``.type``.
|
|
809
|
+
"""
|
|
810
|
+
from cloudsprite.resources.search import search
|
|
811
|
+
|
|
812
|
+
return search(self.client, query, **kwargs)
|
|
813
|
+
|
|
814
|
+
def search_traces(self, **kwargs: Any) -> list[dict[str, Any]]:
|
|
815
|
+
"""Search traces with filters; returns raw result dicts."""
|
|
816
|
+
from cloudsprite.resources.search import search_traces
|
|
817
|
+
|
|
818
|
+
return search_traces(self.client, **kwargs)
|
|
819
|
+
|
|
820
|
+
# ------------------------------------------------------------------
|
|
821
|
+
# Publish / lineage (owned by this client)
|
|
822
|
+
# ------------------------------------------------------------------
|
|
823
|
+
|
|
824
|
+
def cloudscript(
|
|
825
|
+
self,
|
|
826
|
+
file_path: str | None = None,
|
|
827
|
+
seed: Any = None,
|
|
828
|
+
*,
|
|
829
|
+
install_hooks: bool | None = None,
|
|
830
|
+
upload_source: bool | None = None,
|
|
831
|
+
include_git: bool | None = None,
|
|
832
|
+
include_error: bool | None = None,
|
|
833
|
+
purpose: str | None = None,
|
|
834
|
+
params: dict[str, Any] | None = None,
|
|
835
|
+
include_argv: bool | None = None,
|
|
836
|
+
) -> None:
|
|
837
|
+
"""Enable CloudScript lineage tracking and SDK run reporting on this client.
|
|
838
|
+
|
|
839
|
+
``purpose`` (why the run was made, up to 280 chars), ``params`` (the run's
|
|
840
|
+
parameters, secrets redacted before sending) and ``sys.argv[1:]`` (redacted;
|
|
841
|
+
opt out with ``include_argv=False``) go in the run report. Script source is
|
|
842
|
+
attached on ``publish()`` only with your consent (asked once in a terminal and
|
|
843
|
+
saved in ``~/.cloudsprite/config``; ``upload_source=`` or
|
|
844
|
+
``CLOUDSPRITE_UPLOAD_SOURCE`` override it; cloud runs always attach it). The work context
|
|
845
|
+
active here (see :meth:`work_context`) is the run's activity.
|
|
846
|
+
|
|
847
|
+
``Client.sprite`` and ``Client.track_script`` are legacy aliases of
|
|
848
|
+
``Client.cloudscript`` — same callable, no deprecation warning.
|
|
849
|
+
"""
|
|
850
|
+
from cloudsprite._lineage import LineageTracker
|
|
851
|
+
|
|
852
|
+
self._check_open()
|
|
853
|
+
if self._lineage is None:
|
|
854
|
+
self._lineage = LineageTracker(owner=self)
|
|
855
|
+
self._lineage.cloudscript(
|
|
856
|
+
file_path,
|
|
857
|
+
seed=seed,
|
|
858
|
+
install_hooks=install_hooks,
|
|
859
|
+
upload_source=upload_source,
|
|
860
|
+
include_git=include_git,
|
|
861
|
+
include_error=include_error,
|
|
862
|
+
purpose=purpose,
|
|
863
|
+
params=params,
|
|
864
|
+
include_argv=include_argv,
|
|
865
|
+
)
|
|
866
|
+
|
|
867
|
+
# Legacy names kept as true aliases (same object).
|
|
868
|
+
sprite = cloudscript
|
|
869
|
+
track_script = cloudscript
|
|
870
|
+
|
|
871
|
+
def work_context(self, activity: Any, attempt: Any = None) -> AbstractContextManager[_work_context.WorkContext]:
|
|
872
|
+
"""Run a block under an engineering activity (and optionally one of its attempts).
|
|
873
|
+
|
|
874
|
+
Every API request this client makes inside the block carries the work-context
|
|
875
|
+
header, so datasets published and runs reported there are stamped with it, and
|
|
876
|
+
the run report names the activity. Blocks nest (the inner one replaces the outer);
|
|
877
|
+
the context is per thread / asyncio task and per client. ``CLOUDSPRITE_ACTIVITY``
|
|
878
|
+
sets a process-wide default when no block is active. Server runs inherit the
|
|
879
|
+
context from their run token, so nothing is sent there.
|
|
880
|
+
|
|
881
|
+
Args:
|
|
882
|
+
activity: Activity id (UUID string, ``uuid.UUID``, or an object with ``.id``).
|
|
883
|
+
attempt: Optional attempt id of that activity (same forms).
|
|
884
|
+
|
|
885
|
+
Raises:
|
|
886
|
+
ValidationError: ``activity`` or ``attempt`` is not a UUID.
|
|
887
|
+
|
|
888
|
+
Example:
|
|
889
|
+
>>> with cs.work_context(activity="0b9c1f4e-...", attempt="5a1d2c3b-..."):
|
|
890
|
+
... cs.publish(traces=[t], name="s21-sweep")
|
|
891
|
+
"""
|
|
892
|
+
return self._work_scope.use(activity, attempt)
|
|
893
|
+
|
|
894
|
+
def report_run(self, status: str = "succeeded", error: str | None = None) -> dict[str, Any] | None:
|
|
895
|
+
"""Post the active cloudscript() run report immediately."""
|
|
896
|
+
lineage = self._lineage
|
|
897
|
+
if lineage is None or not lineage.is_tracking:
|
|
898
|
+
import warnings
|
|
899
|
+
|
|
900
|
+
warnings.warn(
|
|
901
|
+
"report_run() called without cloudscript()/sprite()/track_script(); ignoring",
|
|
902
|
+
stacklevel=2,
|
|
903
|
+
)
|
|
904
|
+
return None
|
|
905
|
+
|
|
906
|
+
project_slug = self.project_slug
|
|
907
|
+
if not project_slug:
|
|
908
|
+
raise ValidationError("No project specified. Call set_project() before report_run().")
|
|
909
|
+
|
|
910
|
+
project_id = self.resolve_project_id(project_slug)
|
|
911
|
+
return lineage.report_run(self.client, project_id, status=status, error=error)
|
|
912
|
+
|
|
913
|
+
def publish(
|
|
914
|
+
self,
|
|
915
|
+
traces: list[Any],
|
|
916
|
+
name: str,
|
|
917
|
+
description: str = "",
|
|
918
|
+
params: dict[str, Any] | None = None,
|
|
919
|
+
project: str | None = None,
|
|
920
|
+
) -> dict[str, Any]:
|
|
921
|
+
"""Publish computed traces as a new dataset."""
|
|
922
|
+
from cloudsprite._publish import publish_dataset
|
|
923
|
+
|
|
924
|
+
project_slug = project or self.project_slug
|
|
925
|
+
if not project_slug:
|
|
926
|
+
raise ValidationError("No project specified. Call set_project() or pass project='name'.")
|
|
927
|
+
|
|
928
|
+
project_id = self.resolve_project_id(project_slug)
|
|
929
|
+
lineage = self._lineage
|
|
930
|
+
|
|
931
|
+
result = publish_dataset(
|
|
932
|
+
client=self.client,
|
|
933
|
+
traces=traces,
|
|
934
|
+
name=name,
|
|
935
|
+
project_id=project_id,
|
|
936
|
+
description=description,
|
|
937
|
+
params=params,
|
|
938
|
+
lineage=lineage,
|
|
939
|
+
param_post_pool=self.param_post_pool,
|
|
940
|
+
)
|
|
941
|
+
if lineage is not None and lineage.is_tracking and isinstance(result, dict):
|
|
942
|
+
ds_id = result.get("id")
|
|
943
|
+
if ds_id:
|
|
944
|
+
lineage.record_output(ds_id)
|
|
945
|
+
return result
|