bladekit 4.41.0__tar.gz → 4.43.0__tar.gz

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 (35) hide show
  1. {bladekit-4.41.0 → bladekit-4.43.0}/PKG-INFO +2 -1
  2. {bladekit-4.41.0 → bladekit-4.43.0}/pyproject.toml +2 -1
  3. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_client.py +64 -3
  4. bladekit-4.43.0/src/bladekit/_metrics_cli.py +429 -0
  5. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_render.py +220 -8
  6. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/cli.py +603 -4
  7. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/exceptions.py +3 -0
  8. {bladekit-4.41.0 → bladekit-4.43.0}/.gitignore +0 -0
  9. {bladekit-4.41.0 → bladekit-4.43.0}/README.md +0 -0
  10. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/__init__.py +0 -0
  11. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_app.py +0 -0
  12. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_banner.py +0 -0
  13. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_batch.py +0 -0
  14. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_bucket.py +0 -0
  15. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_build.py +0 -0
  16. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_bundle.py +0 -0
  17. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_cls.py +0 -0
  18. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_constants.py +0 -0
  19. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_cron.py +0 -0
  20. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_dict.py +0 -0
  21. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_env.py +0 -0
  22. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_exported_metrics.py +0 -0
  23. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_image.py +0 -0
  24. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_loader.py +0 -0
  25. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_map.py +0 -0
  26. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_preempt.py +0 -0
  27. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_queue.py +0 -0
  28. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_runner_api.py +0 -0
  29. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_sandbox.py +0 -0
  30. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_secret.py +0 -0
  31. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_serialize.py +0 -0
  32. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_serve.py +0 -0
  33. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_volume.py +0 -0
  34. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/_webhook.py +0 -0
  35. {bladekit-4.41.0 → bladekit-4.43.0}/src/bladekit/config.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: bladekit
3
- Version: 4.41.0
3
+ Version: 4.43.0
4
4
  Summary: Blade AI Fabric SDK + CLI — run Python functions on Blade's GPU fleet.
5
5
  Project-URL: Homepage, https://blade.sh
6
6
  Project-URL: Documentation, https://console.blade.sh
@@ -16,6 +16,7 @@ Requires-Dist: watchfiles>=0.21
16
16
  Provides-Extra: dev
17
17
  Requires-Dist: pytest-timeout>=2.3; extra == 'dev'
18
18
  Requires-Dist: pytest>=8.0; extra == 'dev'
19
+ Requires-Dist: pyyaml; extra == 'dev'
19
20
  Description-Content-Type: text/markdown
20
21
 
21
22
  # bladekit — Blade AI Fabric SDK + CLI
@@ -16,7 +16,7 @@
16
16
  # uninstalled during an upgrade, and `forge` is a different project's name on
17
17
  # public PyPI.
18
18
  name = "bladekit"
19
- version = "4.41.0"
19
+ version = "4.43.0"
20
20
  description = "Blade AI Fabric SDK + CLI — run Python functions on Blade's GPU fleet."
21
21
  readme = "README.md"
22
22
  requires-python = ">=3.10"
@@ -45,6 +45,7 @@ bladekit = "bladekit.cli:app"
45
45
  dev = [
46
46
  "pytest>=8.0",
47
47
  "pytest-timeout>=2.3",
48
+ "pyyaml",
48
49
  ]
49
50
 
50
51
  [build-system]
@@ -34,6 +34,7 @@ _CODE_EXC = {
34
34
  "UNAUTHENTICATED": exc.AuthenticationError,
35
35
  "RUN_TOKEN_EXPIRED": exc.AuthenticationError,
36
36
  "PERMISSION_DENIED": exc.PermissionDeniedError,
37
+ "INSUFFICIENT_SCOPE": exc.PermissionDeniedError,
37
38
  "NOT_FOUND": exc.NotFoundError,
38
39
  "RUN_NOT_FOUND": exc.NotFoundError,
39
40
  "CALL_NOT_FOUND": exc.NotFoundError,
@@ -46,6 +47,14 @@ _CODE_EXC = {
46
47
  "EXPORTED_METRICS_INVALID": exc.InvalidArgumentError,
47
48
  "METRIC_NAME_COLLISION": exc.InvalidArgumentError,
48
49
  "METRIC_BUDGET_EXCEEDED": exc.InvalidArgumentError,
50
+ "EXPORT_TOO_LARGE": exc.InvalidArgumentError,
51
+ # P-PAAS-304 push destinations (/v1/metrics/destinations).
52
+ "METRICS_DESTINATION_NAME_CONFLICT": exc.ConflictError,
53
+ "METRICS_DESTINATION_LIMIT": exc.InvalidArgumentError,
54
+ "CREDENTIALS_REQUIRED_FOR_NEW_HOST": exc.InvalidArgumentError,
55
+ "METRICS_DESTINATION_NOT_FOUND": exc.NotFoundError,
56
+ # Kept on the base class: callers branch on ``.code`` and ``.retry_after``.
57
+ "RATE_LIMITED": exc.APIError,
49
58
  "BUNDLE_NOT_READY": exc.ConflictError,
50
59
  "BUNDLE_CHECKSUM_MISMATCH": exc.ConflictError,
51
60
  "RUN_NOT_CANCELLABLE": exc.ConflictError,
@@ -138,7 +147,20 @@ def _version_lt(current: str, minimum: str) -> bool:
138
147
  return _version_tuple(current) < _version_tuple(minimum)
139
148
 
140
149
 
141
- def _raise_for_envelope(status: int, body: Any) -> None:
150
+ def _retry_after(headers: Optional[Mapping[str, str]]) -> Optional[float]:
151
+ """``Retry-After`` in seconds (delta-seconds form only), else ``None``."""
152
+ if not headers:
153
+ return None
154
+ raw = headers.get("Retry-After")
155
+ try:
156
+ return max(0.0, float(raw)) if raw is not None else None
157
+ except ValueError:
158
+ return None
159
+
160
+
161
+ def _raise_for_envelope(
162
+ status: int, body: Any, headers: Optional[Mapping[str, str]] = None
163
+ ) -> None:
142
164
  code = "INTERNAL"
143
165
  message = f"HTTP {status}"
144
166
  details: Mapping[str, Any] = {}
@@ -152,7 +174,9 @@ def _raise_for_envelope(status: int, body: Any) -> None:
152
174
  # Prefer the machine code for the class; fall back to status family; then
153
175
  # a generic APIError so unknown codes are still surfaced (conventions §2).
154
176
  cls = _CODE_EXC.get(code) or _STATUS_EXC.get(status) or exc.APIError
155
- raise cls(code, message, status_code=status, details=details)
177
+ raise cls(
178
+ code, message, status_code=status, details=details, retry_after=_retry_after(headers)
179
+ )
156
180
 
157
181
 
158
182
  def _could_not_connect(err: BaseException) -> bool:
@@ -220,7 +244,7 @@ class Client:
220
244
  body = resp.json()
221
245
  except ValueError:
222
246
  body = None
223
- _raise_for_envelope(resp.status_code, body)
247
+ _raise_for_envelope(resp.status_code, body, resp.headers)
224
248
 
225
249
  if resp.content:
226
250
  return resp.json()
@@ -778,6 +802,43 @@ class Client:
778
802
  json={"exported_metrics": metrics},
779
803
  )
780
804
 
805
+ def get_app_metrics(self, app_id: str, *, range_: str = "6h") -> dict:
806
+ """Platform and custom metric series for an app (by id) over ``range_``."""
807
+ return self._request("GET", f"/v1/apps/{app_id}/metrics", params={"range": range_})
808
+
809
+ def get_run_metrics(self, run_id: str, *, range_: str | None = None) -> dict:
810
+ """Resource series for a run; absent range selects its whole lifetime."""
811
+ params = {"range": range_} if range_ is not None else None
812
+ return self._request("GET", f"/v1/runs/{run_id}/metrics", params=params)
813
+
814
+ def get_app_metrics_latest(self, app: str) -> dict:
815
+ """Latest exported custom values of an app (id or name) and their status."""
816
+ return self._request("GET", f"/v1/apps/{app}/metrics/latest")
817
+
818
+ # -- metrics push destinations ------------------------------------------
819
+
820
+ def list_metrics_destinations(self) -> list[dict]:
821
+ """The org's push destinations (never with credential values)."""
822
+ return self._request("GET", "/v1/metrics/destinations")["items"]
823
+
824
+ def get_metrics_destination(self, destination_id: str) -> dict:
825
+ return self._request("GET", f"/v1/metrics/destinations/{destination_id}")
826
+
827
+ def create_metrics_destination(self, body: dict) -> dict:
828
+ """``body`` carries ``credentials`` and ``acknowledge_data_leaves_blade``."""
829
+ return self._request("POST", "/v1/metrics/destinations", json=body)
830
+
831
+ def update_metrics_destination(self, destination_id: str, body: dict) -> dict:
832
+ """Partial update (PATCH); a host change needs credentials and a new acknowledgement."""
833
+ return self._request("PATCH", f"/v1/metrics/destinations/{destination_id}", json=body)
834
+
835
+ def delete_metrics_destination(self, destination_id: str) -> None:
836
+ self._request("DELETE", f"/v1/metrics/destinations/{destination_id}")
837
+
838
+ def test_metrics_destination(self, destination_id: str) -> dict:
839
+ """One push now: ``{status_code, error, series, bytes, duration_ms}``."""
840
+ return self._request("POST", f"/v1/metrics/destinations/{destination_id}/test")
841
+
781
842
  def create_deployment(self, app_id: str, body: dict) -> dict:
782
843
  return self._request("POST", f"/v1/apps/{app_id}/deployments", json=body)
783
844
 
@@ -0,0 +1,429 @@
1
+ """Helpers for the ``blade metrics`` CLI group.
2
+
3
+ Interval parsing, series statistics, sparklines, unit-aware value formatting,
4
+ host normalisation, app reference resolution, metric rows and push-destination
5
+ helpers. I/O is limited to the stdin/environ passed to :func:`read_credentials`,
6
+ the egress prompt of :func:`confirm_egress` and the client passed in.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import math
12
+ import re
13
+ import sys
14
+ import time
15
+ from collections.abc import Callable, Iterable, Mapping
16
+ from typing import TextIO
17
+ from urllib.parse import urlsplit
18
+
19
+ RANGES: tuple[str, ...] = ("1h", "6h", "24h", "7d")
20
+
21
+ _BARS = "▁▂▃▄▅▆▇█"
22
+ _INTERVAL_RE = re.compile(r"^(\d+)([sm]?)$")
23
+ _TIME_UNITS = {"s": 1.0, "ms": 1e-3, "us": 1e-6}
24
+ _SIZE_UNITS = {"By": 1, "bytes": 1, "KiBy": 1024, "MiBy": 1024**2, "GiBy": 1024**3}
25
+
26
+
27
+ class CredentialsError(ValueError):
28
+ """Malformed credentials input. The message never contains a credential value."""
29
+
30
+
31
+ def stdin_is_tty() -> bool:
32
+ return sys.stdin.isatty()
33
+
34
+
35
+ def parse_interval(text: str, *, minimum: int, maximum: int | None = None) -> int:
36
+ """Parse ``"5s"``, ``"2m"`` or ``"60"`` into seconds, enforcing the bounds."""
37
+ bounds = f"at least {minimum}s" if maximum is None else f"between {minimum}s and {maximum}s"
38
+ match = _INTERVAL_RE.match(text.strip())
39
+ if match is None:
40
+ raise ValueError(f"invalid interval {text!r}: use e.g. 30s or 2m, {bounds}")
41
+ seconds = int(match.group(1)) * (60 if match.group(2) == "m" else 1)
42
+ if seconds < minimum or (maximum is not None and seconds > maximum):
43
+ raise ValueError(f"interval {text!r} out of range: must be {bounds}")
44
+ return seconds
45
+
46
+
47
+ def _finite(values: Iterable[float | None]) -> list[float]:
48
+ return [v for v in values if v is not None and math.isfinite(v)]
49
+
50
+
51
+ def series_stats(points: list[dict]) -> dict[str, float | None]:
52
+ """latest/min/avg/max over the finite point values; all ``None`` when there are none."""
53
+ vals = _finite([p.get("v") for p in points])
54
+ if not vals:
55
+ return {"latest": None, "min": None, "avg": None, "max": None}
56
+ return {"latest": vals[-1], "min": min(vals), "avg": sum(vals) / len(vals), "max": max(vals)}
57
+
58
+
59
+ def sparkline(values: list[float], width: int = 20) -> str:
60
+ """One bar per value (bucket means beyond ``width``); NaN/empty buckets draw as a gap."""
61
+ if len(values) > width:
62
+ n = len(values)
63
+ buckets: list[float] = []
64
+ for i in range(width):
65
+ chunk = _finite(values[i * n // width:(i + 1) * n // width])
66
+ buckets.append(sum(chunk) / len(chunk) if chunk else math.nan)
67
+ values = buckets
68
+ finite = _finite(values)
69
+ if not finite:
70
+ return " " * len(values)
71
+ lo, hi = min(finite), max(finite)
72
+ out = []
73
+ for v in values:
74
+ if not math.isfinite(v):
75
+ out.append(" ")
76
+ elif hi == lo:
77
+ out.append(_BARS[3])
78
+ else:
79
+ out.append(_BARS[round((v - lo) / (hi - lo) * (len(_BARS) - 1))])
80
+ return "".join(out)
81
+
82
+
83
+ def _sig3(value: float) -> str:
84
+ """Three significant digits, trailing zeros dropped, never scientific notation."""
85
+ if value == 0:
86
+ return "0"
87
+ decimals = 2 - math.floor(math.log10(abs(value)))
88
+ rounded = round(value, decimals)
89
+ if decimals <= 0:
90
+ return str(int(rounded))
91
+ return f"{rounded:.{decimals}f}".rstrip("0").rstrip(".")
92
+
93
+
94
+ def _scaled(value: float, steps: list[tuple[float, str]]) -> str:
95
+ """Pick the largest step whose factor ≤ |value| (first step is the floor)."""
96
+ factor, suffix = steps[0]
97
+ for f, s in steps:
98
+ if abs(value) >= f:
99
+ factor, suffix = f, s
100
+ return _sig3(value / factor) + suffix
101
+
102
+
103
+ def format_value(value: float | None, unit: str, *, rate: bool = False) -> str:
104
+ """Human value with its unit; ``rate`` appends ``/s``. ``None`` → ``-``."""
105
+ if value is None:
106
+ return "-"
107
+ if math.isnan(value):
108
+ return "NaN"
109
+ if math.isinf(value):
110
+ return "+Inf" if value > 0 else "-Inf"
111
+ per = "/s" if rate else ""
112
+ if unit in _TIME_UNITS:
113
+ secs = value * _TIME_UNITS[unit]
114
+ text = _scaled(secs, [(1e-6, " µs"), (1e-3, " ms"), (1.0, " s"), (60.0, " min")])
115
+ return text + per
116
+ if unit in _SIZE_UNITS:
117
+ size = value * _SIZE_UNITS[unit]
118
+ text = _scaled(size, [(1, " B"), (1024, " KiB"), (1024**2, " MiB"), (1024**3, " GiB")])
119
+ return text + per
120
+ if unit == "1":
121
+ return _sig3(value * 100) + "%" + per
122
+ if unit == "%":
123
+ return _sig3(value) + "%" + per
124
+ number = _scaled(value, [(1, ""), (1e3, "k"), (1e6, "M"), (1e9, "G")])
125
+ if unit.startswith("{") and unit.endswith("}"):
126
+ noun = unit[1:-1]
127
+ if value != 1:
128
+ noun += "s"
129
+ return f"{number} {noun}{per}"
130
+ if unit:
131
+ return f"{number} {unit}{per}"
132
+ return f"{number} {per}" if rate else number
133
+
134
+
135
+ def url_host(url: str) -> str:
136
+ """Lowercase hostname without port, brackets or trailing dot (``""`` if absent)."""
137
+ host = urlsplit(url.strip()).hostname or ""
138
+ return host.rstrip(".")
139
+
140
+
141
+ def resolve_app_ref(client, name_or_id: str, *, allow_name: bool) -> str:
142
+ """An ``app_`` id as is, else the id of the app with that name.
143
+
144
+ A metrics-only key may not list apps (403). Routes that accept names get the
145
+ name back (``allow_name``); id-only routes get an actionable error instead.
146
+ """
147
+ from . import exceptions as exc
148
+ from .cli import _resolve_app_id
149
+
150
+ try:
151
+ return _resolve_app_id(client, name_or_id)
152
+ except exc.PermissionDeniedError as e:
153
+ if e.code != "INSUFFICIENT_SCOPE":
154
+ raise
155
+ if allow_name:
156
+ return name_or_id
157
+ raise exc.InvalidArgumentError(
158
+ "INSUFFICIENT_SCOPE", "a metrics-only key cannot resolve app names; pass the app_ id"
159
+ ) from None
160
+
161
+
162
+ # ---- push destinations ----------------------------------------------------
163
+
164
+ PROTOCOLS: dict[str, str] = {"otlp": "otlp_http", "remote-write": "prometheus_remote_write"}
165
+ AUTH_KINDS: tuple[str, ...] = ("none", "bearer", "basic", "headers")
166
+ TEMPORALITIES: tuple[str, ...] = ("cumulative", "delta")
167
+ INCLUDE_KEYS: tuple[str, ...] = ("platform", "custom", "requests")
168
+ _AUTH_KEYS: dict[str, dict[str, str]] = {
169
+ "bearer": {"TOKEN": "token"},
170
+ "basic": {"USERNAME": "username", "PASSWORD": "password"},
171
+ }
172
+
173
+
174
+ def check_destination_url(url: str) -> str:
175
+ """The normalised host of an https receiver URL; ``ValueError`` otherwise (D17)."""
176
+ parts = urlsplit(url.strip())
177
+ if parts.scheme.lower() != "https":
178
+ raise ValueError("--url must use https (https only)")
179
+ if parts.username is not None or parts.password is not None:
180
+ raise ValueError("--url must not contain a user or password; use --auth")
181
+ host = url_host(url)
182
+ if not host:
183
+ raise ValueError("--url has no host")
184
+ return host
185
+
186
+
187
+ def _credential_values(wanted: Mapping[str, str], from_env: list[str], stdin: TextIO,
188
+ environ: Mapping[str, str]) -> dict[str, str]:
189
+ """``KEY -> value`` from ``--from-env`` items when given, else stdin ``KEY=VALUE`` lines.
190
+
191
+ Only keys in ``wanted`` are ever echoed: anything else may be a secret (a raw
192
+ token split at its padding, or a ``--from-env`` item expanded by the shell).
193
+ """
194
+ values: dict[str, str] = {}
195
+ if from_env:
196
+ for index, item in enumerate(from_env, start=1):
197
+ key, _, var = item.partition("=")
198
+ key, var = key.strip(), (var.strip() or key.strip())
199
+ if key not in wanted:
200
+ raise CredentialsError(f"unexpected key in --from-env item {index}")
201
+ if key in values:
202
+ raise CredentialsError(f"credential key {key} given twice")
203
+ if var not in environ:
204
+ raise CredentialsError(f"the environment variable for {key} is not set")
205
+ values[key] = environ[var]
206
+ return values
207
+ for lineno, line in enumerate(stdin.read().splitlines(), start=1):
208
+ if not line.strip():
209
+ continue
210
+ key, sep, value = line.partition("=")
211
+ key = key.strip()
212
+ if not sep or not key:
213
+ raise CredentialsError(f"stdin line {lineno} is not KEY=VALUE")
214
+ if key not in wanted:
215
+ raise CredentialsError(f"unexpected key on stdin line {lineno}")
216
+ if key in values:
217
+ raise CredentialsError(f"credential key {key} given twice")
218
+ values[key] = value
219
+ return values
220
+
221
+
222
+ def read_credentials(auth: str, header_names: list[str], from_env: list[str], *,
223
+ stdin: TextIO, environ: Mapping[str, str]) -> dict | None:
224
+ """The ``credentials`` object for ``auth``, read from ``--from-env`` or stdin.
225
+
226
+ ``none`` reads nothing. ``bearer`` wants TOKEN, ``basic`` USERNAME and PASSWORD,
227
+ ``headers`` exactly the ``--header`` names. Errors name keys, never values.
228
+ """
229
+ if auth == "none":
230
+ if from_env:
231
+ raise CredentialsError("--auth none takes no credentials; drop --from-env")
232
+ return None
233
+ wanted = {n: n for n in header_names} if auth == "headers" else _AUTH_KEYS[auth]
234
+ values = _credential_values(wanted, from_env, stdin, environ)
235
+ missing = [k for k in wanted if k not in values]
236
+ if missing:
237
+ raise CredentialsError(f"--auth {auth} credentials: missing {', '.join(missing)}")
238
+ empty = [k for k in wanted if not values[k]]
239
+ if empty:
240
+ raise CredentialsError(f"empty value for {', '.join(empty)}")
241
+ if auth == "headers":
242
+ return {"headers": {k: values[k] for k in wanted}}
243
+ return {field: values[key] for key, field in wanted.items()}
244
+
245
+
246
+ def confirm_egress(host: str, *, acknowledged: bool) -> None:
247
+ """Require consent before metrics leave Blade: flag, TTY prompt, else exit 2."""
248
+ import typer
249
+
250
+ if acknowledged:
251
+ return
252
+ # Global looked up per call so tests can patch ``bladekit._metrics_cli.stdin_is_tty``.
253
+ if not stdin_is_tty():
254
+ typer.echo(f"error: pass --yes-data-leaves-blade to send metrics to {host}", err=True)
255
+ raise typer.Exit(2)
256
+ if not typer.confirm(
257
+ f"Metrics from the selected apps will be sent to {host}, outside Blade. Continue?"
258
+ ):
259
+ raise typer.Exit(1)
260
+
261
+
262
+ def destination_body(*, name: str | None, protocol: str | None, url: str | None,
263
+ auth: str | None, header_names: list[str] | None,
264
+ temporality: str | None, apps: list[str] | None,
265
+ include: list[str] | None, interval_seconds: int | None) -> dict:
266
+ """A destination create/update body holding only the fields that were given."""
267
+ fields = {
268
+ "name": name,
269
+ "protocol": None if protocol is None else PROTOCOLS[protocol],
270
+ "url": url,
271
+ "auth_kind": auth,
272
+ "header_names": header_names,
273
+ "temporality": temporality,
274
+ "apps": apps,
275
+ "include": None if include is None else {k: k in include for k in INCLUDE_KEYS},
276
+ "interval_seconds": interval_seconds,
277
+ }
278
+ return {k: v for k, v in fields.items() if v is not None}
279
+
280
+
281
+ def resolve_destination(client, name_or_id: str) -> dict:
282
+ """The destination with this ``mdst_`` id, else the one with exactly this name."""
283
+ from . import exceptions as exc
284
+
285
+ if name_or_id.startswith("mdst_"):
286
+ return client.get_metrics_destination(name_or_id)
287
+ for item in client.list_metrics_destinations():
288
+ if item.get("name") == name_or_id:
289
+ return item
290
+ raise exc.NotFoundError(
291
+ "METRICS_DESTINATION_NOT_FOUND", f"no metrics destination named {name_or_id!r}"
292
+ )
293
+
294
+
295
+ def _row(group: str, metric: str, endpoint: str | None, unit: str, series: dict,
296
+ *, type_: str | None = None, status: str | None = None,
297
+ reason: str | None = None) -> dict:
298
+ points = series.get("points") or []
299
+ return {
300
+ "group": group, "metric": metric, "endpoint": endpoint,
301
+ "labels": dict(series.get("labels") or {}), "unit": unit, "type": type_,
302
+ "status": status, "reason": reason, **series_stats(points),
303
+ # Not part of the --json contract: the sparkline input, dropped before JSON.
304
+ "values": [math.nan if p.get("v") is None else p["v"] for p in points],
305
+ }
306
+
307
+
308
+ def metrics_rows(resp: dict, *, endpoint: str | None, metrics: list[str]) -> list[dict]:
309
+ """One row per series of an AppMetrics response, platform rows first.
310
+
311
+ ``endpoint`` keeps only custom metrics of that endpoint; ``metrics`` (platform
312
+ keys or declared custom names) keeps only those. Rows carry a ``values`` list
313
+ for the sparkline that callers drop from ``--json`` output.
314
+ """
315
+ wanted = set(metrics)
316
+ rows: list[dict] = []
317
+ for m in resp.get("metrics") or []:
318
+ if wanted and m.get("metric") not in wanted:
319
+ continue
320
+ for series in m.get("series") or [{"labels": {}, "points": []}]:
321
+ rows.append(_row("platform", m.get("metric", ""), None, m.get("unit") or "", series))
322
+ for c in resp.get("custom") or []:
323
+ if endpoint is not None and c.get("endpoint") != endpoint:
324
+ continue
325
+ if wanted and c.get("name") not in wanted:
326
+ continue
327
+ series_list = c.get("series") or [{"labels": {}, "points": []}]
328
+ for series in series_list:
329
+ rows.append(_row(
330
+ "custom", c.get("name", ""), c.get("endpoint"), c.get("unit") or "", series,
331
+ type_=c.get("type"), status=c.get("status"), reason=c.get("reason"),
332
+ ))
333
+ return rows
334
+
335
+
336
+ def workload_rows(resp: dict) -> list[dict]:
337
+ """Flatten run resource series in server order, retaining GPU labels."""
338
+ rows: list[dict] = []
339
+ for metric in resp.get("metrics") or []:
340
+ for series in metric.get("series") or [{"labels": {}, "points": []}]:
341
+ rows.append({
342
+ "metric": metric["metric"],
343
+ "labels": dict(series.get("labels") or {}),
344
+ "unit": metric.get("unit") or "",
345
+ **series_stats(series.get("points") or []),
346
+ })
347
+ return rows
348
+
349
+
350
+ def watch_loop(fetch: Callable[[], dict], show: Callable[[dict | None, str], None], *,
351
+ interval: int, sleep: Callable[[float], None] = time.sleep) -> None:
352
+ """Poll ``fetch`` every ``interval`` seconds until Ctrl-C.
353
+
354
+ A 429 ``RATE_LIMITED`` never ends the loop: ``show(None, caption)`` keeps the
355
+ last table, and the wait honours ``Retry-After`` when it exceeds ``interval``.
356
+ Other errors propagate to the caller.
357
+ """
358
+ from . import exceptions as exc
359
+
360
+ try:
361
+ while True:
362
+ wait: float = interval
363
+ try:
364
+ resp = fetch()
365
+ except exc.APIError as e:
366
+ if e.code != "RATE_LIMITED":
367
+ raise
368
+ wait = max(interval, math.ceil(e.retry_after or 0))
369
+ show(None, f"rate limited, retrying in {wait}s")
370
+ else:
371
+ show(resp, "")
372
+ sleep(wait)
373
+ except KeyboardInterrupt:
374
+ return
375
+
376
+
377
+ _SCRAPE_TEMPLATES = {
378
+ "prometheus": """\
379
+ # Write your metrics key ($BLADE_METRICS_TOKEN) into the credentials file.
380
+ scrape_configs:
381
+ - job_name: <job>
382
+ scrape_interval: 30s # 15 s minimum
383
+ scheme: https
384
+ metrics_path: <path>
385
+ authorization:
386
+ credentials_file: /etc/prometheus/blade_metrics_token
387
+ static_configs:
388
+ - targets: [<host>]
389
+ """,
390
+ "alloy": """\
391
+ prometheus.scrape "<job>" {
392
+ targets = [{ __address__ = "<host>" }]
393
+ scheme = "https"
394
+ metrics_path = "<path>"
395
+ scrape_interval = "30s"
396
+ authorization {
397
+ type = "Bearer"
398
+ credentials = sys.env("BLADE_METRICS_TOKEN")
399
+ }
400
+ forward_to = [prometheus.remote_write.default.receiver]
401
+ }
402
+ """,
403
+ "datadog": """\
404
+ # conf.d/openmetrics.d/conf.yaml — replace $BLADE_METRICS_TOKEN with your metrics key.
405
+ instances:
406
+ - openmetrics_endpoint: https://<host><path>
407
+ namespace: blade
408
+ min_collection_interval: 30
409
+ metrics:
410
+ - forge_app_.*
411
+ - forge_vllm_.*
412
+ headers:
413
+ Authorization: "Bearer $BLADE_METRICS_TOKEN"
414
+ """,
415
+ }
416
+ SCRAPE_FORMATS: tuple[str, ...] = tuple(_SCRAPE_TEMPLATES)
417
+
418
+
419
+ def scrape_config(fmt: str, *, api_url: str, app_ref: str | None, app_name: str | None) -> str:
420
+ """Scrape snippet for ``fmt``; ``app_ref=None`` targets the org route. No credentials."""
421
+ host = urlsplit(api_url).netloc
422
+ if app_ref is None:
423
+ path, job = "/v1/metrics/export", "blade-org"
424
+ else:
425
+ path, job = f"/v1/apps/{app_ref}/metrics/export", f"blade-{app_name or app_ref}"
426
+ if fmt == "alloy":
427
+ job = re.sub(r"[^A-Za-z0-9_]", "_", job)
428
+ return (_SCRAPE_TEMPLATES[fmt]
429
+ .replace("<job>", job).replace("<host>", host).replace("<path>", path))