maproom 0.2.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 (199) hide show
  1. maproom/__init__.py +14 -0
  2. maproom/__main__.py +10 -0
  3. maproom/analyze/__init__.py +1 -0
  4. maproom/analyze/accel_families.py +45 -0
  5. maproom/analyze/account_azure_activity.py +260 -0
  6. maproom/analyze/account_azure_quota_requests.py +177 -0
  7. maproom/analyze/account_cloudtrail.py +316 -0
  8. maproom/analyze/account_quota_requests.py +180 -0
  9. maproom/analyze/analyze_v1_orchestration.py +1194 -0
  10. maproom/analyze/catalog.py +353 -0
  11. maproom/analyze/change_detection.py +652 -0
  12. maproom/analyze/context_client.py +99 -0
  13. maproom/analyze/context_lookup.py +142 -0
  14. maproom/analyze/cover_analyze.py +344 -0
  15. maproom/analyze/cover_client.py +65 -0
  16. maproom/analyze/cover_lookup.py +242 -0
  17. maproom/analyze/engine.py +644 -0
  18. maproom/analyze/fleetfit_endpoints.py +217 -0
  19. maproom/analyze/fleetfit_policy.py +66 -0
  20. maproom/analyze/instance_price_analyze.py +221 -0
  21. maproom/analyze/instance_price_client.py +108 -0
  22. maproom/analyze/instance_price_lookup.py +60 -0
  23. maproom/analyze/local_reads.py +484 -0
  24. maproom/analyze/lookup_http.py +280 -0
  25. maproom/analyze/metric_format.py +20 -0
  26. maproom/analyze/migration_method.py +130 -0
  27. maproom/analyze/move_list.py +93 -0
  28. maproom/analyze/operator_context.py +156 -0
  29. maproom/analyze/performance_rank.py +97 -0
  30. maproom/analyze/primary_recommendation.py +422 -0
  31. maproom/analyze/provider_comparison.py +401 -0
  32. maproom/analyze/quota_analyze.py +481 -0
  33. maproom/analyze/quota_client.py +75 -0
  34. maproom/analyze/quota_lookup.py +110 -0
  35. maproom/analyze/quota_outcome_steer.py +105 -0
  36. maproom/analyze/recommend_batch.py +199 -0
  37. maproom/analyze/recommend_client.py +362 -0
  38. maproom/analyze/recommend_share.py +118 -0
  39. maproom/analyze/recommendation.py +591 -0
  40. maproom/analyze/reservation_pack.py +883 -0
  41. maproom/analyze/reservation_read.py +461 -0
  42. maproom/analyze/safe_analyze.py +1134 -0
  43. maproom/analyze/safe_move.py +195 -0
  44. maproom/analyze/safe_moves.py +571 -0
  45. maproom/analyze/safe_moves_catalog.py +127 -0
  46. maproom/analyze/safe_moves_client.py +70 -0
  47. maproom/analyze/series_analyze.py +491 -0
  48. maproom/analyze/series_client.py +106 -0
  49. maproom/analyze/series_lookup.py +663 -0
  50. maproom/analyze/shape.py +254 -0
  51. maproom/analyze/size_analyze.py +883 -0
  52. maproom/analyze/size_client.py +81 -0
  53. maproom/analyze/size_keep.py +409 -0
  54. maproom/analyze/size_lookup.py +368 -0
  55. maproom/analyze/specs.py +325 -0
  56. maproom/analyze/spot_analyze.py +392 -0
  57. maproom/analyze/spot_client.py +74 -0
  58. maproom/analyze/spot_lookup.py +213 -0
  59. maproom/analyze/token_client.py +97 -0
  60. maproom/analyze/utilization.py +190 -0
  61. maproom/analyze/workload.py +104 -0
  62. maproom/analyze/workset.py +762 -0
  63. maproom/aws_region.py +78 -0
  64. maproom/cache/__init__.py +1 -0
  65. maproom/cache/catalog.py +372 -0
  66. maproom/cache/commands.py +215 -0
  67. maproom/cache/instances.py +460 -0
  68. maproom/cli.py +2084 -0
  69. maproom/cli_argv.py +329 -0
  70. maproom/cli_floors.py +89 -0
  71. maproom/cliio/__init__.py +1 -0
  72. maproom/cliio/registry.py +377 -0
  73. maproom/cliio/runner.py +489 -0
  74. maproom/consent/__init__.py +33 -0
  75. maproom/consent/gate.py +238 -0
  76. maproom/consent/policy.py +20 -0
  77. maproom/consent/prompt.py +61 -0
  78. maproom/consent/service_upload_gate.py +318 -0
  79. maproom/consent/service_upload_prompt.py +62 -0
  80. maproom/consent/stdin.py +45 -0
  81. maproom/consent/storage.py +24 -0
  82. maproom/consent/write_token.py +29 -0
  83. maproom/contracts/__init__.py +6 -0
  84. maproom/contracts/schema_diff.py +119 -0
  85. maproom/contracts/validate.py +113 -0
  86. maproom/data/__init__.py +1 -0
  87. maproom/data/clear.py +76 -0
  88. maproom/data/commands.py +14 -0
  89. maproom/doctor/__init__.py +1 -0
  90. maproom/doctor/aws_session.py +226 -0
  91. maproom/doctor/checks.py +701 -0
  92. maproom/doctor/context.py +32 -0
  93. maproom/doctor/display.py +96 -0
  94. maproom/doctor/inventory_display.py +377 -0
  95. maproom/doctor/runner.py +1467 -0
  96. maproom/errors.py +43 -0
  97. maproom/exitcodes.py +70 -0
  98. maproom/inventory/__init__.py +1 -0
  99. maproom/inventory/account_identity.py +79 -0
  100. maproom/inventory/accounts.py +155 -0
  101. maproom/inventory/command.py +961 -0
  102. maproom/inventory/messages.py +264 -0
  103. maproom/inventory/reservations_refresh.py +37 -0
  104. maproom/mock_environment/__init__.py +28 -0
  105. maproom/mock_environment/load.py +241 -0
  106. maproom/mock_environment/runner.py +387 -0
  107. maproom/output/__init__.py +1 -0
  108. maproom/output/json_envelope.py +241 -0
  109. maproom/output/redact.py +11 -0
  110. maproom/output/terminal.py +129 -0
  111. maproom/parsers.py +284 -0
  112. maproom/paths.py +105 -0
  113. maproom/plan/__init__.py +1 -0
  114. maproom/plan/accept.py +59 -0
  115. maproom/plan/analysis_context.py +78 -0
  116. maproom/plan/analyze_selection.py +279 -0
  117. maproom/plan/commands.py +586 -0
  118. maproom/plan/current.py +59 -0
  119. maproom/plan/errors.py +10 -0
  120. maproom/plan/export.py +36 -0
  121. maproom/plan/formatting.py +91 -0
  122. maproom/plan/ids.py +13 -0
  123. maproom/plan/migration_options.py +75 -0
  124. maproom/plan/model.py +265 -0
  125. maproom/plan/names.py +24 -0
  126. maproom/plan/store.py +193 -0
  127. maproom/plan/tty.py +34 -0
  128. maproom/pricing/__init__.py +5 -0
  129. maproom/pricing/prices.py +119 -0
  130. maproom/privacy/__init__.py +6 -0
  131. maproom/privacy/commands.py +159 -0
  132. maproom/privacy/delete_uploads.py +204 -0
  133. maproom/privacy/fleetfit_policy.py +125 -0
  134. maproom/privacy/fleetfit_statement.py +104 -0
  135. maproom/privacy/format.py +76 -0
  136. maproom/privacy/manifests.py +342 -0
  137. maproom/privacy/statement.py +58 -0
  138. maproom/quotas/__init__.py +21 -0
  139. maproom/quotas/aws.py +204 -0
  140. maproom/quotas/azure.py +75 -0
  141. maproom/quotas/commands.py +240 -0
  142. maproom/quotas/family_coverage.py +122 -0
  143. maproom/quotas/fetch.py +124 -0
  144. maproom/quotas/load.py +41 -0
  145. maproom/quotas/model.py +178 -0
  146. maproom/quotas/outcome_ledger.py +245 -0
  147. maproom/quotas/quota_request_sync.py +221 -0
  148. maproom/quotas/show.py +73 -0
  149. maproom/quotas/status.py +206 -0
  150. maproom/quotas/store.py +161 -0
  151. maproom/redaction.py +157 -0
  152. maproom/reference_data/__init__.py +1 -0
  153. maproom/reference_data/aws/aws_prices.csv +25562 -0
  154. maproom/reference_data/aws/capabilities.csv +1346 -0
  155. maproom/reference_data/aws/instance_types.csv +1346 -0
  156. maproom/reference_data/azure/azure_prices.csv +1 -0
  157. maproom/reference_data/azure/vm_types.csv +1 -0
  158. maproom/reference_data/benchmarks/cpu-lscpu-v2-instances.json +27 -0
  159. maproom/reference_data/benchmarks/safe-moves-v1.json +328 -0
  160. maproom/reference_data/manifest.json +174 -0
  161. maproom/reference_data/manifest.py +69 -0
  162. maproom/reservations/__init__.py +17 -0
  163. maproom/reservations/aws.py +76 -0
  164. maproom/reservations/azure.py +36 -0
  165. maproom/reservations/commands.py +149 -0
  166. maproom/reservations/load.py +41 -0
  167. maproom/reservations/model.py +316 -0
  168. maproom/reservations/show.py +64 -0
  169. maproom/reservations/status.py +181 -0
  170. maproom/reservations/store.py +391 -0
  171. maproom/resources.py +54 -0
  172. maproom/root_help.py +251 -0
  173. maproom/saving_plans/__init__.py +15 -0
  174. maproom/saving_plans/aws.py +73 -0
  175. maproom/saving_plans/commands.py +122 -0
  176. maproom/saving_plans/load.py +41 -0
  177. maproom/saving_plans/model.py +101 -0
  178. maproom/saving_plans/show.py +64 -0
  179. maproom/saving_plans/status.py +118 -0
  180. maproom/saving_plans/store.py +173 -0
  181. maproom/secret_egress_gate.py +108 -0
  182. maproom/service/install_id.py +60 -0
  183. maproom/settings/__init__.py +1 -0
  184. maproom/settings/defaults.py +73 -0
  185. maproom/settings/init.py +143 -0
  186. maproom/settings/model.py +105 -0
  187. maproom/settings/product_version_change.py +343 -0
  188. maproom/settings/product_versions.py +68 -0
  189. maproom/settings/set.py +347 -0
  190. maproom/settings/show.py +227 -0
  191. maproom/settings/write.py +273 -0
  192. maproom/snapshot_time.py +27 -0
  193. maproom-0.2.0.dist-info/METADATA +263 -0
  194. maproom-0.2.0.dist-info/RECORD +199 -0
  195. maproom-0.2.0.dist-info/WHEEL +5 -0
  196. maproom-0.2.0.dist-info/entry_points.txt +2 -0
  197. maproom-0.2.0.dist-info/licenses/LICENSE +201 -0
  198. maproom-0.2.0.dist-info/licenses/NOTICE +72 -0
  199. maproom-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,15 @@
1
+ """Savings Plan inventory get, load, and read-side status."""
2
+
3
+ from maproom.saving_plans.status import (
4
+ SavingPlanState,
5
+ read_saving_plan_state,
6
+ saving_plans_tty_segment,
7
+ stale_saving_plan_warning,
8
+ )
9
+
10
+ __all__ = [
11
+ "SavingPlanState",
12
+ "read_saving_plan_state",
13
+ "saving_plans_tty_segment",
14
+ "stale_saving_plan_warning",
15
+ ]
@@ -0,0 +1,73 @@
1
+ """AWS Savings Plan inventory collection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any
7
+
8
+ from maproom.saving_plans.model import SavingPlanError, normalize_records_from_aws
9
+
10
+
11
+ def _parse_runner_json(result: Any, operation: str) -> dict[str, Any]:
12
+ if result.exit_code != 0:
13
+ detail = (result.stderr or "").strip() or f"exit code {result.exit_code}"
14
+ raise SavingPlanError(f"{operation} failed: {detail}")
15
+ if not result.stdout.strip():
16
+ raise SavingPlanError(f"{operation} returned empty output")
17
+ try:
18
+ data = json.loads(result.stdout)
19
+ except json.JSONDecodeError as exc:
20
+ raise SavingPlanError(f"{operation} returned invalid JSON: {exc}") from exc
21
+ if not isinstance(data, dict):
22
+ raise SavingPlanError(f"{operation} returned unexpected JSON shape")
23
+ return data
24
+
25
+
26
+ def _default_region(runner: Any) -> str:
27
+ result = runner.run(
28
+ "aws",
29
+ ["configure", "get", "region"],
30
+ record=False,
31
+ api_id="aws_configure_get_region",
32
+ )
33
+ if result.exit_code == 0 and result.stdout.strip():
34
+ return result.stdout.strip()
35
+ return "us-east-1"
36
+
37
+
38
+ def fetch_aws_savings_plans(
39
+ runner: Any,
40
+ *,
41
+ region: str | None = None,
42
+ ) -> tuple[list[dict[str, Any]], str]:
43
+ """Every Savings Plan in the account, any state.
44
+
45
+ The API is account-wide. ``region`` selects the endpoint.
46
+ """
47
+ resolved_region = region or _default_region(runner)
48
+ result = runner.run(
49
+ "aws",
50
+ [
51
+ "savingsplans",
52
+ "describe-savings-plans",
53
+ "--region",
54
+ resolved_region,
55
+ "--output",
56
+ "json",
57
+ ],
58
+ record=False,
59
+ pagination="merge",
60
+ api_id="aws_savingsplans_describe_savings_plans",
61
+ )
62
+ data = _parse_runner_json(
63
+ result,
64
+ f"aws savingsplans describe-savings-plans ({resolved_region})",
65
+ )
66
+ raw = data.get("savingsPlans")
67
+ if raw is None:
68
+ plans: list[dict[str, Any]] = []
69
+ elif not isinstance(raw, list):
70
+ raise SavingPlanError("describe-savings-plans savingsPlans is not a list")
71
+ else:
72
+ plans = [item for item in raw if isinstance(item, dict)]
73
+ return normalize_records_from_aws(plans), resolved_region
@@ -0,0 +1,122 @@
1
+ """Fetch and save helpers used by maproom inventory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from maproom.cliio.runner import CliBelowFloorError
11
+
12
+ from maproom.cli_floors import ensure_cli_floors, fail_cli_floor
13
+ from maproom.consent import require_cloud_read_consent
14
+ from maproom.exitcodes import SUCCESS
15
+ from maproom.mock_environment import MockEnvironmentError, command_runner
16
+ from maproom.inventory.messages import (
17
+ saving_plans_fetch_progress_line,
18
+ saving_plans_get_human_lines,
19
+ saving_plans_get_summary_message,
20
+ )
21
+ from maproom.output.json_envelope import (
22
+ finish_consent_gate,
23
+ print_command_error as _print_error,
24
+ print_command_success as _print_success,
25
+ )
26
+ from maproom.saving_plans import aws, store
27
+ from maproom.saving_plans.load import load_payer_file
28
+ from maproom.saving_plans.model import SavingPlanError, build_snapshot
29
+
30
+
31
+ def cmd_saving_plans_get(args: argparse.Namespace) -> int:
32
+ as_json = bool(args.json)
33
+ invoked = "savings-plans get"
34
+ try:
35
+ runner = command_runner()
36
+ except MockEnvironmentError as exc:
37
+ return _print_error(exc.message, as_json=as_json, invoked=invoked)
38
+ try:
39
+ ensure_cli_floors(runner=runner)
40
+ except CliBelowFloorError as exc:
41
+ return fail_cli_floor(exc, as_json=as_json, invoked=invoked)
42
+
43
+ gate = require_cloud_read_consent(
44
+ consent_cloud_reads=bool(getattr(args, "consent_cloud_reads", False)),
45
+ quiet=as_json,
46
+ )
47
+ if not gate.allowed:
48
+ return finish_consent_gate(gate, as_json=as_json, invoked=invoked)
49
+
50
+ aws_region = getattr(args, "region", None) or None
51
+ if not as_json:
52
+ print(saving_plans_fetch_progress_line(), file=sys.stderr)
53
+
54
+ try:
55
+ records, region = aws.fetch_aws_savings_plans(runner, region=aws_region)
56
+ except SavingPlanError as exc:
57
+ return _print_error(exc.message, as_json=as_json, invoked=invoked)
58
+
59
+ snapshot = build_snapshot(records, source="aws_get", region=region)
60
+ err = store.write_snapshot(snapshot)
61
+ if err is not None:
62
+ return _print_error(err.message, as_json=as_json, invoked=invoked)
63
+
64
+ path = store.inventory_path()
65
+ record_count = int(snapshot["record_count"])
66
+ loaded_as_of = str(snapshot["loaded_as_of"])
67
+ if as_json:
68
+ _print_success(
69
+ "saving_plans_get",
70
+ "maproom.saving_plans_get",
71
+ invoked,
72
+ {
73
+ "snapshot_path": str(path),
74
+ "loaded_as_of": loaded_as_of,
75
+ "record_count": record_count,
76
+ "source": snapshot["source"],
77
+ "message": saving_plans_get_summary_message(record_count),
78
+ },
79
+ )
80
+ else:
81
+ for line in saving_plans_get_human_lines(
82
+ record_count=record_count,
83
+ path=str(path),
84
+ loaded_as_of=loaded_as_of,
85
+ ):
86
+ print(line)
87
+ return SUCCESS
88
+
89
+
90
+ def cmd_saving_plans_load(args: argparse.Namespace) -> int:
91
+ as_json = bool(args.json)
92
+ invoked = "savings-plans load"
93
+ payer_path = Path(args.path)
94
+ try:
95
+ records = load_payer_file(payer_path)
96
+ except SavingPlanError as exc:
97
+ return _print_error(exc.message, as_json=as_json, invoked=invoked)
98
+
99
+ snapshot = build_snapshot(records, source="payer_file")
100
+ err = store.write_snapshot(snapshot)
101
+ if err is not None:
102
+ return _print_error(err.message, as_json=as_json, invoked=invoked)
103
+
104
+ path = store.inventory_path()
105
+ if as_json:
106
+ _print_success(
107
+ "saving_plans_load",
108
+ "maproom.saving_plans_load",
109
+ invoked,
110
+ {
111
+ "snapshot_path": str(path),
112
+ "loaded_as_of": snapshot["loaded_as_of"],
113
+ "record_count": snapshot["record_count"],
114
+ "source": snapshot["source"],
115
+ },
116
+ )
117
+ else:
118
+ print(
119
+ f"Saved {snapshot['record_count']} savings plan record(s) to {path} "
120
+ f"(loaded as of {snapshot['loaded_as_of']})"
121
+ )
122
+ return SUCCESS
@@ -0,0 +1,41 @@
1
+ """Payer-file Savings Plan inventory load."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from maproom.saving_plans.model import SavingPlanError, normalize_records_from_payload
10
+
11
+
12
+ def _file_loaded_as_of(data: dict[str, Any]) -> str | None:
13
+ raw = data.get("loaded_as_of")
14
+ if isinstance(raw, str) and raw.strip():
15
+ return raw.strip()
16
+ return None
17
+
18
+
19
+ def load_payer_file_with_timestamp(path: Path) -> tuple[list[dict[str, Any]], str | None]:
20
+ if not path.exists():
21
+ raise SavingPlanError(f"file not found: {path}")
22
+ if path.is_dir():
23
+ raise SavingPlanError(f"path is a directory: {path}")
24
+ try:
25
+ text = path.read_text(encoding="utf-8")
26
+ except OSError as exc:
27
+ raise SavingPlanError(f"could not read {path}: {exc}") from exc
28
+ if not text.strip():
29
+ raise SavingPlanError(f"file is empty: {path}")
30
+ try:
31
+ data = json.loads(text)
32
+ except json.JSONDecodeError as exc:
33
+ raise SavingPlanError(f"invalid JSON in {path}: {exc}") from exc
34
+ if not isinstance(data, dict):
35
+ raise SavingPlanError(f"expected JSON object in {path}")
36
+ return normalize_records_from_payload(data), _file_loaded_as_of(data)
37
+
38
+
39
+ def load_payer_file(path: Path) -> list[dict[str, Any]]:
40
+ records, _ = load_payer_file_with_timestamp(path)
41
+ return records
@@ -0,0 +1,101 @@
1
+ """Savings Plan snapshot schema and normalization."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime, timezone
6
+ from typing import Any
7
+
8
+ SCHEMA_VERSION = 1
9
+
10
+
11
+ class SavingPlanError(Exception):
12
+ """Validation or normalization failure."""
13
+
14
+ def __init__(self, message: str) -> None:
15
+ self.message = message
16
+ super().__init__(message)
17
+
18
+
19
+ def utc_now_iso() -> str:
20
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
21
+
22
+
23
+ def normalize_savings_plan(item: dict[str, Any]) -> dict[str, Any]:
24
+ region = str(item.get("region") or item.get("Region") or "global")
25
+ plan_type = str(item.get("savingsPlanType") or item.get("SavingsPlanType") or "unknown")
26
+ state = str(item.get("state") or item.get("State") or "unknown").lower()
27
+ return {
28
+ "kind": "savings_plan",
29
+ "region": region,
30
+ "plan_type": plan_type,
31
+ "state": state,
32
+ "payment_option": str(item.get("paymentOption") or item.get("PaymentOption") or ""),
33
+ "commitment": str(item.get("commitment") or item.get("Commitment") or ""),
34
+ "start": str(item.get("start") or item.get("Start") or ""),
35
+ "end": str(item.get("end") or item.get("End") or ""),
36
+ }
37
+
38
+
39
+ def normalize_records_from_aws(
40
+ savings_plans: list[dict[str, Any]] | None,
41
+ ) -> list[dict[str, Any]]:
42
+ records: list[dict[str, Any]] = []
43
+ for item in savings_plans or []:
44
+ if isinstance(item, dict):
45
+ records.append(normalize_savings_plan(item))
46
+ return records
47
+
48
+
49
+ def _normalize_sp_record_from_snapshot(item: dict[str, Any]) -> dict[str, Any]:
50
+ return {
51
+ "kind": "savings_plan",
52
+ "region": str(item.get("region") or "global"),
53
+ "plan_type": str(item.get("plan_type") or "unknown"),
54
+ "state": str(item.get("state") or "unknown").lower(),
55
+ "payment_option": str(item.get("payment_option") or ""),
56
+ "commitment": str(item.get("commitment") or ""),
57
+ "start": str(item.get("start") or ""),
58
+ "end": str(item.get("end") or ""),
59
+ }
60
+
61
+
62
+ def normalize_records_from_payload(data: dict[str, Any]) -> list[dict[str, Any]]:
63
+ if "records" in data and isinstance(data["records"], list):
64
+ records: list[dict[str, Any]] = []
65
+ for item in data["records"]:
66
+ if not isinstance(item, dict):
67
+ raise SavingPlanError("invalid record entry in snapshot")
68
+ kind = item.get("kind")
69
+ if kind == "savings_plan":
70
+ records.append(_normalize_sp_record_from_snapshot(item))
71
+ elif kind == "ec2_reserved_instance":
72
+ continue
73
+ else:
74
+ raise SavingPlanError(f"unsupported record kind: {kind}")
75
+ return records
76
+ if "savingsPlans" in data:
77
+ plans = data.get("savingsPlans")
78
+ if plans is not None and not isinstance(plans, list):
79
+ raise SavingPlanError("savingsPlans is not a list")
80
+ return normalize_records_from_aws(plans if isinstance(plans, list) else None)
81
+ raise SavingPlanError("unrecognized payer file shape")
82
+
83
+
84
+ def build_snapshot(
85
+ records: list[dict[str, Any]],
86
+ *,
87
+ source: str,
88
+ loaded_as_of: str | None = None,
89
+ region: str | None = None,
90
+ ) -> dict[str, Any]:
91
+ ts = loaded_as_of or utc_now_iso()
92
+ payload: dict[str, Any] = {
93
+ "schema_version": SCHEMA_VERSION,
94
+ "loaded_as_of": ts,
95
+ "source": source,
96
+ "record_count": len(records),
97
+ "records": records,
98
+ }
99
+ if region:
100
+ payload["region"] = region
101
+ return payload
@@ -0,0 +1,64 @@
1
+ """Savings-plan snapshot summary. The operator command is maproom inventory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from maproom.doctor.inventory_display import (
6
+ SAVING_PLANS_GET_HINT,
7
+ saving_plan_inventory_detail_lines,
8
+ saving_plan_record_lines,
9
+ )
10
+ from maproom.exitcodes import RUNTIME, SUCCESS
11
+ from maproom.output.json_envelope import build_document, command_metadata, error_item, print_json
12
+ from maproom.saving_plans.status import doctor_saving_plans_message, read_saving_plan_state
13
+
14
+
15
+ def run_saving_plans_show(*, as_json: bool = False) -> int:
16
+ state = read_saving_plan_state()
17
+ if state.parse_error:
18
+ message = doctor_saving_plans_message(state)
19
+ if as_json:
20
+ print_json(
21
+ build_document(
22
+ schema_type="saving_plans",
23
+ schema_id="maproom.saving_plans",
24
+ metadata=command_metadata("savings-plans"),
25
+ errors=[error_item("runtime", message)],
26
+ warnings=[],
27
+ payload={
28
+ "snapshot_path": str(state.snapshot_path),
29
+ "exists": state.exists,
30
+ "loaded_as_of": state.loaded_as_of,
31
+ "record_count": state.record_count,
32
+ "is_stale": state.is_stale,
33
+ "records": [],
34
+ },
35
+ )
36
+ )
37
+ return RUNTIME
38
+ print(message)
39
+ return RUNTIME
40
+ if as_json:
41
+ print_json(
42
+ build_document(
43
+ schema_type="saving_plans",
44
+ schema_id="maproom.saving_plans",
45
+ metadata=command_metadata("savings-plans"),
46
+ payload={
47
+ "snapshot_path": str(state.snapshot_path),
48
+ "exists": state.exists,
49
+ "loaded_as_of": state.loaded_as_of,
50
+ "record_count": state.record_count,
51
+ "is_stale": state.is_stale,
52
+ "records": list(state.records),
53
+ },
54
+ )
55
+ )
56
+ return SUCCESS
57
+
58
+ for line in saving_plan_inventory_detail_lines(state):
59
+ print(line)
60
+ for line in saving_plan_record_lines(state):
61
+ print(line)
62
+ print()
63
+ print(SAVING_PLANS_GET_HINT)
64
+ return SUCCESS
@@ -0,0 +1,118 @@
1
+ """Savings Plan inventory read-side status and TTY helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from datetime import datetime
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from maproom.paths import settings_read_file
11
+ from maproom.saving_plans import store
12
+ from maproom.saving_plans.model import SavingPlanError
13
+ from maproom.settings.model import cache_max_age_hours, snapshot_is_stale
14
+ from maproom.snapshot_time import as_of_date_label
15
+
16
+ SAVING_PLANS_INVENTORY_REMEDIATION = "Refresh with: maproom inventory get"
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class SavingPlanState:
21
+ snapshot_path: Path
22
+ exists: bool
23
+ loaded_as_of: str | None
24
+ record_count: int
25
+ is_stale: bool
26
+ cache_max_age_hours: int
27
+ parse_error: str | None = None
28
+ source: str | None = None
29
+ records: tuple[dict[str, Any], ...] = ()
30
+ region: str | None = None
31
+
32
+
33
+ def read_saving_plan_state(
34
+ settings_path: Path | None = None,
35
+ *,
36
+ now_utc: datetime | None = None,
37
+ ) -> SavingPlanState:
38
+ path = store.inventory_path()
39
+ settings_file_path = settings_path or settings_read_file()
40
+ max_age = cache_max_age_hours(settings_file_path)
41
+
42
+ data = store.read_snapshot()
43
+ if isinstance(data, SavingPlanError):
44
+ return SavingPlanState(
45
+ snapshot_path=path,
46
+ exists=True,
47
+ loaded_as_of=None,
48
+ record_count=0,
49
+ is_stale=False,
50
+ cache_max_age_hours=max_age,
51
+ parse_error=data.message,
52
+ )
53
+ if data is None:
54
+ return SavingPlanState(
55
+ snapshot_path=path,
56
+ exists=False,
57
+ loaded_as_of=None,
58
+ record_count=0,
59
+ is_stale=False,
60
+ cache_max_age_hours=max_age,
61
+ )
62
+
63
+ loaded_as_of = str(data.get("loaded_as_of") or "")
64
+ records_raw = data.get("records") or []
65
+ records = tuple(r for r in records_raw if isinstance(r, dict))
66
+ record_count = int(
67
+ data.get("record_count")
68
+ if data.get("record_count") is not None
69
+ else len(records)
70
+ )
71
+ source = str(data.get("source") or "") or None
72
+ region = str(data.get("region") or "") or None
73
+ stale = snapshot_is_stale(loaded_as_of, max_age, now=now_utc)
74
+ return SavingPlanState(
75
+ snapshot_path=path,
76
+ exists=True,
77
+ loaded_as_of=loaded_as_of or None,
78
+ record_count=record_count,
79
+ is_stale=stale,
80
+ cache_max_age_hours=max_age,
81
+ source=source,
82
+ records=records,
83
+ region=region,
84
+ )
85
+
86
+
87
+ def saving_plans_tty_segment(state: SavingPlanState) -> str:
88
+ if not state.exists or state.parse_error:
89
+ return "savings-plans: none loaded (on-demand pricing)"
90
+ as_of = as_of_date_label(state.loaded_as_of)
91
+ if state.is_stale:
92
+ return f"savings-plans: loaded (stale) (as of {as_of})"
93
+ if state.record_count == 0:
94
+ return f"savings-plans: none in snapshot (checked {as_of})"
95
+ return f"savings-plans: loaded (as of {as_of})"
96
+
97
+
98
+ def stale_saving_plan_warning(state: SavingPlanState) -> str | None:
99
+ if not state.exists or not state.is_stale or not state.loaded_as_of:
100
+ return None
101
+ as_of = as_of_date_label(state.loaded_as_of)
102
+ return (
103
+ f"Savings Plan inventory is stale (loaded {as_of}; reuse limit "
104
+ f"{state.cache_max_age_hours} hours). Re-run 'maproom inventory get'."
105
+ )
106
+
107
+
108
+ def doctor_saving_plans_message(state: SavingPlanState) -> str:
109
+ path = str(state.snapshot_path)
110
+ if state.parse_error:
111
+ return f"{path}; could not read snapshot: {state.parse_error}"
112
+ if not state.exists:
113
+ return f"No Savings Plans snapshot file yet. Path: {path}"
114
+ parts = [path, f"loaded_as_of={state.loaded_as_of}"]
115
+ warning = stale_saving_plan_warning(state)
116
+ if warning:
117
+ parts.append(warning)
118
+ return "; ".join(parts)