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,992 @@
1
+ """Report resource — project-scoped markdown documents with citations and history.
2
+
3
+ Parity with ``/api/reports/*``: list/create/get/update, trash/restore/permanent
4
+ delete, team and trash lists, publish/unpublish, versions, references,
5
+ backlinks, and attachments.
6
+
7
+ Example::
8
+
9
+ report = cs.reports.create("Cable Qual Summary", project_id=project.id, body_md="See [[CQ-DS-1]]")
10
+ report.publish()
11
+ cited = cs.reports.backlinks_for_dataset(dataset.id)
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import hashlib
17
+ import os
18
+ import time
19
+ from pathlib import Path
20
+ from typing import Any
21
+ from urllib.parse import parse_qs, urlparse
22
+
23
+ from cloudsprite._exceptions import (
24
+ APIError,
25
+ AuthError,
26
+ ExportError,
27
+ ExportTimeoutError,
28
+ ValidationError,
29
+ export_error,
30
+ validate_id,
31
+ )
32
+ from cloudsprite.resources._base import Resource, ResourceCollection
33
+
34
+ _MAX_PAGE = 200
35
+
36
+ # Report export contract (API exports). ``md`` is a zip of markdown plus assets;
37
+ # ``pdf`` is accepted by the schema but the server answers FORMAT_UNAVAILABLE until its render worker ships.
38
+ EXPORT_FORMATS = ("md", "html", "pdf")
39
+ _EXPORT_TERMINAL = frozenset({"succeeded", "failed", "expired"})
40
+ # Failure codes the create call can answer with a structured ``{"detail", "code"}`` body.
41
+ _EXPORT_CREATE_CODES = frozenset({"inputs_changed", "permission_denied", "source_unavailable", "too_large"})
42
+ _sleep = time.sleep # indirection so tests can run ``wait`` without real delays
43
+
44
+
45
+ def _resource_id(value: Any, name: str) -> str:
46
+ raw = getattr(value, "id", None)
47
+ if raw is None:
48
+ raw = value
49
+ return validate_id(str(raw), name)
50
+
51
+
52
+ def _as_list(payload: Any) -> list[dict[str, Any]]:
53
+ if isinstance(payload, list):
54
+ return [item for item in payload if isinstance(item, dict)]
55
+ if isinstance(payload, dict):
56
+ raw = payload.get("results") or payload.get("items") or []
57
+ if isinstance(raw, list):
58
+ return [item for item in raw if isinstance(item, dict)]
59
+ return []
60
+
61
+
62
+ def _require_dict(payload: Any, what: str) -> dict[str, Any]:
63
+ if not isinstance(payload, dict):
64
+ raise ValidationError(f"Unexpected {what} response")
65
+ return payload
66
+
67
+
68
+ def _project_id_from_collection_path(path: str) -> str | None:
69
+ query = urlparse(path).query or (path.split("?", 1)[1] if "?" in path else "")
70
+ values = parse_qs(query).get("project_id") or []
71
+ if not values or not values[0]:
72
+ return None
73
+ return values[0]
74
+
75
+
76
+ def _confirm_identity(resource: Resource, confirm_name: str, action: str) -> None:
77
+ typed = confirm_name.strip()
78
+ names = {n for n in (resource.name, str(resource._data.get("slug") or "")) if n}
79
+ if typed not in names:
80
+ raise ValidationError(f"{action} requires confirm_name to match the report title or slug exactly")
81
+
82
+
83
+ class ReportBacklink(Resource):
84
+ """A report that cites a dataset or notebook (backlink list row)."""
85
+
86
+ @property
87
+ def slug(self) -> str:
88
+ """Report slug when assigned, else empty."""
89
+ return str(self._data.get("slug") or "")
90
+
91
+ @property
92
+ def project_id(self) -> str:
93
+ """Owning project UUID."""
94
+ return str(self._data.get("project_id", ""))
95
+
96
+ @property
97
+ def project_title(self) -> str:
98
+ """Owning project title."""
99
+ return str(self._data.get("project_title") or "")
100
+
101
+ @property
102
+ def status(self) -> str:
103
+ """Report status (``draft`` or ``published``)."""
104
+ return str(self._data.get("status", ""))
105
+
106
+ @property
107
+ def updated_at(self) -> str:
108
+ """Last-updated timestamp from the API."""
109
+ return str(self._data.get("updated_at") or "")
110
+
111
+
112
+ class ReportReference(Resource):
113
+ """A citation from a report to a dataset, notebook, script, or workflow."""
114
+
115
+ @property
116
+ def type(self) -> str:
117
+ """Referenced resource kind (``dataset``, ``notebook``, ``script``, ``workflow``)."""
118
+ return str(self._data.get("type", ""))
119
+
120
+ @property
121
+ def target_id(self) -> str:
122
+ """UUID of the cited resource."""
123
+ return str(self._data.get("target_id", ""))
124
+
125
+ @property
126
+ def slug(self) -> str:
127
+ """Cited resource slug when present."""
128
+ return str(self._data.get("slug") or "")
129
+
130
+ @property
131
+ def label(self) -> str:
132
+ """Display label for the citation."""
133
+ return str(self._data.get("label") or "")
134
+
135
+ @property
136
+ def source(self) -> str:
137
+ """How the reference was created (``extracted`` or ``manual``)."""
138
+ return str(self._data.get("source", ""))
139
+
140
+ @property
141
+ def order(self) -> int:
142
+ """Display order within the report."""
143
+ raw = self._data.get("order", 0)
144
+ return int(raw) if raw is not None else 0
145
+
146
+
147
+ class ReportAttachment(Resource):
148
+ """A file attached to a report."""
149
+
150
+ @property
151
+ def report_id(self) -> str:
152
+ """Owning report UUID."""
153
+ return str(self._data.get("report_id", ""))
154
+
155
+ @property
156
+ def content_type(self) -> str:
157
+ """Stored MIME type."""
158
+ return str(self._data.get("content_type", ""))
159
+
160
+ @property
161
+ def size(self) -> int:
162
+ """File size in bytes."""
163
+ raw = self._data.get("size", 0)
164
+ return int(raw) if raw is not None else 0
165
+
166
+ @property
167
+ def file_url(self) -> str | None:
168
+ """Presigned download URL when the API provides one."""
169
+ raw = self._data.get("file_url")
170
+ return str(raw) if raw else None
171
+
172
+
173
+ class ReportVersion(Resource):
174
+ """An immutable snapshot of a report (append-only history)."""
175
+
176
+ @property
177
+ def report_id(self) -> str:
178
+ """Owning report UUID."""
179
+ return str(self._data.get("report_id", ""))
180
+
181
+ @property
182
+ def version(self) -> int:
183
+ """Monotonic version number (1-based)."""
184
+ raw = self._data.get("version", 0)
185
+ return int(raw) if raw is not None else 0
186
+
187
+ @property
188
+ def content_hash(self) -> str:
189
+ """Content hash of the snapshot payload."""
190
+ return str(self._data.get("content_hash", ""))
191
+
192
+ @property
193
+ def message(self) -> str:
194
+ """Optional snapshot message."""
195
+ return str(self._data.get("message") or "")
196
+
197
+ @property
198
+ def payload(self) -> dict[str, Any] | None:
199
+ """Full snapshot body when fetched via :meth:`ReportVersionCollection.get`."""
200
+ raw = self._data.get("payload")
201
+ return raw if isinstance(raw, dict) else None
202
+
203
+
204
+ class TrashedReport(Resource):
205
+ """A soft-deleted report awaiting restore or permanent delete."""
206
+
207
+ @property
208
+ def project_id(self) -> str:
209
+ """Owning project UUID."""
210
+ return str(self._data.get("project_id", ""))
211
+
212
+ @property
213
+ def trashed_at(self) -> str:
214
+ """When the report was moved to trash."""
215
+ return str(self._data.get("trashed_at") or "")
216
+
217
+ @property
218
+ def days_remaining(self) -> int | None:
219
+ """Days until purge, when the API reports it."""
220
+ raw = self._data.get("days_remaining")
221
+ return int(raw) if raw is not None else None
222
+
223
+ def restore(self) -> Report:
224
+ """Restore this report from trash.
225
+
226
+ Server: ``POST /api/reports/{id}/restore``.
227
+ """
228
+ data = _require_dict(self._client.post(f"/api/reports/{self.id}/restore"), "report restore")
229
+ return Report(self._client, data)
230
+
231
+ def permanent_delete(self, *, confirm_name: str) -> None:
232
+ """Permanently delete this trashed report.
233
+
234
+ Requires ``confirm_name`` matching the report title or slug.
235
+ Server: ``DELETE /api/reports/{id}/permanent-delete``.
236
+ """
237
+ _confirm_identity(self, confirm_name, "permanent_delete")
238
+ self._client.delete(f"/api/reports/{self.id}/permanent-delete")
239
+
240
+
241
+ class ReportVersionCollection:
242
+ """Version snapshots for one report (list/get/create/restore)."""
243
+
244
+ def __init__(self, client: Any, report_id: str) -> None:
245
+ self._client = client
246
+ self._report_id = report_id
247
+
248
+ def list(self) -> list[ReportVersion]:
249
+ """List snapshots of this report.
250
+
251
+ Server: ``GET /api/reports/{id}/versions``.
252
+ """
253
+ items: list[ReportVersion] = []
254
+ offset = 0
255
+ while True:
256
+ page = _as_list(
257
+ self._client.get(
258
+ f"/api/reports/{self._report_id}/versions",
259
+ params={"offset": offset, "limit": _MAX_PAGE},
260
+ )
261
+ )
262
+ items.extend(ReportVersion(self._client, item) for item in page)
263
+ if len(page) < _MAX_PAGE:
264
+ return items
265
+ offset += len(page)
266
+
267
+ def get(self, version_id: str) -> ReportVersion:
268
+ """Fetch one snapshot, including payload.
269
+
270
+ Server: ``GET /api/reports/{id}/versions/{version_id}``.
271
+ """
272
+ version_id = validate_id(version_id, "version_id")
273
+ data = _require_dict(
274
+ self._client.get(f"/api/reports/{self._report_id}/versions/{version_id}"),
275
+ "report version",
276
+ )
277
+ return ReportVersion(self._client, data)
278
+
279
+ def create(self, *, message: str = "") -> ReportVersion:
280
+ """Commit a new snapshot of the current report body.
281
+
282
+ Server: ``POST /api/reports/{id}/versions``.
283
+ """
284
+ data = _require_dict(
285
+ self._client.post(f"/api/reports/{self._report_id}/versions", json={"message": message}),
286
+ "report version",
287
+ )
288
+ return ReportVersion(self._client, data)
289
+
290
+ def restore(self, version_id: str, *, expected_updated_at: str) -> Report:
291
+ """Restore a snapshot (append-only; does not rewrite history).
292
+
293
+ Server: ``POST /api/reports/{id}/versions/{version_id}/restore``.
294
+ """
295
+ version_id = validate_id(version_id, "version_id")
296
+ data = _require_dict(
297
+ self._client.post(
298
+ f"/api/reports/{self._report_id}/versions/{version_id}/restore",
299
+ json={"expected_updated_at": expected_updated_at},
300
+ ),
301
+ "report",
302
+ )
303
+ return Report(self._client, data)
304
+
305
+
306
+ class ReportReferenceCollection:
307
+ """Citations on one report."""
308
+
309
+ def __init__(self, client: Any, report_id: str) -> None:
310
+ self._client = client
311
+ self._report_id = report_id
312
+
313
+ def list(self) -> list[ReportReference]:
314
+ """List references on this report.
315
+
316
+ Server: ``GET /api/reports/{id}/references``.
317
+ """
318
+ items: list[ReportReference] = []
319
+ offset = 0
320
+ while True:
321
+ page = _as_list(
322
+ self._client.get(
323
+ f"/api/reports/{self._report_id}/references",
324
+ params={"offset": offset, "limit": _MAX_PAGE},
325
+ )
326
+ )
327
+ items.extend(ReportReference(self._client, item) for item in page)
328
+ if len(page) < _MAX_PAGE:
329
+ return items
330
+ offset += len(page)
331
+
332
+ def add(self, *, type: str, target_id: str, label: str = "") -> ReportReference:
333
+ """Add a manual reference.
334
+
335
+ Server: ``POST /api/reports/{id}/references``.
336
+ """
337
+ target_id = validate_id(str(target_id), "target_id")
338
+ data = _require_dict(
339
+ self._client.post(
340
+ f"/api/reports/{self._report_id}/references",
341
+ json={"type": type, "target_id": target_id, "label": label},
342
+ ),
343
+ "report reference",
344
+ )
345
+ return ReportReference(self._client, data)
346
+
347
+ def delete(self, reference_id: str) -> None:
348
+ """Remove a manual reference.
349
+
350
+ Server: ``DELETE /api/reports/{id}/references/{reference_id}``.
351
+ """
352
+ reference_id = validate_id(reference_id, "reference_id")
353
+ self._client.delete(f"/api/reports/{self._report_id}/references/{reference_id}")
354
+
355
+
356
+ class ReportAttachmentCollection:
357
+ """Files attached to one report."""
358
+
359
+ def __init__(self, client: Any, report_id: str) -> None:
360
+ self._client = client
361
+ self._report_id = report_id
362
+
363
+ def list(self) -> list[ReportAttachment]:
364
+ """List attachments on this report.
365
+
366
+ Server: ``GET /api/reports/{id}/attachments/``.
367
+ """
368
+ raw = _as_list(self._client.get(f"/api/reports/{self._report_id}/attachments/"))
369
+ return [ReportAttachment(self._client, item) for item in raw]
370
+
371
+ def upload(self, file_path: str) -> ReportAttachment:
372
+ """Upload an attachment (multipart/form-data).
373
+
374
+ JSON-only ``use_sdk`` dispatch cannot execute this method — the same
375
+ limitation as :meth:`~cloudsprite.resources.cloudscripts.CloudScript.upload_version`.
376
+
377
+ Server: ``POST /api/reports/{id}/attachments/``.
378
+ """
379
+ path = Path(file_path)
380
+ if not path.exists():
381
+ raise FileNotFoundError(f"File not found: {file_path}")
382
+ data = _require_dict(
383
+ self._client.post_file(
384
+ f"/api/reports/{self._report_id}/attachments/",
385
+ path.name,
386
+ path.read_bytes(),
387
+ ),
388
+ "report attachment",
389
+ )
390
+ return ReportAttachment(self._client, data)
391
+
392
+ def delete(self, attachment_id: str) -> None:
393
+ """Delete an attachment.
394
+
395
+ Server: ``DELETE /api/reports/{id}/attachments/{attachment_id}``.
396
+ """
397
+ attachment_id = validate_id(attachment_id, "attachment_id")
398
+ self._client.delete(f"/api/reports/{self._report_id}/attachments/{attachment_id}")
399
+
400
+
401
+ class ReportExport(Resource):
402
+ """An export job for one report (``md`` zip or standalone ``html``).
403
+
404
+ Create with :meth:`Report.export`, then ``wait()`` and ``download(path)``::
405
+
406
+ job = report.export("html")
407
+ path = job.wait(timeout=300).download("./reports/")
408
+
409
+ The presigned download URL is short-lived and grants access to the artifact,
410
+ so it is never exposed as an attribute, ``repr`` or log line.
411
+ """
412
+
413
+ def __init__(self, client: Any, data: dict[str, Any], *, report_id: str | None = None) -> None:
414
+ data = dict(data)
415
+ self._download_url: str | None = data.pop("download_url", None) or None
416
+ super().__init__(client, data)
417
+ self._report_id = str(data.get("report_id") or report_id or "") # the API echoes the UUID even for a slug
418
+
419
+ def __repr__(self) -> str:
420
+ return f"ReportExport('{self.id}', format='{self.format}', status='{self.status}')"
421
+
422
+ @property
423
+ def name(self) -> str:
424
+ """Artifact filename once built, else the job id."""
425
+ return self.filename or self.id
426
+
427
+ @property
428
+ def report_id(self) -> str:
429
+ """Owning report UUID."""
430
+ return self._report_id
431
+
432
+ @property
433
+ def format(self) -> str:
434
+ """Requested format (``md``, ``html`` or ``pdf``)."""
435
+ return str(self._data.get("format", ""))
436
+
437
+ @property
438
+ def status(self) -> str:
439
+ """``queued``, ``running``, ``succeeded``, ``failed`` or ``expired``."""
440
+ return str(self._data.get("status", ""))
441
+
442
+ @property
443
+ def cached(self) -> bool:
444
+ """True on create when a finished identical artifact was reused."""
445
+ return bool(self._data.get("cached", False))
446
+
447
+ @property
448
+ def filename(self) -> str | None:
449
+ """Artifact filename once the build has finished."""
450
+ raw = self._data.get("filename")
451
+ return str(raw) if raw else None
452
+
453
+ @property
454
+ def size_bytes(self) -> int | None:
455
+ """Artifact size in bytes once built."""
456
+ raw = self._data.get("size_bytes")
457
+ return int(raw) if raw is not None else None
458
+
459
+ @property
460
+ def sha256(self) -> str | None:
461
+ """Hex SHA-256 of the artifact once built."""
462
+ raw = self._data.get("sha256")
463
+ return str(raw) if raw else None
464
+
465
+ @property
466
+ def expires_at(self) -> str | None:
467
+ """When the stored artifact expires."""
468
+ raw = self._data.get("expires_at")
469
+ return str(raw) if raw else None
470
+
471
+ @property
472
+ def degraded(self) -> list[dict[str, Any]]:
473
+ """Parts of the report the export had to approximate (for example a figure rendered as a placeholder)."""
474
+ raw = self._data.get("degraded")
475
+ return [item for item in raw if isinstance(item, dict)] if isinstance(raw, list) else []
476
+
477
+ @property
478
+ def error_code(self) -> str | None:
479
+ """Failure code (for example ``inputs_changed``) when ``status`` is ``failed``."""
480
+ error = self._data.get("error")
481
+ return str(error["code"]) if isinstance(error, dict) and error.get("code") else None
482
+
483
+ @property
484
+ def error_message(self) -> str | None:
485
+ """User-safe failure message when ``status`` is ``failed``."""
486
+ error = self._data.get("error")
487
+ return str(error.get("message") or "") if isinstance(error, dict) else None
488
+
489
+ @property
490
+ def done(self) -> bool:
491
+ """True once the job is ``succeeded``, ``failed`` or ``expired``."""
492
+ return self.status in _EXPORT_TERMINAL
493
+
494
+ def _path(self) -> str:
495
+ return f"/api/reports/{self._report_id}/exports/{self.id}/"
496
+
497
+ def refresh(self) -> ReportExport:
498
+ """Re-read the job. A succeeded job also yields a fresh five-minute download URL.
499
+
500
+ Server: ``GET /api/reports/{id}/exports/{job_id}/``. Issuing the URL is the audited download event.
501
+ """
502
+ data = dict(_require_dict(self._client.get(self._path()), "report export"))
503
+ self._download_url = data.pop("download_url", None) or None
504
+ self._data.update(data)
505
+ return self
506
+
507
+ def raise_for_failure(self) -> None:
508
+ """Raise the typed :class:`~cloudsprite.ExportError` when the job failed or expired."""
509
+ if self.status == "failed":
510
+ raise export_error(
511
+ self.error_code or "renderer_error", self.error_message or "Export failed.", job_id=self.id
512
+ )
513
+ if self.status == "expired":
514
+ raise ExportError("expired", "The export expired. Request it again.", job_id=self.id)
515
+
516
+ def wait(
517
+ self,
518
+ timeout: float = 300.0,
519
+ *,
520
+ poll_interval: float = 1.0,
521
+ max_interval: float = 10.0,
522
+ backoff: float = 1.5,
523
+ ) -> ReportExport:
524
+ """Poll until the export finishes, backing off between polls.
525
+
526
+ Returns ``self`` once ``succeeded``. Raises
527
+ :class:`~cloudsprite.ExportInputsChangedError` or
528
+ :class:`~cloudsprite.ExportPermissionDeniedError` for those failure codes,
529
+ :class:`~cloudsprite.ExportError` for any other failure or expiry, and
530
+ :class:`~cloudsprite.ExportTimeoutError` when ``timeout`` seconds pass first
531
+ (the job keeps running; call ``wait`` again).
532
+ """
533
+ if timeout <= 0 or poll_interval <= 0 or max_interval < poll_interval or backoff < 1:
534
+ raise ValidationError(
535
+ "wait needs timeout > 0, poll_interval > 0, max_interval >= poll_interval, backoff >= 1"
536
+ )
537
+ deadline = time.monotonic() + timeout
538
+ interval = poll_interval
539
+ while not self.done:
540
+ remaining = deadline - time.monotonic()
541
+ if remaining <= 0:
542
+ raise ExportTimeoutError("timeout", f"Export still {self.status} after {timeout:g}s.", job_id=self.id)
543
+ _sleep(min(interval, remaining))
544
+ interval = min(interval * backoff, max_interval)
545
+ self.refresh()
546
+ self.raise_for_failure()
547
+ return self
548
+
549
+ def download(self, path: str | os.PathLike[str]) -> Path:
550
+ """Download the finished artifact and return its path.
551
+
552
+ ``path`` is a file path, or a directory (an existing one, or a path ending in ``/``, which is created); the
553
+ artifact filename is used inside it. The bytes are
554
+ verified against the API's size and SHA-256; a mismatch deletes the file and raises
555
+ :class:`~cloudsprite.ExportError` (``checksum_mismatch``).
556
+ """
557
+ if not self.done:
558
+ raise ValidationError("Export has not finished; call wait() first")
559
+ self.raise_for_failure()
560
+ if not self._download_url:
561
+ self.refresh()
562
+ self.raise_for_failure()
563
+ if not self._download_url:
564
+ raise ExportError(
565
+ "expired", "No download link is available for this export. Request it again.", job_id=self.id
566
+ )
567
+ raw_path = os.fspath(path)
568
+ dest = Path(raw_path)
569
+ if dest.is_dir() or raw_path.endswith(("/", os.sep)) or (os.altsep and raw_path.endswith(os.altsep)):
570
+ name = Path(self.filename or f"report-export-{self.id}").name
571
+ if name in ("", ".", ".."):
572
+ raise ExportError(
573
+ "invalid_filename", "The export has an unusable filename; pass a file path.", job_id=self.id
574
+ )
575
+ dest = dest / name
576
+ dest.parent.mkdir(parents=True, exist_ok=True)
577
+ url, self._download_url = self._download_url, None # single use: do not keep the credential around
578
+ self._client.download_presigned(url, dest)
579
+ self._verify(dest)
580
+ return dest
581
+
582
+ def _verify(self, dest: Path) -> None:
583
+ expected_size, expected_hash = self.size_bytes, self.sha256
584
+ digest = hashlib.sha256()
585
+ with open(dest, "rb") as fh:
586
+ for block in iter(lambda: fh.read(1024 * 1024), b""):
587
+ digest.update(block)
588
+ size_ok = expected_size is None or dest.stat().st_size == expected_size
589
+ hash_ok = expected_hash is None or digest.hexdigest() == expected_hash.lower()
590
+ if not (size_ok and hash_ok):
591
+ dest.unlink(missing_ok=True)
592
+ raise export_error(
593
+ "checksum_mismatch", "Downloaded file does not match the export checksum.", job_id=self.id
594
+ )
595
+
596
+ def delete(self) -> None:
597
+ """Remove this export from your list. Fails (409) while it is still running.
598
+
599
+ Server: ``DELETE /api/reports/{id}/exports/{job_id}/``.
600
+ """
601
+ self._client.delete(self._path())
602
+
603
+
604
+ class ReportExportCollection:
605
+ """Export jobs you requested for one report."""
606
+
607
+ def __init__(self, client: Any, report_id: str) -> None:
608
+ self._client = client
609
+ self._report_id = report_id
610
+
611
+ def list(self, *, limit: int = 50, offset: int = 0) -> list[ReportExport]:
612
+ """List your exports for this report, newest first (server caps ``limit`` at 100; page with ``offset``).
613
+
614
+ Server: ``GET /api/reports/{id}/exports/``.
615
+ """
616
+ raw = _as_list(
617
+ self._client.get(f"/api/reports/{self._report_id}/exports/", params={"limit": limit, "offset": offset})
618
+ )
619
+ return [ReportExport(self._client, item, report_id=self._report_id) for item in raw]
620
+
621
+ def get(self, job_id: str) -> ReportExport:
622
+ """Fetch one export by id.
623
+
624
+ Server: ``GET /api/reports/{id}/exports/{job_id}/``.
625
+ """
626
+ job_id = validate_id(str(job_id), "job_id")
627
+ data = _require_dict(self._client.get(f"/api/reports/{self._report_id}/exports/{job_id}/"), "report export")
628
+ return ReportExport(self._client, data, report_id=self._report_id)
629
+
630
+ def create(
631
+ self,
632
+ format: str = "html",
633
+ *,
634
+ source: str | int = "current",
635
+ options: dict[str, Any] | None = None,
636
+ force: bool = False,
637
+ ) -> ReportExport:
638
+ """Queue an export and return the job without waiting.
639
+
640
+ ``format`` is ``"html"`` (standalone page) or ``"md"`` (zip of markdown and assets); ``"pdf"`` is
641
+ reserved and currently refused by the server. ``source`` is ``"current"``, ``"published"`` or a
642
+ version number. ``force`` rebuilds even when a fresh identical artifact exists.
643
+
644
+ Raises :class:`~cloudsprite.ExportPermissionDeniedError`,
645
+ :class:`~cloudsprite.ExportInputsChangedError` or :class:`~cloudsprite.ExportError` when the API
646
+ answers with a structured export error.
647
+
648
+ Server: ``POST /api/reports/{id}/exports/`` (202).
649
+ """
650
+ if format not in EXPORT_FORMATS:
651
+ raise ValidationError(f"format must be one of {', '.join(EXPORT_FORMATS)} (got {format!r}); 'md' is a zip")
652
+ if isinstance(source, bool) or not (
653
+ source in ("current", "published") or (isinstance(source, int) and source >= 1)
654
+ ):
655
+ raise ValidationError("source must be 'current', 'published' or a version number of 1 or more")
656
+ body: dict[str, Any] = {"format": format, "source": source, "options": dict(options or {}), "force": force}
657
+ try:
658
+ data = self._client.post(f"/api/reports/{self._report_id}/exports/", json=body)
659
+ except (APIError, AuthError) as exc:
660
+ code = str((exc.response_body or {}).get("code") or "").lower()
661
+ if code in _EXPORT_CREATE_CODES:
662
+ raise export_error(code, str((exc.response_body or {}).get("detail") or code)) from exc
663
+ raise
664
+ return ReportExport(self._client, _require_dict(data, "report export"), report_id=self._report_id)
665
+
666
+
667
+ class Report(Resource):
668
+ """A markdown report in a project.
669
+
670
+ Attributes:
671
+ id: Unique identifier (UUID).
672
+ name: Display title.
673
+ slug: URL-safe identifier when assigned.
674
+ """
675
+
676
+ @property
677
+ def slug(self) -> str:
678
+ """URL-safe identifier (``{prefix}-RPT-{n}``) when assigned."""
679
+ return str(self._data.get("slug") or "")
680
+
681
+ @property
682
+ def status(self) -> str:
683
+ """``draft`` or ``published``."""
684
+ return str(self._data.get("status", ""))
685
+
686
+ @property
687
+ def body_md(self) -> str:
688
+ """Markdown body. Empty on list rows that omit it."""
689
+ return str(self._data.get("body_md") or "")
690
+
691
+ @property
692
+ def project_id(self) -> str:
693
+ """Owning project UUID."""
694
+ return str(self._data.get("project_id", ""))
695
+
696
+ @property
697
+ def updated_at(self) -> str:
698
+ """Last-updated timestamp; pass to :meth:`update` as ``expected_updated_at``."""
699
+ return str(self._data.get("updated_at") or "")
700
+
701
+ @property
702
+ def published_at(self) -> str | None:
703
+ """When the report was published, or None."""
704
+ raw = self._data.get("published_at")
705
+ return str(raw) if raw else None
706
+
707
+ @property
708
+ def latest_version(self) -> int | None:
709
+ """Latest snapshot number when the API provides one."""
710
+ raw = self._data.get("latest_version")
711
+ return int(raw) if raw is not None else None
712
+
713
+ @property
714
+ def versions(self) -> ReportVersionCollection:
715
+ """Version snapshots for this report."""
716
+ return ReportVersionCollection(self._client, self.id)
717
+
718
+ @property
719
+ def references(self) -> ReportReferenceCollection:
720
+ """Citations on this report."""
721
+ return ReportReferenceCollection(self._client, self.id)
722
+
723
+ @property
724
+ def attachments(self) -> ReportAttachmentCollection:
725
+ """Files attached to this report."""
726
+ return ReportAttachmentCollection(self._client, self.id)
727
+
728
+ @property
729
+ def exports(self) -> ReportExportCollection:
730
+ """Export jobs you requested for this report."""
731
+ return ReportExportCollection(self._client, self.id)
732
+
733
+ def export(
734
+ self,
735
+ format: str = "html",
736
+ *,
737
+ source: str | int = "current",
738
+ options: dict[str, Any] | None = None,
739
+ force: bool = False,
740
+ ) -> ReportExport:
741
+ """Queue an export of this report. See :meth:`ReportExportCollection.create`.
742
+
743
+ Example::
744
+
745
+ path = report.export("md").wait().download("./out/")
746
+ """
747
+ return self.exports.create(format, source=source, options=options, force=force)
748
+
749
+ def update(
750
+ self,
751
+ *,
752
+ expected_updated_at: str | None = None,
753
+ title: str | None = None,
754
+ body_md: str | None = None,
755
+ tag_ids: list[str] | None = None,
756
+ ) -> Report:
757
+ """Patch this report. Stale ``expected_updated_at`` yields HTTP 409.
758
+
759
+ Server: ``PATCH /api/reports/{id}``.
760
+ """
761
+ ts = expected_updated_at or self.updated_at
762
+ if not ts:
763
+ raise ValidationError("update() requires expected_updated_at")
764
+ payload: dict[str, Any] = {"expected_updated_at": ts}
765
+ if title is not None:
766
+ payload["title"] = title
767
+ if body_md is not None:
768
+ payload["body_md"] = body_md
769
+ if tag_ids is not None:
770
+ payload["tag_ids"] = tag_ids
771
+ data = _require_dict(self._client.patch(f"/api/reports/{self.id}", json=payload), "report")
772
+ self._data.update(data)
773
+ return self
774
+
775
+ def trash(self) -> None:
776
+ """Move this report to trash (soft delete).
777
+
778
+ Server: ``DELETE /api/reports/{id}``.
779
+ """
780
+ self._client.delete(f"/api/reports/{self.id}")
781
+
782
+ def restore(self) -> Report:
783
+ """Restore this report from trash.
784
+
785
+ Server: ``POST /api/reports/{id}/restore``. Restore is append-only at
786
+ the assistant boundary and does not require ``confirm_name``.
787
+ """
788
+ data = _require_dict(self._client.post(f"/api/reports/{self.id}/restore"), "report restore")
789
+ self._data.update(data)
790
+ return self
791
+
792
+ def permanent_delete(self, *, confirm_name: str) -> None:
793
+ """Permanently delete a trashed report.
794
+
795
+ Requires ``confirm_name`` matching this report's title or slug.
796
+ Server: ``DELETE /api/reports/{id}/permanent-delete``.
797
+ """
798
+ _confirm_identity(self, confirm_name, "permanent_delete")
799
+ self._client.delete(f"/api/reports/{self.id}/permanent-delete")
800
+
801
+ def publish(self) -> Report:
802
+ """Publish this report. Requires ``report:publish``.
803
+
804
+ Server: ``POST /api/reports/{id}/publish``.
805
+ """
806
+ data = _require_dict(self._client.post(f"/api/reports/{self.id}/publish"), "report")
807
+ self._data.update(data)
808
+ return self
809
+
810
+ def unpublish(self) -> Report:
811
+ """Revert this report to draft.
812
+
813
+ Server: ``POST /api/reports/{id}/unpublish``.
814
+ """
815
+ data = _require_dict(self._client.post(f"/api/reports/{self.id}/unpublish"), "report")
816
+ self._data.update(data)
817
+ return self
818
+
819
+
820
+ class ReportCollection(ResourceCollection[Report]):
821
+ """Reports in a project, plus team/trash/backlink helpers."""
822
+
823
+ def list_team(self, team: str | None = None) -> list[Report]:
824
+ """List published reports the caller can read in a team.
825
+
826
+ Server: ``GET /api/reports/team``. Team-scoped via ``X-Team-ID``.
827
+ """
828
+ headers = {"X-Team-ID": _resource_id(team, "team_id")} if team is not None else None
829
+ items: list[Report] = []
830
+ offset = 0
831
+ while True:
832
+ page = _as_list(
833
+ self._client.get("/api/reports/team", params={"offset": offset, "limit": _MAX_PAGE}, headers=headers)
834
+ )
835
+ items.extend(Report(self._client, item) for item in page)
836
+ if len(page) < _MAX_PAGE:
837
+ return items
838
+ offset += len(page)
839
+
840
+ def list_trashed(self, project: str | None = None) -> list[TrashedReport]:
841
+ """List trashed reports for the current team.
842
+
843
+ Server: ``GET /api/reports/trash``. Team-scoped via ``X-Team-ID``.
844
+ When ``project`` is given, results are filtered to that project.
845
+ """
846
+ items: list[TrashedReport] = []
847
+ offset = 0
848
+ while True:
849
+ page = _as_list(self._client.get("/api/reports/trash", params={"offset": offset, "limit": _MAX_PAGE}))
850
+ items.extend(TrashedReport(self._client, item) for item in page)
851
+ if len(page) < _MAX_PAGE:
852
+ break
853
+ offset += len(page)
854
+ if project is None:
855
+ return items
856
+ pid = _resource_id(project, "project_id")
857
+ return [item for item in items if item.project_id == pid]
858
+
859
+ def export(
860
+ self,
861
+ report: Any,
862
+ format: str = "html",
863
+ *,
864
+ source: str | int = "current",
865
+ options: dict[str, Any] | None = None,
866
+ force: bool = False,
867
+ ) -> ReportExport:
868
+ """Queue an export of ``report`` (a :class:`Report` or its id) and return the job.
869
+
870
+ Chain ``.wait()`` and ``.download(path)`` to fetch the artifact.
871
+ See :meth:`ReportExportCollection.create` for arguments and errors.
872
+ """
873
+ return ReportExportCollection(self._client, _resource_id(report, "report_id")).create(
874
+ format, source=source, options=options, force=force
875
+ )
876
+
877
+ def get(self, report_id: str) -> Report:
878
+ """Fetch a report by id or slug.
879
+
880
+ Server: ``GET /api/reports/{report_id}``.
881
+ """
882
+ report_id = validate_id(str(report_id), "report_id")
883
+ data = _require_dict(self._client.get(f"/api/reports/{report_id}"), "report")
884
+ return Report(self._client, data)
885
+
886
+ def create(self, *args: Any, **kwargs: Any) -> Report:
887
+ """Create a report.
888
+
889
+ Server: ``POST /api/reports/``. ``project_id`` is taken from the
890
+ collection URL when omitted.
891
+
892
+ Title may be passed positionally (``create("Title", ...)``) or as
893
+ ``title=``.
894
+ """
895
+ if args:
896
+ if len(args) != 1:
897
+ raise ValidationError("reports.create() takes at most one positional argument (title)")
898
+ if "title" in kwargs:
899
+ raise ValidationError("reports.create() got multiple values for title")
900
+ title = args[0]
901
+ else:
902
+ title = kwargs.pop("title", None)
903
+ if title is None:
904
+ raise ValidationError("reports.create() requires title")
905
+ project_id = kwargs.pop("project_id", None) or _project_id_from_collection_path(self._path)
906
+ if not project_id:
907
+ raise ValidationError("reports.create() requires project_id")
908
+ payload: dict[str, Any] = {
909
+ "title": title,
910
+ "project_id": _resource_id(project_id, "project_id"),
911
+ "body_md": kwargs.pop("body_md", ""),
912
+ }
913
+ if "tag_ids" in kwargs:
914
+ payload["tag_ids"] = kwargs.pop("tag_ids")
915
+ payload.update(kwargs)
916
+ data = _require_dict(self._client.post("/api/reports/", json=payload), "report")
917
+ self._items = None
918
+ return Report(self._client, data)
919
+
920
+ def backlinks_for_dataset(self, dataset: str) -> list[ReportBacklink]:
921
+ """List reports that cite a dataset.
922
+
923
+ Server: ``GET /api/reports/backlinks/datasets/{dataset_id}``.
924
+ """
925
+ dataset_id = _resource_id(dataset, "dataset_id")
926
+ items: list[ReportBacklink] = []
927
+ offset = 0
928
+ while True:
929
+ page = _as_list(
930
+ self._client.get(
931
+ f"/api/reports/backlinks/datasets/{dataset_id}",
932
+ params={"offset": offset, "limit": _MAX_PAGE},
933
+ )
934
+ )
935
+ items.extend(ReportBacklink(self._client, item) for item in page)
936
+ if len(page) < _MAX_PAGE:
937
+ return items
938
+ offset += len(page)
939
+
940
+ def backlinks_for_notebook(self, notebook: str) -> list[ReportBacklink]:
941
+ """List reports that cite a notebook.
942
+
943
+ Server: ``GET /api/reports/backlinks/notebooks/{notebook_id}``.
944
+ """
945
+ notebook_id = _resource_id(notebook, "notebook_id")
946
+ items: list[ReportBacklink] = []
947
+ offset = 0
948
+ while True:
949
+ page = _as_list(
950
+ self._client.get(
951
+ f"/api/reports/backlinks/notebooks/{notebook_id}",
952
+ params={"offset": offset, "limit": _MAX_PAGE},
953
+ )
954
+ )
955
+ items.extend(ReportBacklink(self._client, item) for item in page)
956
+ if len(page) < _MAX_PAGE:
957
+ return items
958
+ offset += len(page)
959
+
960
+ def backlinks(self, *, dataset: str | None = None, notebook: str | None = None) -> list[ReportBacklink]:
961
+ """List reports that cite a dataset or a notebook. Pass exactly one.
962
+
963
+ Server: ``GET /api/reports/backlinks/datasets/{dataset_id}`` or
964
+ ``GET /api/reports/backlinks/notebooks/{notebook_id}``.
965
+ """
966
+ if dataset is not None and notebook is None:
967
+ return self.backlinks_for_dataset(dataset)
968
+ if notebook is not None and dataset is None:
969
+ return self.backlinks_for_notebook(notebook)
970
+ raise ValidationError("backlinks() requires exactly one of dataset= or notebook=")
971
+
972
+ def list(self, project: str, *, q: str | None = None, ordering: str | None = None) -> list[Report]:
973
+ """List reports in a project.
974
+
975
+ Server: ``GET /api/reports/``.
976
+ """
977
+ params: dict[str, Any] = {"project_id": _resource_id(project, "project_id")}
978
+ if q:
979
+ params["q"] = q
980
+ if ordering:
981
+ params["ordering"] = ordering
982
+ items: list[Report] = []
983
+ offset = 0
984
+ while True:
985
+ query = dict(params)
986
+ query["offset"] = offset
987
+ query["limit"] = _MAX_PAGE
988
+ page = _as_list(self._client.get("/api/reports/", params=query))
989
+ items.extend(Report(self._client, item) for item in page)
990
+ if len(page) < _MAX_PAGE:
991
+ return items
992
+ offset += len(page)