bladekit 4.34.3__tar.gz → 4.36.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 (34) hide show
  1. {bladekit-4.34.3 → bladekit-4.36.0}/PKG-INFO +1 -1
  2. {bladekit-4.34.3 → bladekit-4.36.0}/pyproject.toml +1 -1
  3. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/__init__.py +2 -0
  4. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_app.py +13 -0
  5. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_client.py +27 -0
  6. bladekit-4.36.0/src/bladekit/_exported_metrics.py +181 -0
  7. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_render.py +32 -0
  8. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/cli.py +144 -1
  9. {bladekit-4.34.3 → bladekit-4.36.0}/.gitignore +0 -0
  10. {bladekit-4.34.3 → bladekit-4.36.0}/README.md +0 -0
  11. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_banner.py +0 -0
  12. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_batch.py +0 -0
  13. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_bucket.py +0 -0
  14. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_build.py +0 -0
  15. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_bundle.py +0 -0
  16. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_cls.py +0 -0
  17. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_constants.py +0 -0
  18. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_cron.py +0 -0
  19. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_dict.py +0 -0
  20. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_env.py +0 -0
  21. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_image.py +0 -0
  22. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_loader.py +0 -0
  23. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_map.py +0 -0
  24. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_preempt.py +0 -0
  25. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_queue.py +0 -0
  26. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_runner_api.py +0 -0
  27. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_sandbox.py +0 -0
  28. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_secret.py +0 -0
  29. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_serialize.py +0 -0
  30. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_serve.py +0 -0
  31. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_volume.py +0 -0
  32. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/_webhook.py +0 -0
  33. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/config.py +0 -0
  34. {bladekit-4.34.3 → bladekit-4.36.0}/src/bladekit/exceptions.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: bladekit
3
- Version: 4.34.3
3
+ Version: 4.36.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,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.34.3"
19
+ version = "4.36.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"
@@ -41,6 +41,7 @@ compatibility package that installs this one plus a ``forge`` import shim and a
41
41
 
42
42
  from __future__ import annotations
43
43
 
44
+ from ._exported_metrics import ExportMetric
44
45
  from ._app import (
45
46
  App,
46
47
  Autoscale,
@@ -132,6 +133,7 @@ __all__ = [
132
133
  "App",
133
134
  "app",
134
135
  "Autoscale",
136
+ "ExportMetric",
135
137
  "Function",
136
138
  "FunctionCall",
137
139
  "DeployedFunctionCall",
@@ -24,6 +24,7 @@ if TYPE_CHECKING: # pragma: no cover — typing only, avoids an import cycle
24
24
  from ._map import MapHandle
25
25
 
26
26
  from . import exceptions as exc
27
+ from ._exported_metrics import ExportMetric, validate_export_metrics
27
28
  from ._constants import (
28
29
  CALL_TERMINAL_STATES,
29
30
  DEFAULT_CPU_MILLICORES,
@@ -266,6 +267,8 @@ class EndpointDeclaration:
266
267
  # GPU snapshot opt-in (coldstart-snapshot.md §5). Valid ONLY on web_server
267
268
  # with gpu_count==1 — validated in _endpoint_specs() (mirror of the server).
268
269
  snapshot: bool = False
270
+ # Exported app metrics (P-PAAS-304 §4.1). Non-empty only on web_server.
271
+ export_metrics: tuple[ExportMetric, ...] = ()
269
272
 
270
273
 
271
274
  @dataclass
@@ -544,6 +547,7 @@ class Function:
544
547
  startup_timeout_seconds=decl.startup_timeout_seconds,
545
548
  autoscale=decl.autoscale,
546
549
  snapshot=decl.snapshot,
550
+ export_metrics=decl.export_metrics,
547
551
  )
548
552
  self._endpoints.append(normalized)
549
553
 
@@ -567,6 +571,7 @@ class Function:
567
571
  startup_timeout_seconds=decl.startup_timeout_seconds,
568
572
  autoscale=decl.autoscale,
569
573
  snapshot=decl.snapshot,
574
+ export_metrics=decl.export_metrics,
570
575
  )
571
576
 
572
577
  def _set_target_inputs(self, target_inputs: int) -> None:
@@ -1067,6 +1072,9 @@ class Function:
1067
1072
  # the deployed endpoint to fuse concurrent requests into batches.
1068
1073
  if self.batch_config is not None:
1069
1074
  spec["batch_config"] = self.batch_config
1075
+ # R7: deploy is authoritative, so the key is sent on EVERY endpoint;
1076
+ # [] clears a live value. label/unit are omitted, never null.
1077
+ spec["exported_metrics"] = [m.to_spec() for m in decl.export_metrics]
1070
1078
  specs.append(spec)
1071
1079
  return specs
1072
1080
 
@@ -2617,6 +2625,7 @@ class App:
2617
2625
  public: bool = False,
2618
2626
  autoscale: Optional[Autoscale] = None,
2619
2627
  snapshot: bool = False,
2628
+ export_metrics: Optional[Sequence[ExportMetric]] = None,
2620
2629
  ):
2621
2630
  """Decorator: serve a long-lived HTTP server running inside the container.
2622
2631
 
@@ -2678,6 +2687,9 @@ class App:
2678
2687
  max_queue_depth=max_queue_depth,
2679
2688
  )
2680
2689
  _validate_endpoint_autoscale("web_server", autoscale)
2690
+ exported = (
2691
+ validate_export_metrics(export_metrics) if export_metrics is not None else ()
2692
+ )
2681
2693
 
2682
2694
  def wrap(fn: Callable[..., Any]) -> Function:
2683
2695
  decl = EndpointDeclaration(
@@ -2696,6 +2708,7 @@ class App:
2696
2708
  startup_timeout_seconds=startup_timeout,
2697
2709
  autoscale=autoscale,
2698
2710
  snapshot=snapshot,
2711
+ export_metrics=exported,
2699
2712
  )
2700
2713
  if isinstance(fn, Function):
2701
2714
  return _apply_endpoint_marker(fn, decl)
@@ -42,6 +42,10 @@ _CODE_EXC = {
42
42
  "INVALID_ARGUMENT": exc.InvalidArgumentError,
43
43
  "INVALID_CURSOR": exc.InvalidArgumentError,
44
44
  "IMAGE_ALIAS_UNKNOWN": exc.InvalidArgumentError,
45
+ # P-PAAS-304 exported app metrics (declaration, collision, series budget).
46
+ "EXPORTED_METRICS_INVALID": exc.InvalidArgumentError,
47
+ "METRIC_NAME_COLLISION": exc.InvalidArgumentError,
48
+ "METRIC_BUDGET_EXCEEDED": exc.InvalidArgumentError,
45
49
  "BUNDLE_NOT_READY": exc.ConflictError,
46
50
  "BUNDLE_CHECKSUM_MISMATCH": exc.ConflictError,
47
51
  "RUN_NOT_CANCELLABLE": exc.ConflictError,
@@ -197,6 +201,7 @@ class Client:
197
201
  # makes the at-most-once promise safe if a worker thread also touches it.
198
202
  self._version_checked = False
199
203
  self._version_lock = threading.Lock()
204
+ self._features: Optional[frozenset[str]] = None
200
205
 
201
206
  # -- low level ----------------------------------------------------------
202
207
 
@@ -235,6 +240,14 @@ class Client:
235
240
  def get_version(self) -> dict:
236
241
  return self._request("GET", "/v1/version")
237
242
 
243
+ def server_features(self) -> frozenset[str]:
244
+ """``GET /v1/version`` ``features``, fetched once per client; missing → empty."""
245
+ if self._features is None:
246
+ info = self.get_version()
247
+ raw = info.get("features") if isinstance(info, Mapping) else None
248
+ self._features = frozenset(str(f) for f in raw or [])
249
+ return self._features
250
+
238
251
  def warn_if_outdated(self) -> None:
239
252
  """Call ``/v1/version`` once and warn if the SDK is below ``min_sdk_version``.
240
253
 
@@ -751,6 +764,20 @@ class Client:
751
764
  "POST", f"/v1/apps/{app_id}/endpoints/{endpoint_name}/scale", json=body
752
765
  )
753
766
 
767
+ def set_exported_metrics(
768
+ self, app_id: str, endpoint_name: str, metrics: list[dict]
769
+ ) -> dict:
770
+ """Replace a deployed endpoint's exported_metrics live (``[]`` clears).
771
+
772
+ Returns ``{exported_metrics, rollout, warnings}``; the value lasts until
773
+ the next deploy, which replaces it (with an overwrite warning).
774
+ """
775
+ return self._request(
776
+ "PUT",
777
+ f"/v1/apps/{app_id}/endpoints/{endpoint_name}/exported-metrics",
778
+ json={"exported_metrics": metrics},
779
+ )
780
+
754
781
  def create_deployment(self, app_id: str, body: dict) -> dict:
755
782
  return self._request("POST", f"/v1/apps/{app_id}/deployments", json=body)
756
783
 
@@ -0,0 +1,181 @@
1
+ """Exported app metrics declared on ``@app.web_server(export_metrics=...)``.
2
+
3
+ Local mirror of the control plane's declaration rules (P-PAAS-304 §4.1/§4.7,
4
+ ``control-plane/internal/core/exported_metrics.go``). Name collisions and the
5
+ series budget stay server-side: they depend on the endpoint's scaling policy.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from dataclasses import KW_ONLY, dataclass
12
+ from typing import TYPE_CHECKING, Optional, Sequence
13
+
14
+ from . import exceptions as exc
15
+
16
+ if TYPE_CHECKING:
17
+ from ._client import Client
18
+
19
+ METRIC_TYPES: tuple[str, ...] = ("gauge", "counter", "histogram", "summary")
20
+ RESERVED_LABELS: frozenset[str] = frozenset(
21
+ {
22
+ "le",
23
+ "quantile",
24
+ "app",
25
+ "app_id",
26
+ "endpoint",
27
+ "replica",
28
+ "replica_id",
29
+ "gpu",
30
+ "gpu_uuid",
31
+ "instance",
32
+ "job",
33
+ "function",
34
+ "deployment",
35
+ "container_id",
36
+ "node_id",
37
+ "endpoint_id",
38
+ }
39
+ )
40
+ UNIT_CODES: frozenset[str] = frozenset(
41
+ {"s", "ms", "us", "By", "KiBy", "MiBy", "GiBy", "1", "%"}
42
+ )
43
+ MAX_EXPORTED_METRICS = 12
44
+
45
+ _CODE = "EXPORTED_METRICS_INVALID"
46
+ # fullmatch everywhere: Go's `$` is end-of-text, Python's `$` accepts a trailing "\n".
47
+ _NAME_RE = re.compile(r"[a-zA-Z_:][a-zA-Z0-9_:]{0,127}")
48
+ _LABEL_RE = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]{0,63}")
49
+ _NOUN_UNIT_RE = re.compile(r"\{[a-z][a-z0-9_]{0,23}\}")
50
+
51
+
52
+ @dataclass(frozen=True)
53
+ class ExportMetric:
54
+ """One app metric to export from a ``web_server`` endpoint's own ``/metrics``.
55
+
56
+ ``label`` names at most one label kept from the source series; ``unit`` is
57
+ display metadata only (UCUM code from ``UNIT_CODES`` or ``{noun}``).
58
+ """
59
+
60
+ name: str
61
+ type: str
62
+ _: KW_ONLY
63
+ label: Optional[str] = None
64
+ unit: Optional[str] = None
65
+
66
+ def __post_init__(self) -> None:
67
+ name = self.name
68
+ if (
69
+ not isinstance(name, str)
70
+ or not _NAME_RE.fullmatch(name)
71
+ or name.startswith(("vllm:", "forge_"))
72
+ or name.endswith(("_bucket", "_sum", "_count"))
73
+ ):
74
+ raise exc.InvalidArgumentError(
75
+ _CODE, f"invalid exported metric name {name!r}"
76
+ )
77
+ if self.type not in METRIC_TYPES:
78
+ raise exc.InvalidArgumentError(
79
+ _CODE, f"exported metric type must be one of {', '.join(METRIC_TYPES)}"
80
+ )
81
+ label = self.label
82
+ if label is not None and (
83
+ not isinstance(label, str)
84
+ or not _LABEL_RE.fullmatch(label)
85
+ or label.startswith(("__", "exported_"))
86
+ or label in RESERVED_LABELS
87
+ ):
88
+ raise exc.InvalidArgumentError(
89
+ _CODE, f"invalid exported metric label {label!r}"
90
+ )
91
+ unit = self.unit
92
+ if unit is not None and (
93
+ not isinstance(unit, str)
94
+ or (unit not in UNIT_CODES and not _NOUN_UNIT_RE.fullmatch(unit))
95
+ ):
96
+ raise exc.InvalidArgumentError(
97
+ _CODE, f"invalid exported metric unit {unit!r}"
98
+ )
99
+
100
+ def to_spec(self) -> dict[str, str]:
101
+ # label/unit are omitted, never null: the server refuses an explicit null.
102
+ spec = {"name": self.name, "type": self.type}
103
+ if self.label is not None:
104
+ spec["label"] = self.label
105
+ if self.unit is not None:
106
+ spec["unit"] = self.unit
107
+ return spec
108
+
109
+
110
+ def parse_metric_arg(arg: str) -> ExportMetric:
111
+ """Parse a CLI ``NAME:TYPE[:LABEL][@UNIT]`` spec into a validated ExportMetric.
112
+
113
+ The unit is the text after the LAST ``@``; the rest splits on ``:`` and the
114
+ type is found from the right, so a name keeps its colons (``ns:lat:histogram``).
115
+ """
116
+ head, at, unit = arg.rpartition("@")
117
+ if not at:
118
+ head, unit = arg, ""
119
+ parts = head.split(":")
120
+ if len(parts) >= 2 and parts[-1] in METRIC_TYPES:
121
+ name, type_, label = ":".join(parts[:-1]), parts[-1], None
122
+ elif len(parts) >= 3 and parts[-2] in METRIC_TYPES:
123
+ name, type_, label = ":".join(parts[:-2]), parts[-2], parts[-1]
124
+ else:
125
+ raise ValueError("expected NAME:TYPE[:LABEL][@UNIT]")
126
+ return ExportMetric(name, type_, label=label, unit=unit if at else None)
127
+
128
+
129
+ def validate_export_metrics(
130
+ metrics: Sequence[ExportMetric],
131
+ ) -> tuple[ExportMetric, ...]:
132
+ if isinstance(metrics, (str, bytes)) or not isinstance(metrics, Sequence):
133
+ raise exc.InvalidArgumentError(
134
+ _CODE, "export_metrics must be a sequence of bladekit.ExportMetric"
135
+ )
136
+ out = tuple(metrics)
137
+ if len(out) > MAX_EXPORTED_METRICS:
138
+ raise exc.InvalidArgumentError(
139
+ _CODE, f"export_metrics must have at most {MAX_EXPORTED_METRICS} entries"
140
+ )
141
+ for m in out:
142
+ if not isinstance(m, ExportMetric):
143
+ raise exc.InvalidArgumentError(
144
+ _CODE, "export_metrics entries must be bladekit.ExportMetric"
145
+ )
146
+ return out
147
+
148
+
149
+ def require_exported_metrics_support(client: "Client", endpoint_specs: list[dict]) -> None:
150
+ """Refuse, before anything is created, to send declarations a control plane
151
+ without the ``exported_metrics`` feature would silently drop (§4.6)."""
152
+ if not any(spec.get("exported_metrics") for spec in endpoint_specs):
153
+ return
154
+ if "exported_metrics" not in client.server_features():
155
+ raise exc.FabricError(
156
+ "this control plane does not support export_metrics; remove "
157
+ "export_metrics= or deploy to a newer control plane"
158
+ )
159
+
160
+
161
+ def check_exported_metrics_echo(endpoint_specs: list[dict], deployment: dict) -> None:
162
+ """Backstop: every endpoint's stored ``exported_metrics`` must equal what was sent."""
163
+ stored = {
164
+ ep.get("name"): ep.get("exported_metrics", [])
165
+ for ep in deployment.get("endpoints") or []
166
+ }
167
+ for spec in endpoint_specs:
168
+ name = spec.get("name")
169
+ if spec.get("exported_metrics", []) != stored.get(name, []):
170
+ raise exc.FabricError(
171
+ f"the control plane did not store export_metrics for endpoint {name!r}; "
172
+ "the deployment exists but will not export these metrics"
173
+ )
174
+
175
+
176
+ def warning_messages(body: dict) -> list[str]:
177
+ """Human messages of a response's ``warnings`` ([{code, message, details}])."""
178
+ return [
179
+ str(item["message"]) if isinstance(item, dict) and "message" in item else str(item)
180
+ for item in body.get("warnings") or []
181
+ ]
@@ -625,6 +625,38 @@ def secrets_table(items: list) -> Table:
625
625
  return table
626
626
 
627
627
 
628
+ def rollout_line(rollout: Optional[dict]) -> str:
629
+ """One line for an endpoint's ``exported_metrics_rollout`` (null = unknown)."""
630
+ if rollout is None:
631
+ return "rollout unknown (metrics backend unavailable)"
632
+ line = f"applied {rollout.get('applied', 0)}/{rollout.get('ready', 0)} ready"
633
+ legacy = rollout.get("legacy") or 0
634
+ if legacy:
635
+ line += f" ({legacy} legacy exporter{'' if legacy == 1 else 's'})"
636
+ return f"{line}: {rollout.get('state', '-')}"
637
+
638
+
639
+ def exported_metrics_table(endpoint: dict) -> Table:
640
+ source = endpoint.get("exported_metrics_source") or "—"
641
+ table = Table(
642
+ title=f"{endpoint.get('name', '-')} (source: {source})",
643
+ caption=rollout_line(endpoint.get("exported_metrics_rollout")),
644
+ header_style="bold",
645
+ )
646
+ table.add_column("name", overflow="fold")
647
+ table.add_column("type")
648
+ table.add_column("label")
649
+ table.add_column("unit")
650
+ for m in endpoint.get("exported_metrics") or []:
651
+ table.add_row(
652
+ Text(m.get("name", "-")),
653
+ m.get("type", "-"),
654
+ Text(m.get("label") or "-"),
655
+ Text(m.get("unit") or "-"),
656
+ )
657
+ return table
658
+
659
+
628
660
  def images_table(items: list) -> Table:
629
661
  table = Table(title="image catalogue", header_style="bold")
630
662
  table.add_column("alias")
@@ -64,6 +64,13 @@ app.add_typer(dict_app, name="dict")
64
64
  sandbox_app = typer.Typer(no_args_is_help=True, help="Manage sandboxes.")
65
65
  app.add_typer(sandbox_app, name="sandbox")
66
66
 
67
+ metrics_app = typer.Typer(no_args_is_help=True, help="App metrics.")
68
+ app.add_typer(metrics_app, name="metrics")
69
+ metrics_declare_app = typer.Typer(
70
+ no_args_is_help=True, help="Declare which app metrics Blade collects."
71
+ )
72
+ metrics_app.add_typer(metrics_declare_app, name="declare")
73
+
67
74
  admin_app = typer.Typer(
68
75
  no_args_is_help=True,
69
76
  help="Platform-admin containment tools (requires a staff SESSION token: an fg_ key "
@@ -1006,8 +1013,21 @@ def deploy(
1006
1013
  the raw build-step stream.
1007
1014
  """
1008
1015
  from ._loader import load_script
1009
- from ._render import phase, print_deployed, result_line, summary_line, set_verbose
1016
+ from ._exported_metrics import (
1017
+ check_exported_metrics_echo,
1018
+ require_exported_metrics_support,
1019
+ warning_messages,
1020
+ )
1021
+ from ._render import (
1022
+ err_console,
1023
+ phase,
1024
+ print_deployed,
1025
+ result_line,
1026
+ set_verbose,
1027
+ summary_line,
1028
+ )
1010
1029
  from rich.text import Text
1030
+ from rich.markup import escape
1011
1031
  from . import exceptions as exc
1012
1032
 
1013
1033
  if verbose:
@@ -1030,6 +1050,8 @@ def deploy(
1030
1050
  labels=labels or None,
1031
1051
  )
1032
1052
 
1053
+ # Refuse before create_app so an unsupported declaration creates nothing.
1054
+ require_exported_metrics_support(client, manifest.endpoints)
1033
1055
  gpu = _manifest_gpu(manifest)
1034
1056
  reg_meta = forge_app.name if not gpu else f"{forge_app.name} ({gpu})"
1035
1057
  with phase("registering", reg_meta):
@@ -1043,6 +1065,11 @@ def deploy(
1043
1065
  )
1044
1066
  ph.update(meta=url_text)
1045
1067
 
1068
+ # Warnings first, so they still print when the echo backstop raises.
1069
+ for message in warning_messages(deployment):
1070
+ err_console.print(f"[yellow]warning[/yellow]: {escape(message)}")
1071
+ check_exported_metrics_echo(manifest.endpoints, deployment)
1072
+
1046
1073
  endpoints = deployment.get("endpoints") or []
1047
1074
  want_coldstart = any(
1048
1075
  ((e.get("autoscaling") or {}).get("min_replicas") or 0) > 0
@@ -1386,6 +1413,122 @@ def app_scale(
1386
1413
  client.close()
1387
1414
 
1388
1415
 
1416
+ # --------------------------------------------------------------------------
1417
+ # metrics declare
1418
+ # --------------------------------------------------------------------------
1419
+
1420
+
1421
+ def _put_exported_metrics(app_name_or_id: str, endpoint: str, metrics: list[dict]) -> dict:
1422
+ """PUT one endpoint's exported_metrics; print the server's warnings."""
1423
+ from rich.markup import escape
1424
+
1425
+ from ._exported_metrics import warning_messages
1426
+ from ._render import err_console
1427
+ from . import exceptions as exc
1428
+
1429
+ client, _ = _make_client()
1430
+ try:
1431
+ app_id = _resolve_app_id(client, app_name_or_id)
1432
+ resp = client.set_exported_metrics(app_id, endpoint, metrics)
1433
+ except exc.FabricError as e:
1434
+ raise _handle_fabric_error(e)
1435
+ finally:
1436
+ client.close()
1437
+ for message in warning_messages(resp):
1438
+ err_console.print(f"[yellow]warning[/yellow]: {escape(message)}")
1439
+ return resp
1440
+
1441
+
1442
+ @metrics_declare_app.command("set")
1443
+ def metrics_declare_set(
1444
+ app_name_or_id: str = typer.Argument(..., help="App name or app_ id."),
1445
+ endpoint: str = typer.Argument(..., help="Endpoint name."),
1446
+ specs: list[str] = typer.Argument(
1447
+ ..., metavar="NAME:TYPE[:LABEL][@UNIT]...",
1448
+ help="Full list of metrics to export, e.g. request_seconds:histogram:route@s "
1449
+ "tokens_generated_total:counter@{token}.",
1450
+ ),
1451
+ ):
1452
+ """Replace an endpoint's exported metrics live (no redeploy).
1453
+
1454
+ The list replaces the current one entirely and lasts until the next deploy.
1455
+ """
1456
+ from rich.markup import escape
1457
+
1458
+ from ._exported_metrics import parse_metric_arg
1459
+ from ._render import console, exported_metrics_table
1460
+ from . import exceptions as exc
1461
+
1462
+ try:
1463
+ metrics = [parse_metric_arg(s).to_spec() for s in specs]
1464
+ except (ValueError, exc.InvalidArgumentError) as e:
1465
+ console.print(f"[red]Invalid metric:[/red] {escape(str(e))}")
1466
+ raise typer.Exit(2)
1467
+ resp = _put_exported_metrics(app_name_or_id, endpoint, metrics)
1468
+ console.print(exported_metrics_table({
1469
+ "name": endpoint,
1470
+ "exported_metrics": resp.get("exported_metrics") or [],
1471
+ "exported_metrics_source": "live",
1472
+ "exported_metrics_rollout": resp.get("rollout"),
1473
+ }))
1474
+
1475
+
1476
+ @metrics_declare_app.command("clear")
1477
+ def metrics_declare_clear(
1478
+ app_name_or_id: str = typer.Argument(..., help="App name or app_ id."),
1479
+ endpoint: str = typer.Argument(..., help="Endpoint name."),
1480
+ ):
1481
+ """Stop exporting any app metric from an endpoint (until the next deploy)."""
1482
+ from ._render import console
1483
+
1484
+ _put_exported_metrics(app_name_or_id, endpoint, [])
1485
+ console.print(f"[green]cleared[/green] exported metrics on {endpoint}")
1486
+
1487
+
1488
+ @metrics_declare_app.command("show")
1489
+ def metrics_declare_show(
1490
+ app_name_or_id: str = typer.Argument(..., help="App name or app_ id."),
1491
+ endpoint: Optional[str] = typer.Argument(
1492
+ None, help="Endpoint name. Defaults to every endpoint."
1493
+ ),
1494
+ as_json: bool = typer.Option(False, "--json", help="Print JSON."),
1495
+ ):
1496
+ """Show the declared exported metrics, their source and rollout state."""
1497
+ from rich.markup import escape
1498
+
1499
+ from ._render import console, exported_metrics_table
1500
+ from . import exceptions as exc
1501
+
1502
+ client, _ = _make_client()
1503
+ try:
1504
+ app_id = _resolve_app_id(client, app_name_or_id)
1505
+ app_obj = client.get_app(app_id)
1506
+ except exc.FabricError as e:
1507
+ raise _handle_fabric_error(e)
1508
+ finally:
1509
+ client.close()
1510
+ endpoints = (app_obj.get("active_deployment") or {}).get("endpoints") or []
1511
+ if not endpoints:
1512
+ console.print("[red]No active deployment / endpoints.[/red]")
1513
+ raise typer.Exit(1)
1514
+ if endpoint is not None:
1515
+ endpoints = [ep for ep in endpoints if ep.get("name") == endpoint]
1516
+ if not endpoints:
1517
+ console.print(f"[red]No endpoint named[/red] {escape(endpoint)}")
1518
+ raise typer.Exit(1)
1519
+ if as_json:
1520
+ keys = (
1521
+ "name", "exported_metrics", "exported_metrics_source", "exported_metrics_rollout"
1522
+ )
1523
+ typer.echo(json.dumps({
1524
+ "app_id": app_id,
1525
+ "endpoints": [{k: ep.get(k) for k in keys} for ep in endpoints],
1526
+ }, indent=2))
1527
+ return
1528
+ for ep in endpoints:
1529
+ console.print(exported_metrics_table(ep))
1530
+
1531
+
1389
1532
  # --------------------------------------------------------------------------
1390
1533
  # volume
1391
1534
  # --------------------------------------------------------------------------
File without changes
File without changes