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,245 @@
1
+ """Search resources — global and trace-specific search across CloudSprite.
2
+
3
+ Example:
4
+ >>> results = cs.search("cable 25C")
5
+ >>> for r in results:
6
+ ... print(r.type, r.name, r.score)
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import TYPE_CHECKING, Any, cast
12
+
13
+ from cloudsprite._exceptions import APIError, ValidationError
14
+
15
+ if TYPE_CHECKING:
16
+ from cloudsprite._client import HTTPClient
17
+
18
+ # Actual GET /api/search/ groups. No traces group.
19
+ SEARCH_GROUPS: tuple[str, ...] = (
20
+ "projects",
21
+ "datasets",
22
+ "notebooks",
23
+ "reports",
24
+ "parameters",
25
+ "tags",
26
+ "instruments",
27
+ )
28
+ _GROUP_TYPE = {
29
+ "projects": "project",
30
+ "datasets": "dataset",
31
+ "notebooks": "notebook",
32
+ "reports": "report",
33
+ "parameters": "parameter",
34
+ "tags": "tag",
35
+ "instruments": "instrument",
36
+ }
37
+ _SUPPORTED_SEARCH_KWARGS = frozenset({"limit"})
38
+ _SCOPED_SEARCH_HINT = (
39
+ "GET /api/search/ accepts only q and limit. "
40
+ "To scope datasets to a project, use Project.datasets or cs.datasets "
41
+ "with project_id=.... To restrict by resource kind, call cs.search(q) and "
42
+ "filter results by .type, or list the collection directly "
43
+ "(Project.datasets, Project.notebooks, reports)."
44
+ )
45
+
46
+
47
+ def _optional_str(value: Any) -> str | None:
48
+ if value is None or value == "":
49
+ return None
50
+ return str(value)
51
+
52
+
53
+ class SearchResult:
54
+ """A single search result from the global search API.
55
+
56
+ Attributes:
57
+ type: Resource type ('project', 'dataset', 'notebook', etc.).
58
+ id: Unique identifier (UUID).
59
+ name: Display name/title of the matched resource.
60
+ title: Same as name (API field is title).
61
+ slug: Resource slug when the API provides one, else None.
62
+ project_id: Parent project id when provided, else None.
63
+ project_slug: Parent project slug when provided, else None.
64
+ score: Relevance score when the API returns one; otherwise None
65
+ (unknown — global search does not currently return scores).
66
+ data: Full response data dict for advanced use.
67
+ """
68
+
69
+ def __init__(self, data: dict[str, Any], *, result_type: str | None = None):
70
+ self._data = dict(data)
71
+ if result_type and "type" not in self._data:
72
+ self._data["type"] = result_type
73
+
74
+ @property
75
+ def type(self) -> str:
76
+ """Resource type: 'project', 'dataset', 'notebook', etc."""
77
+ return str(self._data.get("type", ""))
78
+
79
+ @property
80
+ def id(self) -> str:
81
+ """Unique identifier of the matched resource."""
82
+ return str(self._data.get("id", ""))
83
+
84
+ @property
85
+ def name(self) -> str:
86
+ """Display name/title of the matched resource."""
87
+ return str(self._data.get("title", self._data.get("name", "")))
88
+
89
+ @property
90
+ def title(self) -> str:
91
+ """API title; same value as name."""
92
+ return self.name
93
+
94
+ @property
95
+ def slug(self) -> str | None:
96
+ """Resource slug when provided by the API."""
97
+ return _optional_str(self._data.get("slug"))
98
+
99
+ @property
100
+ def project_id(self) -> str | None:
101
+ """Parent project id when provided by the API."""
102
+ return _optional_str(self._data.get("project_id"))
103
+
104
+ @property
105
+ def project_slug(self) -> str | None:
106
+ """Parent project slug when provided by the API."""
107
+ return _optional_str(self._data.get("project_slug"))
108
+
109
+ @property
110
+ def subtitle(self) -> str:
111
+ """API subtitle when provided."""
112
+ return str(self._data.get("subtitle", ""))
113
+
114
+ @property
115
+ def score(self) -> float | None:
116
+ """Relevance score when returned; None if the API omitted it."""
117
+ if "score" not in self._data or self._data.get("score") is None:
118
+ return None
119
+ return float(self._data["score"])
120
+
121
+ @property
122
+ def data(self) -> dict[str, Any]:
123
+ """Raw response data for this result."""
124
+ return self._data
125
+
126
+ def __repr__(self) -> str:
127
+ return f"SearchResult(type='{self.type}', name='{self.name}')"
128
+
129
+
130
+ def _type_from_group(group: str) -> str:
131
+ if group in _GROUP_TYPE:
132
+ return _GROUP_TYPE[group]
133
+ if group.endswith("ies") and len(group) > 3:
134
+ return group[:-3] + "y"
135
+ if group.endswith("s") and not group.endswith("ss") and len(group) > 1:
136
+ return group[:-1]
137
+ return group
138
+
139
+
140
+ def _results_from_group(group: str, items: list[Any]) -> list[SearchResult]:
141
+ result_type = _type_from_group(group)
142
+ return [SearchResult(item, result_type=result_type) for item in items if isinstance(item, dict)]
143
+
144
+
145
+ def _flatten_search_payload(data: Any) -> list[SearchResult]:
146
+ """Flatten a grouped SearchResponse (or legacy items list) into SearchResult rows.
147
+
148
+ Raises APIError when the body is not a search payload, so upstream errors
149
+ and unknown shapes cannot look like a successful empty result.
150
+ """
151
+ if isinstance(data, list):
152
+ return [SearchResult(item) for item in data if isinstance(item, dict)]
153
+ if not isinstance(data, dict):
154
+ raise APIError(0, f"Unexpected search response type: {type(data).__name__}", None)
155
+
156
+ known_present = [key for key in SEARCH_GROUPS if key in data]
157
+ if known_present:
158
+ results: list[SearchResult] = []
159
+ seen: set[str] = set()
160
+ for group in SEARCH_GROUPS:
161
+ value = data.get(group)
162
+ if not isinstance(value, list):
163
+ continue
164
+ seen.add(group)
165
+ results.extend(_results_from_group(group, value))
166
+ for key, value in data.items():
167
+ if key in seen or key == "items" or not isinstance(value, list):
168
+ continue
169
+ results.extend(_results_from_group(key, value))
170
+ return results
171
+
172
+ items = data.get("items")
173
+ if isinstance(items, list):
174
+ return [SearchResult(item) for item in items if isinstance(item, dict)]
175
+
176
+ extra_groups = [key for key, value in data.items() if isinstance(value, list)]
177
+ if extra_groups:
178
+ results = []
179
+ for key in extra_groups:
180
+ value = data[key]
181
+ if isinstance(value, list):
182
+ results.extend(_results_from_group(key, value))
183
+ return results
184
+
185
+ raise APIError(
186
+ 0,
187
+ "Unexpected search response shape: expected grouped SearchResponse "
188
+ f"(projects/datasets/notebooks/reports/parameters/tags/instruments) or items[]. Got keys: {sorted(data)}",
189
+ data,
190
+ )
191
+
192
+
193
+ def search(
194
+ client: HTTPClient,
195
+ query: str,
196
+ extra_headers: dict[str, str] | None = None,
197
+ **kwargs: Any,
198
+ ) -> list[SearchResult]:
199
+ """Perform a global search across all CloudSprite resources.
200
+
201
+ Args:
202
+ client: Authenticated HTTPClient instance.
203
+ query: Search query string (mapped to ``q``).
204
+ extra_headers: Additional headers (e.g. X-Team-ID).
205
+ **kwargs: Supported query params:
206
+ - limit (int): Max hits per group (API default 5).
207
+
208
+ ``type`` and ``project_id`` are not accepted by GET /api/search/.
209
+ Passing them raises ValidationError. Scope datasets with
210
+ Project.datasets / cs.datasets(project_id=...), or call search(q)
211
+ and filter results by ``.type``.
212
+
213
+ Returns:
214
+ List of SearchResult objects. Group order follows the API
215
+ (projects, datasets, notebooks, reports, parameters, tags,
216
+ instruments). Relevance ``score`` is None unless the API returns one.
217
+ """
218
+ if not query:
219
+ return []
220
+ unsupported = sorted(key for key in kwargs if key not in _SUPPORTED_SEARCH_KWARGS)
221
+ if unsupported:
222
+ names = ", ".join(unsupported)
223
+ raise ValidationError(f"Global search does not support {names}. {_SCOPED_SEARCH_HINT}")
224
+ params: dict[str, Any] = {"q": query}
225
+ if "limit" in kwargs:
226
+ params["limit"] = kwargs["limit"]
227
+ data = client.get("/api/search/", params=params, headers=extra_headers)
228
+ return _flatten_search_payload(data)
229
+
230
+
231
+ def search_traces(client: HTTPClient, **kwargs: Any) -> list[dict[str, Any]]:
232
+ """Search for traces across all datasets.
233
+
234
+ Args:
235
+ client: Authenticated HTTPClient instance.
236
+ **kwargs: Filters passed as query params:
237
+ - x_unit (str): Filter by x-axis unit (e.g. "Hz").
238
+ - y_unit (str): Filter by y-axis unit (e.g. "dB").
239
+ - name (str): Filter by trace name (e.g. "S21").
240
+ - project_id (str): Scope to a specific project.
241
+
242
+ Returns:
243
+ List of trace metadata dicts.
244
+ """
245
+ return cast(list[dict[str, Any]], client.get("/api/traces/", params=kwargs))
@@ -0,0 +1,229 @@
1
+ """Share links — public read-only links to a dataset, notebook or figure.
2
+
3
+ Parity with the generic owner API ``/api/share-links/``: list, create,
4
+ revoke and regenerate. Authorization is per object, never from scope headers: no
5
+ ``<type>:read`` is a 404, ``<type>:read`` without ``<type>:share`` is a 403.
6
+
7
+ The plaintext link is returned **once**, by :meth:`ShareLinkCollection.create`
8
+ and :meth:`ShareLink.regenerate`. Every other response carries only a token
9
+ prefix. The SDK keeps the plaintext in memory on that one object, never logs it
10
+ and leaves it out of ``repr``.
11
+
12
+ Example::
13
+
14
+ link = cs.shares.create(dataset)
15
+ print(link.share_url) # the only time the URL is available
16
+ link.revoke()
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from datetime import datetime
22
+ from typing import Any
23
+
24
+ from cloudsprite._exceptions import ValidationError, validate_id
25
+ from cloudsprite.resources._base import Resource
26
+
27
+ SHAREABLE_TYPES = ("dataset", "notebook", "figure")
28
+
29
+ _PATH = "/api/share-links/"
30
+
31
+
32
+ def _object_ref(target: Any, object_type: str | None) -> tuple[str, str]:
33
+ """Resolve ``(object_type, object_id)`` from a resource object or an id plus ``object_type``."""
34
+ inferred = {"Dataset": "dataset", "Notebook": "notebook", "Figure": "figure"}.get(type(target).__name__)
35
+ kind = object_type or inferred
36
+ if kind not in SHAREABLE_TYPES:
37
+ raise ValidationError(
38
+ f"Cannot share {type(target).__name__}: pass a Dataset, Notebook or Figure, "
39
+ f"or an id with object_type= one of {', '.join(SHAREABLE_TYPES)}"
40
+ )
41
+ if inferred and object_type and inferred != object_type:
42
+ raise ValidationError(f"object_type={object_type!r} does not match the {type(target).__name__} passed")
43
+ raw = getattr(target, "id", target)
44
+ return kind, validate_id(str(raw), "object_id")
45
+
46
+
47
+ def _iso(value: datetime | str | None) -> str | None:
48
+ if value is None:
49
+ return None
50
+ if isinstance(value, datetime):
51
+ return value.isoformat()
52
+ return str(value)
53
+
54
+
55
+ class ShareLink(Resource):
56
+ """One share link. ``share_url`` is set only on the object returned by create or regenerate."""
57
+
58
+ def __init__(self, client: Any, data: dict[str, Any]) -> None:
59
+ data = dict(data)
60
+ # Held outside ``_data`` so no dict dump, merge or serialisation of the resource can leak it.
61
+ self._share_url: str | None = data.pop("share_url", None) or None
62
+ super().__init__(client, data)
63
+
64
+ def __repr__(self) -> str:
65
+ return f"ShareLink({self.object_type}:{self.object_id}, prefix='{self.token_prefix}', status='{self.status}')"
66
+
67
+ @property
68
+ def name(self) -> str:
69
+ """Token prefix, the only identifier of the link that is safe to print."""
70
+ return self.token_prefix
71
+
72
+ @property
73
+ def share_url(self) -> str | None:
74
+ """The plaintext link, present only on create/regenerate results. Treat it as a secret."""
75
+ return self._share_url
76
+
77
+ @property
78
+ def token_prefix(self) -> str:
79
+ """Leading characters of the token, for recognising a link in a list."""
80
+ return str(self._data.get("token_prefix", ""))
81
+
82
+ @property
83
+ def object_type(self) -> str:
84
+ """``dataset``, ``notebook`` or ``figure``."""
85
+ return str(self._data.get("object_type", ""))
86
+
87
+ @property
88
+ def object_id(self) -> str:
89
+ """UUID of the shared object."""
90
+ return str(self._data.get("object_id", ""))
91
+
92
+ @property
93
+ def status(self) -> str:
94
+ """Link state as reported by the API (for example ``active``, ``revoked`` or ``expired``)."""
95
+ return str(self._data.get("status", ""))
96
+
97
+ @property
98
+ def allow_download(self) -> bool:
99
+ """True when anyone holding the link may download the full data."""
100
+ return bool(self._data.get("allow_download", False))
101
+
102
+ @property
103
+ def show_org_name(self) -> bool:
104
+ """True when the public page shows the organization name."""
105
+ return bool(self._data.get("show_org_name", True))
106
+
107
+ @property
108
+ def expires_at(self) -> str | None:
109
+ """Expiry timestamp, or None for a link that does not expire."""
110
+ raw = self._data.get("expires_at")
111
+ return str(raw) if raw else None
112
+
113
+ @property
114
+ def revoked_at(self) -> str | None:
115
+ """When the link was revoked, or None."""
116
+ raw = self._data.get("revoked_at")
117
+ return str(raw) if raw else None
118
+
119
+ @property
120
+ def view_count(self) -> int:
121
+ """Number of recorded views."""
122
+ raw = self._data.get("view_count", 0)
123
+ return int(raw) if raw is not None else 0
124
+
125
+ @property
126
+ def last_viewed_at(self) -> str | None:
127
+ """Timestamp of the latest view, or None."""
128
+ raw = self._data.get("last_viewed_at")
129
+ return str(raw) if raw else None
130
+
131
+ def _apply(self, data: dict[str, Any]) -> ShareLink:
132
+ data = dict(data)
133
+ url = data.pop("share_url", None)
134
+ self._data.update(data)
135
+ self._share_url = url or None
136
+ return self
137
+
138
+ def revoke(self) -> ShareLink:
139
+ """Stop sharing: the link stops working immediately. Revoking twice is harmless.
140
+
141
+ Server: ``DELETE /api/share-links/{id}``.
142
+ """
143
+ data = self._client.delete(f"/api/share-links/{self.id}")
144
+ if isinstance(data, dict):
145
+ self._apply(data)
146
+ return self
147
+
148
+ def regenerate(self) -> ShareLink:
149
+ """Replace the token; the old link stops working immediately.
150
+
151
+ The new plaintext link is in :attr:`share_url` on the returned object and is not retrievable again.
152
+
153
+ Server: ``POST /api/share-links/{id}/regenerate``.
154
+ """
155
+ data = self._client.post(f"/api/share-links/{self.id}/regenerate")
156
+ if not isinstance(data, dict):
157
+ raise ValidationError("Unexpected share link response")
158
+ return self._apply(data)
159
+
160
+
161
+ class ShareLinkCollection:
162
+ """Share links the caller may manage. Reach it as ``cs.shares``."""
163
+
164
+ def __init__(self, client: Any) -> None:
165
+ self._client = client
166
+
167
+ def list(
168
+ self,
169
+ target: Any = None,
170
+ *,
171
+ object_type: str | None = None,
172
+ team: Any = None,
173
+ include_revoked: bool = False,
174
+ ) -> list[ShareLink]:
175
+ """List share links.
176
+
177
+ With ``target`` (a Dataset, Notebook or Figure, or an id plus ``object_type``): every link of that
178
+ object, history included. Without it: the team's active links (``team`` or the default team), limited to
179
+ objects you may share; ``include_revoked=True`` adds revoked ones.
180
+
181
+ Server: ``GET /api/share-links/``.
182
+ """
183
+ params: dict[str, Any] = {}
184
+ if target is not None:
185
+ kind, object_id = _object_ref(target, object_type)
186
+ params.update(object_type=kind, object_id=object_id)
187
+ else:
188
+ if object_type is not None:
189
+ raise ValidationError("object_type needs a target")
190
+ if team is not None:
191
+ params["team_id"] = validate_id(str(getattr(team, "id", team)), "team_id")
192
+ if include_revoked:
193
+ params["include_revoked"] = "true"
194
+ payload = self._client.get(_PATH, params=params or None)
195
+ if not isinstance(payload, list):
196
+ raise ValidationError("Unexpected share link list response")
197
+ return [ShareLink(self._client, item) for item in payload if isinstance(item, dict)]
198
+
199
+ def create(
200
+ self,
201
+ target: Any,
202
+ *,
203
+ object_type: str | None = None,
204
+ allow_download: bool = False,
205
+ expires_at: datetime | str | None = None,
206
+ show_org_name: bool = True,
207
+ ) -> ShareLink:
208
+ """Create the share link for an object. At most one active link per object (409 otherwise).
209
+
210
+ The plaintext link is in ``share_url`` of the result only. ``allow_download`` lets anyone holding the
211
+ link download the full data and also needs ``dataset:export``. ``expires_at`` must be in the future
212
+ (a datetime, or an ISO 8601 string).
213
+
214
+ Server: ``POST /api/share-links/``.
215
+ """
216
+ kind, object_id = _object_ref(target, object_type)
217
+ body: dict[str, Any] = {
218
+ "object_type": kind,
219
+ "object_id": object_id,
220
+ "allow_download": allow_download,
221
+ "show_org_name": show_org_name,
222
+ }
223
+ expiry = _iso(expires_at)
224
+ if expiry is not None:
225
+ body["expires_at"] = expiry
226
+ data = self._client.post(_PATH, json=body)
227
+ if not isinstance(data, dict):
228
+ raise ValidationError("Unexpected share link response")
229
+ return ShareLink(self._client, data)
@@ -0,0 +1,15 @@
1
+ """Legacy module alias for :mod:`cloudsprite.resources.cloudscripts`.
2
+
3
+ Kept for one minor release so ``from cloudsprite.resources.sprites import Sprite``
4
+ keeps working. The names are true aliases (same objects):
5
+ ``Sprite is CloudScript``. New code should import from
6
+ ``cloudsprite.resources.cloudscripts``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from cloudsprite.resources.cloudscripts import CloudScript as Sprite
12
+ from cloudsprite.resources.cloudscripts import CloudScriptCollection as SpriteCollection
13
+ from cloudsprite.resources.cloudscripts import CloudScriptVersion as SpriteVersion
14
+
15
+ __all__ = ["Sprite", "SpriteCollection", "SpriteVersion"]
@@ -0,0 +1,107 @@
1
+ """Tag resource and team tag collection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from cloudsprite._exceptions import APIError, ValidationError
8
+ from cloudsprite.resources._base import Resource, ResourceCollection
9
+
10
+
11
+ class Tag(Resource):
12
+ """A label that can be applied to datasets within a project."""
13
+
14
+ @property
15
+ def color(self) -> str:
16
+ """Color hex/name for UI display, or empty if unset."""
17
+ return str(self._data.get("color", ""))
18
+
19
+ def update(self, **kwargs: Any) -> None:
20
+ """Update tag fields (name, color)."""
21
+ data = self._client.patch(f"/api/tags/{self.id}", json=kwargs)
22
+ if isinstance(data, dict):
23
+ self._data.update(data)
24
+
25
+ def delete(self) -> None:
26
+ """Delete this tag.
27
+
28
+ Server: ``DELETE /api/tags/{id}`` (hard delete; tags are not trashable).
29
+ """
30
+ self._client.delete(f"/api/tags/{self.id}")
31
+
32
+
33
+ class TagCollection(ResourceCollection[Tag]):
34
+ """Tags of the current team (``cs.tags``).
35
+
36
+ Supports the usual collection surface: ``cs.tags["PASS"]`` (get by name),
37
+ iteration, ``filter("P*")``, ``count`` and :meth:`create`. Update and delete
38
+ live on the returned :class:`Tag` (``cs.tags["PASS"].update(color=...)``,
39
+ ``cs.tags["PASS"].delete()``).
40
+
41
+ Server: ``GET|POST /api/tags/?team_id=``. Names are unique per team.
42
+ """
43
+
44
+ # Create statuses that mean "a tag with this name may already exist":
45
+ # 400/409 for a validation-style duplicate, 500 for servers that predate the
46
+ # idempotent POST (an unhandled IntegrityError on ``unique_tag_per_team``),
47
+ # 502-504 when a gateway gave up on a POST the server may have committed.
48
+ _DUPLICATE_STATUSES = frozenset({400, 409, 500, 502, 503, 504})
49
+
50
+ def _find_by_name(self, name: str) -> Tag | None:
51
+ """Fresh exact-name lookup (bypasses the collection cache)."""
52
+ from cloudsprite._pagination import auto_paginate
53
+
54
+ for item in auto_paginate(self._client, self._path, headers=self._extra_headers):
55
+ if item.get("name") == name:
56
+ return Tag(self._client, data=item)
57
+ return None
58
+
59
+ def get(self, name: str) -> Tag | None:
60
+ """Return the tag with exactly this name, or ``None`` if it does not exist.
61
+
62
+ Unlike ``cs.tags["name"]`` this always reads the current server state and
63
+ does not raise :class:`~cloudsprite.NotFoundError` on a miss.
64
+ """
65
+ return self._find_by_name(name)
66
+
67
+ def create(self, name: str, color: str | None = None) -> Tag: # type: ignore[override]
68
+ """Create a tag, or return the existing one with this name (idempotent).
69
+
70
+ Names are unique per team, so a retry never mints a second tag. Newer
71
+ API versions answer a duplicate with ``200`` and the existing tag (``201``
72
+ for a new one); older servers fail a duplicate with an error instead, so
73
+ this checks for the name first and, if the POST is rejected, looks the
74
+ name up again and returns the existing tag. An error with no matching
75
+ tag is re-raised.
76
+
77
+ Args:
78
+ name: Tag name (exact, case-sensitive).
79
+ color: Optional display color (hex or name). Not applied to an
80
+ already-existing tag; use :meth:`Tag.update` for that.
81
+
82
+ Returns:
83
+ The new or existing :class:`Tag`.
84
+
85
+ Example:
86
+ >>> tag = cs.tags.create("base")
87
+ >>> ds.add_tag(tag.id)
88
+ """
89
+ if not name or not name.strip():
90
+ raise ValidationError("Tag name must not be empty")
91
+ existing = self._find_by_name(name)
92
+ if existing is not None:
93
+ return existing
94
+ body: dict[str, Any] = {"name": name}
95
+ if color is not None:
96
+ body["color"] = color
97
+ try:
98
+ data = self._client.post(self._path, json=body, headers=self._extra_headers)
99
+ except APIError as exc:
100
+ if exc.status_code not in self._DUPLICATE_STATUSES:
101
+ raise
102
+ raced = self._find_by_name(name)
103
+ if raced is None:
104
+ raise
105
+ return raced
106
+ self._items = None # invalidate cache
107
+ return Tag(self._client, data=data)
@@ -0,0 +1,86 @@
1
+ """Team resource."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Any, cast
6
+
7
+ from cloudsprite.resources._base import Resource, ResourceCollection
8
+
9
+ if TYPE_CHECKING:
10
+ from cloudsprite.resources.instruments import Instrument
11
+ from cloudsprite.resources.orbs import Orb
12
+ from cloudsprite.resources.projects import Project
13
+
14
+
15
+ class Team(Resource):
16
+ """A team that owns projects, instruments, and orbs."""
17
+
18
+ @property
19
+ def slug(self) -> str:
20
+ """URL-safe team identifier."""
21
+ return str(self._data.get("slug", ""))
22
+
23
+ @property
24
+ def projects(self) -> ResourceCollection[Project]:
25
+ """Projects belonging to this team."""
26
+ from cloudsprite.resources.projects import Project
27
+
28
+ return ResourceCollection(
29
+ self._client,
30
+ "/api/projects/",
31
+ Project,
32
+ name_field="title",
33
+ extra_headers={"X-Team-ID": self.id},
34
+ )
35
+
36
+ @property
37
+ def members(self) -> list[dict[str, Any]]:
38
+ """List team members."""
39
+ # No trailing slash — the server registers /memberships, and APPEND_SLASH
40
+ # only appends, so the slashed form 404s rather than redirecting.
41
+ result = self._client.get(f"/api/teams/{self.id}/memberships")
42
+ return cast(list[dict[str, Any]], result)
43
+
44
+ @property
45
+ def orbs(self) -> ResourceCollection[Orb]:
46
+ """List orbs associated with this team."""
47
+ from cloudsprite.resources.orbs import Orb
48
+
49
+ return ResourceCollection(
50
+ self._client,
51
+ "/api/orbs/",
52
+ Orb,
53
+ name_field="name",
54
+ extra_headers={"X-Team-ID": self.id},
55
+ )
56
+
57
+ @property
58
+ def instruments(self) -> ResourceCollection[Instrument]:
59
+ """List instruments associated with this team."""
60
+ from cloudsprite.resources.instruments import Instrument
61
+
62
+ return ResourceCollection(
63
+ self._client,
64
+ "/api/instruments/",
65
+ Instrument,
66
+ name_field="name",
67
+ extra_headers={"X-Team-ID": self.id},
68
+ )
69
+
70
+ def update(self, **kwargs: Any) -> None:
71
+ """Update team fields (name, etc.)."""
72
+ data = self._client.patch(f"/api/teams/{self.id}", json=kwargs)
73
+ if isinstance(data, dict):
74
+ self._data.update(data)
75
+
76
+ def invite(self, email: str, role: str = "member") -> dict[str, Any]:
77
+ """Invite a user to this team."""
78
+ return cast(
79
+ dict[str, Any],
80
+ self._client.post(
81
+ # No trailing slash — server route is /invitations. A POST to the
82
+ # slashed form 404s; APPEND_SLASH cannot strip a slash.
83
+ f"/api/teams/{self.id}/invitations",
84
+ json={"email": email, "role": role},
85
+ ),
86
+ )