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/cli.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
"""CLI entry point: ``cloudsprite init`` (first-run configuration) and ``cloudsprite visualizer``.
|
|
2
|
+
|
|
3
|
+
Uses argparse so the console script is scriptable in CI (``--version``,
|
|
4
|
+
``--help``, non-interactive ``init`` flags). Packaging smoke tests must run
|
|
5
|
+
the entry point itself (``cloudsprite --help; echo $?`` → 0), not just
|
|
6
|
+
``import cloudsprite``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import getpass
|
|
13
|
+
import os
|
|
14
|
+
import sys
|
|
15
|
+
from collections.abc import Callable
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any, TextIO
|
|
18
|
+
|
|
19
|
+
from cloudsprite import _consent, _visualizer_cli
|
|
20
|
+
from cloudsprite._config import write_secure_file as _write_secure_file
|
|
21
|
+
from cloudsprite._version import sdk_version
|
|
22
|
+
|
|
23
|
+
CONFIG_DIR = ".cloudsprite"
|
|
24
|
+
CONFIG_FILE = "config"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _config_path() -> Path:
|
|
28
|
+
return Path.home() / CONFIG_DIR / CONFIG_FILE
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def init_config(
|
|
32
|
+
api_key: str,
|
|
33
|
+
team: str | None = None,
|
|
34
|
+
org: str | None = None,
|
|
35
|
+
base_url: str | None = None,
|
|
36
|
+
force: bool = False,
|
|
37
|
+
) -> Path:
|
|
38
|
+
"""Create ~/.cloudsprite/config with the given credentials.
|
|
39
|
+
|
|
40
|
+
The config directory is created mode 0700 and the file is written via an
|
|
41
|
+
atomic 0600 temp file so credentials never sit at umask-default perms.
|
|
42
|
+
"""
|
|
43
|
+
path = _config_path()
|
|
44
|
+
if path.exists() and not force:
|
|
45
|
+
raise FileExistsError(f"Config already exists at {path}. Use --force to overwrite.")
|
|
46
|
+
|
|
47
|
+
directory = path.parent
|
|
48
|
+
# Create with 0700; if it already exists, tighten to 0700 on POSIX.
|
|
49
|
+
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
50
|
+
if os.name != "nt":
|
|
51
|
+
directory.chmod(0o700)
|
|
52
|
+
|
|
53
|
+
lines = ["[default]", f'api_key = "{api_key}"']
|
|
54
|
+
if base_url:
|
|
55
|
+
lines.append(f'base_url = "{base_url}"')
|
|
56
|
+
if org:
|
|
57
|
+
lines.append(f'org = "{org}"')
|
|
58
|
+
if team:
|
|
59
|
+
lines.append(f'team = "{team}"')
|
|
60
|
+
lines.append("")
|
|
61
|
+
content = "\n".join(lines)
|
|
62
|
+
if path.exists():
|
|
63
|
+
# --force rewrites credentials; keep the user's stored privacy answers.
|
|
64
|
+
content += _consent.privacy_block(path)
|
|
65
|
+
|
|
66
|
+
_write_secure_file(path, content)
|
|
67
|
+
return path
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
71
|
+
"""Build the top-level argparse parser for the ``cloudsprite`` console script."""
|
|
72
|
+
parser = argparse.ArgumentParser(
|
|
73
|
+
prog="cloudsprite",
|
|
74
|
+
description="CloudSprite Python SDK command-line tools.",
|
|
75
|
+
)
|
|
76
|
+
parser.add_argument(
|
|
77
|
+
"--version",
|
|
78
|
+
action="version",
|
|
79
|
+
version=f"cloudsprite {sdk_version()}",
|
|
80
|
+
)
|
|
81
|
+
sub = parser.add_subparsers(dest="command")
|
|
82
|
+
|
|
83
|
+
init_p = sub.add_parser(
|
|
84
|
+
"init",
|
|
85
|
+
help="Write ~/.cloudsprite/config with API credentials",
|
|
86
|
+
description="Set up CloudSprite SDK credentials (non-interactive when flags are given).",
|
|
87
|
+
)
|
|
88
|
+
init_p.add_argument(
|
|
89
|
+
"--api-key",
|
|
90
|
+
dest="api_key",
|
|
91
|
+
default=None,
|
|
92
|
+
help="API key (sk_…). Required non-interactively; prompted if omitted.",
|
|
93
|
+
)
|
|
94
|
+
init_p.add_argument(
|
|
95
|
+
"--org",
|
|
96
|
+
default=None,
|
|
97
|
+
help="Default org (tenant) slug (optional; discovered from the API key when omitted on a TTY).",
|
|
98
|
+
)
|
|
99
|
+
init_p.add_argument(
|
|
100
|
+
"--team",
|
|
101
|
+
default=None,
|
|
102
|
+
help="Default team slug (optional; discovered from the API key when omitted on a TTY).",
|
|
103
|
+
)
|
|
104
|
+
init_p.add_argument(
|
|
105
|
+
"--base-url",
|
|
106
|
+
dest="base_url",
|
|
107
|
+
default=None,
|
|
108
|
+
help="API base URL (optional; defaults to production when omitted from config).",
|
|
109
|
+
)
|
|
110
|
+
init_p.add_argument(
|
|
111
|
+
"--force",
|
|
112
|
+
action="store_true",
|
|
113
|
+
help="Overwrite an existing config file.",
|
|
114
|
+
)
|
|
115
|
+
_visualizer_cli.add_parser(sub)
|
|
116
|
+
return parser
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _payload_list(data: Any) -> list[dict[str, Any]]:
|
|
120
|
+
if isinstance(data, list):
|
|
121
|
+
return [item for item in data if isinstance(item, dict)]
|
|
122
|
+
if isinstance(data, dict):
|
|
123
|
+
results = data.get("results") or []
|
|
124
|
+
if isinstance(results, list):
|
|
125
|
+
return [item for item in results if isinstance(item, dict)]
|
|
126
|
+
return []
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _select_resource(
|
|
130
|
+
items: list[dict[str, Any]],
|
|
131
|
+
*,
|
|
132
|
+
kind: str,
|
|
133
|
+
input_fn: Callable[[str], str],
|
|
134
|
+
stdout: TextIO,
|
|
135
|
+
) -> str | None:
|
|
136
|
+
"""Pick a slug from API rows: auto if one, numbered list if many."""
|
|
137
|
+
labelled: list[tuple[str, str]] = []
|
|
138
|
+
for item in items:
|
|
139
|
+
slug = str(item.get("slug") or "").strip()
|
|
140
|
+
name = str(item.get("name") or item.get("title") or slug).strip()
|
|
141
|
+
if slug or name:
|
|
142
|
+
labelled.append((name or slug, slug))
|
|
143
|
+
if not labelled:
|
|
144
|
+
print(f"No {kind}s visible for this key.", file=stdout)
|
|
145
|
+
return None
|
|
146
|
+
if len(labelled) == 1:
|
|
147
|
+
name, slug = labelled[0]
|
|
148
|
+
print(f"Using {kind} {name} ({slug})" if slug else f"Using {kind} {name}", file=stdout)
|
|
149
|
+
return slug or None
|
|
150
|
+
|
|
151
|
+
print(f"{kind.capitalize()}s:", file=stdout)
|
|
152
|
+
for i, (name, slug) in enumerate(labelled, 1):
|
|
153
|
+
extra = f" ({slug})" if slug else ""
|
|
154
|
+
print(f" {i}. {name}{extra}", file=stdout)
|
|
155
|
+
|
|
156
|
+
raw = input_fn(f"{kind.capitalize()} [1] (0 to skip): ").strip()
|
|
157
|
+
if raw == "0":
|
|
158
|
+
return None
|
|
159
|
+
if raw == "":
|
|
160
|
+
return labelled[0][1] or None
|
|
161
|
+
if raw.isdigit():
|
|
162
|
+
idx = int(raw)
|
|
163
|
+
if 1 <= idx <= len(labelled):
|
|
164
|
+
return labelled[idx - 1][1] or None
|
|
165
|
+
print(f"Error: choose 1–{len(labelled)}, or 0 to skip", file=sys.stderr)
|
|
166
|
+
return None
|
|
167
|
+
lowered = raw.lower()
|
|
168
|
+
for name, slug in labelled:
|
|
169
|
+
if slug.lower() == lowered or name.lower() == lowered:
|
|
170
|
+
return slug or None
|
|
171
|
+
print(f"Error: no {kind} matching {raw!r}", file=sys.stderr)
|
|
172
|
+
return None
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _discover_org_and_team(
|
|
176
|
+
api_key: str,
|
|
177
|
+
base_url: str | None,
|
|
178
|
+
*,
|
|
179
|
+
org: str | None,
|
|
180
|
+
team: str | None,
|
|
181
|
+
input_fn: Callable[[str], str],
|
|
182
|
+
stdout: TextIO,
|
|
183
|
+
) -> tuple[str | None, str | None, int]:
|
|
184
|
+
"""Authenticate, list orgs/teams, return (org, team, exit_code)."""
|
|
185
|
+
from cloudsprite._context import Client
|
|
186
|
+
from cloudsprite._exceptions import APIError, AuthError, ValidationError
|
|
187
|
+
|
|
188
|
+
cs = Client(api_key=api_key, base_url=base_url)
|
|
189
|
+
try:
|
|
190
|
+
cs.connect()
|
|
191
|
+
except (AuthError, APIError) as exc:
|
|
192
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
193
|
+
cs.close()
|
|
194
|
+
return org, team, 1
|
|
195
|
+
|
|
196
|
+
# A previous init may have stored a team (even a display name). Connect
|
|
197
|
+
# would apply it and GET /api/tenants/ would try to resolve X-Team-ID first.
|
|
198
|
+
cs._clear_scope()
|
|
199
|
+
|
|
200
|
+
try:
|
|
201
|
+
if org is None:
|
|
202
|
+
orgs = _payload_list(cs.client.get("/api/tenants/") or [])
|
|
203
|
+
org = _select_resource(orgs, kind="org", input_fn=input_fn, stdout=stdout)
|
|
204
|
+
if org:
|
|
205
|
+
cs.set_org(org)
|
|
206
|
+
if team is None:
|
|
207
|
+
try:
|
|
208
|
+
teams = [{"name": t.name, "slug": t.slug} for t in cs.teams]
|
|
209
|
+
except (AuthError, APIError, ValidationError) as exc:
|
|
210
|
+
print(f"Error listing teams: {exc}", file=sys.stderr)
|
|
211
|
+
return org, team, 1
|
|
212
|
+
team = _select_resource(teams, kind="team", input_fn=input_fn, stdout=stdout)
|
|
213
|
+
finally:
|
|
214
|
+
cs.close()
|
|
215
|
+
return org, team, 0
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _run_init(args: argparse.Namespace) -> int:
|
|
219
|
+
"""Execute ``cloudsprite init``; returns a process exit code."""
|
|
220
|
+
api_key = args.api_key
|
|
221
|
+
team = args.team
|
|
222
|
+
org = args.org
|
|
223
|
+
base_url = args.base_url
|
|
224
|
+
interactive = sys.stdin.isatty()
|
|
225
|
+
|
|
226
|
+
if not args.force and _config_path().exists():
|
|
227
|
+
print(
|
|
228
|
+
f"Error: Config already exists at {_config_path()}. Use --force to overwrite.",
|
|
229
|
+
file=sys.stderr,
|
|
230
|
+
)
|
|
231
|
+
return 1
|
|
232
|
+
|
|
233
|
+
if api_key is None:
|
|
234
|
+
if not interactive:
|
|
235
|
+
print(
|
|
236
|
+
"Error: --api-key is required when stdin is not a TTY",
|
|
237
|
+
file=sys.stderr,
|
|
238
|
+
)
|
|
239
|
+
return 1
|
|
240
|
+
try:
|
|
241
|
+
api_key = getpass.getpass("API key (input hidden): ").strip()
|
|
242
|
+
except Exception:
|
|
243
|
+
api_key = input("API key: ").strip()
|
|
244
|
+
if not api_key:
|
|
245
|
+
print("Error: API key is required", file=sys.stderr)
|
|
246
|
+
return 1
|
|
247
|
+
|
|
248
|
+
# Interactive (or TTY with a pasted --api-key): authenticate and list
|
|
249
|
+
# orgs/teams. Never prompt for base URL — production is the default;
|
|
250
|
+
# --base-url remains a flag for local/dev.
|
|
251
|
+
if interactive and (org is None or team is None):
|
|
252
|
+
org, team, status = _discover_org_and_team(
|
|
253
|
+
api_key,
|
|
254
|
+
base_url,
|
|
255
|
+
org=org,
|
|
256
|
+
team=team,
|
|
257
|
+
input_fn=input,
|
|
258
|
+
stdout=sys.stdout,
|
|
259
|
+
)
|
|
260
|
+
if status != 0:
|
|
261
|
+
return status
|
|
262
|
+
|
|
263
|
+
try:
|
|
264
|
+
path = init_config(
|
|
265
|
+
api_key=api_key,
|
|
266
|
+
org=org,
|
|
267
|
+
team=team,
|
|
268
|
+
base_url=base_url,
|
|
269
|
+
force=args.force,
|
|
270
|
+
)
|
|
271
|
+
except FileExistsError as e:
|
|
272
|
+
print(f"Error: {e}", file=sys.stderr)
|
|
273
|
+
return 1
|
|
274
|
+
|
|
275
|
+
print(f"Config written to {path}")
|
|
276
|
+
if org or team:
|
|
277
|
+
bits = [p for p in (f"org={org}" if org else None, f"team={team}" if team else None) if p]
|
|
278
|
+
print("Defaults: " + ", ".join(bits))
|
|
279
|
+
return 0
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def main(argv: list[str] | None = None) -> None:
|
|
283
|
+
"""Entry point for the ``cloudsprite`` console script.
|
|
284
|
+
|
|
285
|
+
Exit codes: 0 success / help / version; 1 usage or command error.
|
|
286
|
+
"""
|
|
287
|
+
parser = build_parser()
|
|
288
|
+
args = parser.parse_args(argv)
|
|
289
|
+
|
|
290
|
+
if args.command is None:
|
|
291
|
+
parser.print_help()
|
|
292
|
+
raise SystemExit(0)
|
|
293
|
+
|
|
294
|
+
if args.command == "init":
|
|
295
|
+
raise SystemExit(_run_init(args))
|
|
296
|
+
|
|
297
|
+
if args.command == "visualizer":
|
|
298
|
+
raise SystemExit(_visualizer_cli.run(args))
|
|
299
|
+
|
|
300
|
+
parser.error(f"Unknown command: {args.command}")
|
cloudsprite/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""CloudSprite resource modules."""
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
"""Base resource class with bracket notation and children support."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from typing import TYPE_CHECKING, Any, Generic, Iterator, TypeVar, cast
|
|
7
|
+
|
|
8
|
+
from cloudsprite._filtering import FilterExpression, GlobPattern, RegexPattern, parse_bracket_arg
|
|
9
|
+
from cloudsprite._resultset import ResultSet
|
|
10
|
+
from cloudsprite.resources._models import ResourceData, display_name, require_id
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from cloudsprite._client import HTTPClient
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
T = TypeVar("T")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Resource:
|
|
21
|
+
"""Shared base for client-bound API resources.
|
|
22
|
+
|
|
23
|
+
Carries ``_client``, ``_data``, ``id``, ``name``, and ``__repr__`` once so
|
|
24
|
+
concrete resources do not re-implement the same four members.
|
|
25
|
+
|
|
26
|
+
``name`` uses the API's display field: ``title`` when present (projects,
|
|
27
|
+
datasets, notebooks), otherwise ``name`` (teams, tags, instruments, …).
|
|
28
|
+
That fallback is for *display only* — bracket lookups never OR title with
|
|
29
|
+
slug (see :meth:`ResourceCollection._exact_match`).
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(self, client: HTTPClient, data: dict[str, Any]) -> None:
|
|
33
|
+
self._client = client
|
|
34
|
+
# Typed boundary: require a non-empty id; keep the full dict for
|
|
35
|
+
# resource-specific fields and PATCH merge.
|
|
36
|
+
require_id(cast(ResourceData, data))
|
|
37
|
+
self._data: dict[str, Any] = data
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def id(self) -> str:
|
|
41
|
+
"""Stable UUID of this resource."""
|
|
42
|
+
return require_id(cast(ResourceData, self._data))
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def name(self) -> str:
|
|
46
|
+
"""Display name (``title`` if present, else ``name``)."""
|
|
47
|
+
return display_name(cast(ResourceData, self._data))
|
|
48
|
+
|
|
49
|
+
def __repr__(self) -> str:
|
|
50
|
+
return f"{type(self).__name__}('{self.name}')"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class ResourceCollection(Generic[T]):
|
|
54
|
+
"""A collection of resources that supports bracket notation, .filter(), and iteration.
|
|
55
|
+
|
|
56
|
+
Type parameter ``T`` is the concrete resource class (``Project``, ``Dataset``, …).
|
|
57
|
+
|
|
58
|
+
Lookup fields
|
|
59
|
+
-------------
|
|
60
|
+
Exact bracket lookup matches **one field at a time**, in priority order:
|
|
61
|
+
|
|
62
|
+
1. ``id``
|
|
63
|
+
2. ``slug`` (when the resource type uses slugs)
|
|
64
|
+
3. ``name_field`` (configured per collection — ``title`` for Project/Dataset/
|
|
65
|
+
Notebook, ``name`` for Team/Tag/Instrument/…)
|
|
66
|
+
|
|
67
|
+
Multi-field OR matching was removed: a dataset titled the same as
|
|
68
|
+
another's slug must not silently resolve to the wrong object.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
def __init__(
|
|
72
|
+
self,
|
|
73
|
+
client: HTTPClient,
|
|
74
|
+
path: str,
|
|
75
|
+
resource_class: type[T],
|
|
76
|
+
name_field: str = "name",
|
|
77
|
+
extra_headers: dict[str, str] | None = None,
|
|
78
|
+
):
|
|
79
|
+
self._client = client
|
|
80
|
+
self._path = path
|
|
81
|
+
self._resource_class = resource_class
|
|
82
|
+
self._name_field = name_field
|
|
83
|
+
self._extra_headers = extra_headers
|
|
84
|
+
self._items: list[dict[str, Any]] | None = None
|
|
85
|
+
|
|
86
|
+
def _fetch_all(self) -> list[dict[str, Any]]:
|
|
87
|
+
if self._items is None:
|
|
88
|
+
from cloudsprite._pagination import auto_paginate
|
|
89
|
+
|
|
90
|
+
self._items = auto_paginate(self._client, self._path, headers=self._extra_headers)
|
|
91
|
+
return self._items
|
|
92
|
+
|
|
93
|
+
def __getitem__(self, key: Any) -> T | ResultSet[T]:
|
|
94
|
+
"""Look up resources by name, glob, regex, or filter expression.
|
|
95
|
+
|
|
96
|
+
**Return type is value-dependent** (accepted wart for the marquee bracket
|
|
97
|
+
API — do not split into ``.match()`` without an explicit API break):
|
|
98
|
+
|
|
99
|
+
* An **exact string** (no ``*`` / ``?``) yields a single ``T`` or raises
|
|
100
|
+
:class:`~cloudsprite.NotFoundError`.
|
|
101
|
+
* A **glob** (``"sweep-*"``), **regex** (``cs.regex(...)``), or
|
|
102
|
+
**filter** (``cs.params.temp > 25``) yields :class:`~cloudsprite._resultset.ResultSet` ``[T]``.
|
|
103
|
+
|
|
104
|
+
A ``*`` (or ``?``) in a name therefore changes the static return type.
|
|
105
|
+
Callers that need a guaranteed :class:`~cloudsprite._resultset.ResultSet`
|
|
106
|
+
should use :meth:`filter` instead of brackets. Type checkers see the
|
|
107
|
+
union; narrow with ``isinstance`` or assert after an exact lookup.
|
|
108
|
+
|
|
109
|
+
Example::
|
|
110
|
+
|
|
111
|
+
project = cs.projects["cable-qual"] # Project
|
|
112
|
+
many = cs.projects["cable-qual"].datasets["sweep-*"] # ResultSet[Dataset]
|
|
113
|
+
all_ds = cs.projects["cable-qual"].datasets.filter("*") # ResultSet[Dataset]
|
|
114
|
+
"""
|
|
115
|
+
parsed = parse_bracket_arg(key)
|
|
116
|
+
if isinstance(parsed, str):
|
|
117
|
+
return self._exact_match(parsed)
|
|
118
|
+
if isinstance(parsed, (GlobPattern, RegexPattern)):
|
|
119
|
+
return self._pattern_match(parsed)
|
|
120
|
+
if isinstance(parsed, FilterExpression):
|
|
121
|
+
return self._filter_match(parsed)
|
|
122
|
+
raise TypeError(f"Unsupported bracket argument: {type(key)}")
|
|
123
|
+
|
|
124
|
+
def _record_dataset_input(self, resource: T) -> None:
|
|
125
|
+
"""When cloudscript() is active, record Dataset reads as run inputs."""
|
|
126
|
+
if getattr(self._resource_class, "__name__", None) != "Dataset":
|
|
127
|
+
return
|
|
128
|
+
try:
|
|
129
|
+
owner = self._client.owner()
|
|
130
|
+
lineage = getattr(owner, "_lineage", None) if owner is not None else None
|
|
131
|
+
if lineage is not None and lineage.is_tracking:
|
|
132
|
+
lineage.record_access(resource.id, resource.name) # type: ignore[attr-defined]
|
|
133
|
+
except Exception: # pragma: no cover - lineage must never break a read
|
|
134
|
+
logger.debug("lineage input recording skipped", exc_info=True)
|
|
135
|
+
|
|
136
|
+
def _instantiate(self, item: dict[str, Any]) -> T:
|
|
137
|
+
resource = self._resource_class(self._client, data=item) # type: ignore[call-arg]
|
|
138
|
+
self._record_dataset_input(resource)
|
|
139
|
+
return resource
|
|
140
|
+
|
|
141
|
+
def _exact_match(self, key: str) -> T:
|
|
142
|
+
"""Resolve an exact bracket key via priority-ordered single-field match.
|
|
143
|
+
|
|
144
|
+
Order: ``id`` → ``slug`` → ``name_field``. First non-empty match set
|
|
145
|
+
wins; within a tier the first list item is returned (server order).
|
|
146
|
+
"""
|
|
147
|
+
from cloudsprite._exceptions import NotFoundError
|
|
148
|
+
|
|
149
|
+
items = self._fetch_all()
|
|
150
|
+
for field in ("id", "slug", self._name_field):
|
|
151
|
+
for item in items:
|
|
152
|
+
if item.get(field) == key:
|
|
153
|
+
return self._instantiate(item)
|
|
154
|
+
raise NotFoundError(self._resource_class.__name__, key)
|
|
155
|
+
|
|
156
|
+
def _pattern_match(self, pattern: GlobPattern | RegexPattern) -> ResultSet[T]:
|
|
157
|
+
"""Match glob/regex against ``name_field`` and ``slug`` independently.
|
|
158
|
+
|
|
159
|
+
Unlike exact match, pattern results are a *set* of resources, so
|
|
160
|
+
matching either field is safe: there is no first-wins ambiguity that
|
|
161
|
+
can silently return the wrong single object (the defect exact
|
|
162
|
+
match avoids). Including slug keeps ``projects["cable-*"]`` working
|
|
163
|
+
when the marquee query is slug-shaped.
|
|
164
|
+
"""
|
|
165
|
+
matches: list[T] = []
|
|
166
|
+
for item in self._fetch_all():
|
|
167
|
+
candidates: list[str] = []
|
|
168
|
+
field_val = item.get(self._name_field)
|
|
169
|
+
if field_val is not None and field_val != "":
|
|
170
|
+
candidates.append(str(field_val))
|
|
171
|
+
slug_val = item.get("slug")
|
|
172
|
+
if slug_val is not None and slug_val != "" and str(slug_val) not in candidates:
|
|
173
|
+
candidates.append(str(slug_val))
|
|
174
|
+
if any(pattern.matches(c) for c in candidates):
|
|
175
|
+
matches.append(self._instantiate(item))
|
|
176
|
+
return ResultSet(matches)
|
|
177
|
+
|
|
178
|
+
def _filter_match(self, expr: FilterExpression) -> ResultSet[T]:
|
|
179
|
+
matches: list[T] = []
|
|
180
|
+
for item in self._fetch_all():
|
|
181
|
+
params_raw = item.get("parameters", item.get("params", {}))
|
|
182
|
+
# Handle both list-of-dicts and dict params
|
|
183
|
+
if isinstance(params_raw, list):
|
|
184
|
+
params: dict[str, Any] = {}
|
|
185
|
+
for p in params_raw:
|
|
186
|
+
if not isinstance(p, dict):
|
|
187
|
+
continue
|
|
188
|
+
key = p.get("parameter_key_title") or p.get("key")
|
|
189
|
+
if key is not None:
|
|
190
|
+
params[str(key)] = p["value"]
|
|
191
|
+
else:
|
|
192
|
+
params = params_raw if isinstance(params_raw, dict) else {}
|
|
193
|
+
if expr.evaluate(params):
|
|
194
|
+
resource = self._resource_class(self._client, data=item) # type: ignore[call-arg]
|
|
195
|
+
self._record_dataset_input(resource)
|
|
196
|
+
matches.append(resource)
|
|
197
|
+
return ResultSet(matches)
|
|
198
|
+
|
|
199
|
+
def filter(self, arg: Any = None, **kwargs: Any) -> ResultSet[T]:
|
|
200
|
+
"""Explicit filter — equivalent to bracket notation for patterns.
|
|
201
|
+
|
|
202
|
+
Always returns a :class:`~cloudsprite._resultset.ResultSet` (possibly empty),
|
|
203
|
+
never a single resource. Prefer this when you need a stable return type.
|
|
204
|
+
"""
|
|
205
|
+
if arg is not None:
|
|
206
|
+
parsed = parse_bracket_arg(arg)
|
|
207
|
+
if isinstance(parsed, str):
|
|
208
|
+
parsed = GlobPattern(parsed) if "*" in parsed or "?" in parsed else parsed
|
|
209
|
+
if isinstance(parsed, (GlobPattern, RegexPattern)):
|
|
210
|
+
return self._pattern_match(parsed)
|
|
211
|
+
if isinstance(parsed, FilterExpression):
|
|
212
|
+
return self._filter_match(parsed)
|
|
213
|
+
return self._pattern_match(GlobPattern("*")) # no filter = all
|
|
214
|
+
|
|
215
|
+
def __iter__(self) -> Iterator[T]:
|
|
216
|
+
"""Iterate items lazily — pages are fetched on-demand."""
|
|
217
|
+
from cloudsprite._pagination import auto_paginate_iter
|
|
218
|
+
|
|
219
|
+
for item in auto_paginate_iter(self._client, self._path, headers=self._extra_headers):
|
|
220
|
+
resource = self._resource_class(self._client, data=item) # type: ignore[call-arg]
|
|
221
|
+
self._record_dataset_input(resource)
|
|
222
|
+
yield resource
|
|
223
|
+
|
|
224
|
+
# Query params that should be forwarded from the list URL to create requests.
|
|
225
|
+
# Other params (include_parameters, pagination) are list-only and must not leak.
|
|
226
|
+
_CREATE_FORWARD_PARAMS = frozenset({"project_id", "notebook_id", "team_id"})
|
|
227
|
+
|
|
228
|
+
# Resource classes that need injected create fields (e.g. Project.visibility,
|
|
229
|
+
# which its schema declares required) define their own ``_CREATE_DEFAULTS``.
|
|
230
|
+
# Nothing is injected collection-wide — every resource type must not get
|
|
231
|
+
# visibility unless its endpoint accepts it.
|
|
232
|
+
# Note this is inherited: a subclass of Project also gets its defaults.
|
|
233
|
+
_CREATE_DEFAULTS: dict[str, Any] = {}
|
|
234
|
+
|
|
235
|
+
def create(self, **kwargs: Any) -> T:
|
|
236
|
+
"""Create a new resource in this collection.
|
|
237
|
+
|
|
238
|
+
Passes all kwargs as the JSON body to POST on the collection endpoint.
|
|
239
|
+
Context parameters (like project_id) are automatically inherited from
|
|
240
|
+
the collection's URL if not explicitly provided.
|
|
241
|
+
|
|
242
|
+
Returns:
|
|
243
|
+
A typed resource object for the newly created item.
|
|
244
|
+
|
|
245
|
+
Example:
|
|
246
|
+
>>> project.datasets.create(title="New Dataset")
|
|
247
|
+
Dataset('New Dataset')
|
|
248
|
+
"""
|
|
249
|
+
# Strip query params from POST path
|
|
250
|
+
post_path = self._path.split("?")[0]
|
|
251
|
+
|
|
252
|
+
# Inject per-resource-class defaults only. An empty dict on the resource
|
|
253
|
+
# class is respected as "inject nothing", not treated as unset.
|
|
254
|
+
defaults = getattr(self._resource_class, "_CREATE_DEFAULTS", {})
|
|
255
|
+
for key, default_val in defaults.items():
|
|
256
|
+
if key not in kwargs:
|
|
257
|
+
kwargs[key] = default_val
|
|
258
|
+
|
|
259
|
+
# Forward only known context params (project_id, etc.) — not display params
|
|
260
|
+
if "?" in self._path:
|
|
261
|
+
query_str = self._path.split("?", 1)[1]
|
|
262
|
+
for pair in query_str.split("&"):
|
|
263
|
+
if "=" not in pair:
|
|
264
|
+
continue
|
|
265
|
+
key, value = pair.split("=", 1)
|
|
266
|
+
if key in self._CREATE_FORWARD_PARAMS and key not in kwargs:
|
|
267
|
+
kwargs[key] = value
|
|
268
|
+
|
|
269
|
+
# Stamp provenance on dataset creates only
|
|
270
|
+
if post_path.rstrip("/").endswith("/datasets") or getattr(self._resource_class, "__name__", None) == "Dataset":
|
|
271
|
+
from cloudsprite.resources.datasets import apply_sdk_dataset_source
|
|
272
|
+
|
|
273
|
+
kwargs = apply_sdk_dataset_source(kwargs)
|
|
274
|
+
|
|
275
|
+
data = self._client.post(post_path, json=kwargs, headers=self._extra_headers)
|
|
276
|
+
self._items = None # invalidate cache
|
|
277
|
+
return self._resource_class(self._client, data=data) # type: ignore[call-arg]
|
|
278
|
+
|
|
279
|
+
@property
|
|
280
|
+
def count(self) -> int:
|
|
281
|
+
"""Number of items in the collection (fetches all pages)."""
|
|
282
|
+
return len(self._fetch_all())
|
|
283
|
+
|
|
284
|
+
def first(self) -> T | None:
|
|
285
|
+
"""Return the first item in the collection, or None if empty.
|
|
286
|
+
|
|
287
|
+
Uses the lazy iterator so only the first page is fetched.
|
|
288
|
+
"""
|
|
289
|
+
from cloudsprite._pagination import auto_paginate_iter
|
|
290
|
+
|
|
291
|
+
for item in auto_paginate_iter(self._client, self._path, headers=self._extra_headers):
|
|
292
|
+
return self._resource_class(self._client, data=item) # type: ignore[call-arg]
|
|
293
|
+
return None
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Typed payload shapes at the API boundary.
|
|
2
|
+
|
|
3
|
+
Resource objects still hold the full JSON dict for PATCH merge and
|
|
4
|
+
resource-specific fields, but identifiers and display names are extracted
|
|
5
|
+
through these helpers so contract drift fails loudly instead of silently
|
|
6
|
+
resolving the wrong object via multi-field OR matching.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import Any, TypedDict
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class ResourceData(TypedDict, total=False):
|
|
15
|
+
"""Common fields returned by CloudSprite list/detail endpoints.
|
|
16
|
+
|
|
17
|
+
Not every resource has every key: teams use ``name``, projects/datasets/
|
|
18
|
+
notebooks use ``title``, many have ``slug``. ``id`` is required for a
|
|
19
|
+
bound :class:`~cloudsprite.resources._base.Resource`.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
id: str
|
|
23
|
+
name: str
|
|
24
|
+
title: str
|
|
25
|
+
slug: str
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def require_id(data: ResourceData | dict[str, Any]) -> str:
|
|
29
|
+
"""Return the resource id, or raise if missing/empty.
|
|
30
|
+
|
|
31
|
+
Loud failure replaces the prior pattern of ``str(data.get("id", ""))``
|
|
32
|
+
which produced resources with empty ids that later failed obscurely.
|
|
33
|
+
"""
|
|
34
|
+
raw = data.get("id")
|
|
35
|
+
if raw is None or raw == "":
|
|
36
|
+
raise ValueError("API resource payload missing required field 'id'")
|
|
37
|
+
return str(raw)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def display_name(data: ResourceData | dict[str, Any]) -> str:
|
|
41
|
+
"""Human-facing label: ``title`` preferred, then ``name``.
|
|
42
|
+
|
|
43
|
+
Used only for ``Resource.name`` / ``__repr__`` — never for bracket
|
|
44
|
+
lookup matching (see :meth:`ResourceCollection._exact_match`).
|
|
45
|
+
"""
|
|
46
|
+
if "title" in data and data["title"] is not None:
|
|
47
|
+
return str(data["title"])
|
|
48
|
+
if "name" in data and data["name"] is not None:
|
|
49
|
+
return str(data["name"])
|
|
50
|
+
return ""
|