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,316 @@
1
+ """Reservation 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 ReservationError(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 _region_from_az(az: str | None) -> str:
24
+ if not az:
25
+ return "unknown"
26
+ text = str(az).strip()
27
+ if len(text) >= 2 and text[-1].isalpha():
28
+ return text[:-1]
29
+ return text or "unknown"
30
+
31
+
32
+ def _instance_family(instance_type: str) -> str:
33
+ text = str(instance_type or "").strip()
34
+ if "." in text:
35
+ return text.split(".", 1)[0]
36
+ return text or "unknown"
37
+
38
+
39
+ def normalize_ec2_reserved_instance(
40
+ item: dict[str, Any],
41
+ *,
42
+ region: str | None = None,
43
+ ) -> dict[str, Any]:
44
+ from_az = _region_from_az(item.get("AvailabilityZone"))
45
+ if from_az == "unknown" and region:
46
+ resolved_region = region
47
+ else:
48
+ resolved_region = from_az
49
+ instance_type = str(item.get("InstanceType") or "unknown")
50
+ subscription_id = str(item.get("ReservedInstancesId") or "")
51
+ name = ""
52
+ for tag in item.get("Tags") or []:
53
+ if isinstance(tag, dict) and str(tag.get("Key") or "") == "Name":
54
+ name = str(tag.get("Value") or "").strip()
55
+ break
56
+ return {
57
+ "kind": "ec2_reserved_instance",
58
+ "region": resolved_region,
59
+ "instance_type": instance_type,
60
+ "subscription_id": subscription_id,
61
+ "name": name or subscription_id or instance_type,
62
+ "instance_family": _instance_family(instance_type),
63
+ "state": str(item.get("State") or "unknown").lower(),
64
+ "quantity": int(item.get("InstanceCount") or 1),
65
+ "offering_class": str(item.get("OfferingClass") or item.get("offering_class") or ""),
66
+ "scope": str(item.get("Scope") or item.get("scope") or ""),
67
+ "tenancy": str(item.get("InstanceTenancy") or item.get("tenancy") or ""),
68
+ "platform": str(item.get("ProductDescription") or item.get("platform") or ""),
69
+ "end": str(item.get("End") or item.get("end") or ""),
70
+ }
71
+
72
+
73
+ def azure_flexibility_group(instance_type: str) -> str:
74
+ name = str(instance_type or "").strip()
75
+ if name.lower().startswith("standard_"):
76
+ name = name[9:]
77
+ index = 0
78
+ prefix: list[str] = []
79
+ while index < len(name) and name[index].isalpha():
80
+ prefix.append(name[index])
81
+ index += 1
82
+ while index < len(name) and name[index].isdigit():
83
+ index += 1
84
+ group = "".join(prefix) + name[index:]
85
+ return group or str(instance_type or "unknown")
86
+
87
+
88
+ def normalize_azure_reserved_vm(item: dict[str, Any]) -> dict[str, Any] | None:
89
+ properties = item.get("properties") if isinstance(item.get("properties"), dict) else {}
90
+ resource = str(properties.get("reservedResourceType") or item.get("reservedResourceType") or "")
91
+ if resource and resource != "VirtualMachines":
92
+ return None
93
+ sku = item.get("sku") if isinstance(item.get("sku"), dict) else {}
94
+ instance_type = str(sku.get("name") or item.get("instance_type") or "").strip()
95
+ if not instance_type:
96
+ return None
97
+ region = str(item.get("location") or properties.get("location") or item.get("region") or "").strip().lower()
98
+ scope = str(properties.get("appliedScopeType") or item.get("appliedScopeType") or "Shared")
99
+ flexibility = str(properties.get("instanceFlexibility") or item.get("instanceFlexibility") or "")
100
+ if flexibility:
101
+ size_flexible = flexibility.strip().lower() == "on" and scope.strip().lower() != "single"
102
+ elif "size_flexible" in item:
103
+ size_flexible = bool(item.get("size_flexible"))
104
+ else:
105
+ size_flexible = scope.strip().lower() != "single"
106
+ try:
107
+ quantity = int(properties.get("quantity") or item.get("quantity") or 1)
108
+ except (TypeError, ValueError):
109
+ quantity = 1
110
+ display = str(item.get("name") or properties.get("displayName") or instance_type)
111
+ return {
112
+ "kind": "azure_reserved_vm",
113
+ "region": region or "unknown",
114
+ "instance_type": instance_type,
115
+ "subscription_id": str(item.get("id") or item.get("name") or ""),
116
+ "name": display,
117
+ "instance_family": azure_flexibility_group(instance_type),
118
+ "state": str(properties.get("provisioningState") or "succeeded").lower(),
119
+ "quantity": quantity,
120
+ "offering_class": "",
121
+ "scope": scope,
122
+ "tenancy": "",
123
+ "platform": "*",
124
+ "size_flexible": size_flexible,
125
+ "end": str(properties.get("expiryDateTime") or ""),
126
+ }
127
+
128
+
129
+ def normalize_records_from_azure(items: list[dict[str, Any]] | None) -> list[dict[str, Any]]:
130
+ records: list[dict[str, Any]] = []
131
+ for item in items or []:
132
+ if not isinstance(item, dict):
133
+ continue
134
+ nested = item.get("reservations")
135
+ properties = item.get("properties") if isinstance(item.get("properties"), dict) else {}
136
+ if not isinstance(nested, list):
137
+ nested = properties.get("reservations")
138
+ if isinstance(nested, list) and nested:
139
+ records.extend(normalize_records_from_azure([row for row in nested if isinstance(row, dict)]))
140
+ continue
141
+ record = normalize_azure_reserved_vm(item)
142
+ if record is not None:
143
+ records.append(record)
144
+ return records
145
+
146
+
147
+ def normalize_records_from_aws(
148
+ reserved_instances: list[dict[str, Any]] | None,
149
+ *,
150
+ region: str | None = None,
151
+ ) -> list[dict[str, Any]]:
152
+ records: list[dict[str, Any]] = []
153
+ for item in reserved_instances or []:
154
+ if isinstance(item, dict):
155
+ records.append(normalize_ec2_reserved_instance(item, region=region))
156
+ return records
157
+
158
+
159
+ def _normalize_ec2_record_from_snapshot(item: dict[str, Any]) -> dict[str, Any]:
160
+ instance_type = str(item.get("instance_type") or "unknown")
161
+ subscription_id = str(item.get("subscription_id") or "").strip()
162
+ name = str(item.get("name") or "").strip()
163
+ row: dict[str, Any] = {
164
+ "kind": "ec2_reserved_instance",
165
+ "region": str(item.get("region") or "unknown"),
166
+ "instance_type": instance_type,
167
+ "instance_family": str(item.get("instance_family") or _instance_family(instance_type)),
168
+ "state": str(item.get("state") or "unknown").lower(),
169
+ "quantity": int(item.get("quantity") or 1),
170
+ "offering_class": str(item.get("offering_class") or ""),
171
+ "scope": str(item.get("scope") or ""),
172
+ "tenancy": str(item.get("tenancy") or ""),
173
+ "platform": str(item.get("platform") or ""),
174
+ "end": str(item.get("end") or ""),
175
+ }
176
+ if subscription_id:
177
+ row["subscription_id"] = subscription_id
178
+ if name:
179
+ row["name"] = name
180
+ account_id = str(item.get("account_id") or "").strip()
181
+ if account_id:
182
+ row["account_id"] = account_id
183
+ alias = str(item.get("account_alias") or "").strip()
184
+ if alias:
185
+ row["account_alias"] = alias
186
+ return row
187
+
188
+
189
+ def stamp_account_on_records(
190
+ records: list[dict[str, Any]],
191
+ *,
192
+ account_id: str,
193
+ account_alias: str | None = None,
194
+ ) -> list[dict[str, Any]]:
195
+ """Copy rows and set owning account fields used by the multi-account pool."""
196
+ stamped: list[dict[str, Any]] = []
197
+ for item in records:
198
+ if not isinstance(item, dict):
199
+ continue
200
+ row = dict(item)
201
+ row["account_id"] = account_id
202
+ if account_alias:
203
+ row["account_alias"] = account_alias
204
+ else:
205
+ row.pop("account_alias", None)
206
+ stamped.append(row)
207
+ return stamped
208
+
209
+
210
+ def dedupe_records_by_subscription_id(records: list[dict[str, Any]]) -> list[dict[str, Any]]:
211
+ """Keep one row per subscription_id; rows without an id are kept in order."""
212
+ seen: dict[str, int] = {}
213
+ out: list[dict[str, Any]] = []
214
+ for item in records:
215
+ if not isinstance(item, dict):
216
+ continue
217
+ sub = str(item.get("subscription_id") or "").strip()
218
+ if not sub:
219
+ out.append(item)
220
+ continue
221
+ prior = seen.get(sub)
222
+ if prior is None:
223
+ seen[sub] = len(out)
224
+ out.append(item)
225
+ continue
226
+ out[prior] = item
227
+ return out
228
+
229
+
230
+ def regions_from_records(records: list[dict[str, Any]]) -> list[str]:
231
+ found: set[str] = set()
232
+ for item in records:
233
+ if not isinstance(item, dict):
234
+ continue
235
+ region = str(item.get("region") or "").strip()
236
+ if region:
237
+ found.add(region)
238
+ return sorted(found)
239
+
240
+
241
+ def fetched_regions_from_payload(payload: dict[str, Any]) -> set[str]:
242
+ """Regions this write is refreshing (envelope region(s) or record regions)."""
243
+ regions: set[str] = set()
244
+ raw_list = payload.get("regions")
245
+ if isinstance(raw_list, list):
246
+ for item in raw_list:
247
+ text = str(item or "").strip()
248
+ if text:
249
+ regions.add(text)
250
+ single = str(payload.get("region") or "").strip()
251
+ if single:
252
+ regions.add(single)
253
+ if regions:
254
+ return regions
255
+ rows = payload.get("records")
256
+ if isinstance(rows, list):
257
+ return set(regions_from_records([r for r in rows if isinstance(r, dict)]))
258
+ return set()
259
+
260
+
261
+ def _reject_azure(item: dict[str, Any]) -> dict[str, Any]:
262
+ raise ReservationError(f"invalid azure reservation record: {item.get('instance_type') or 'unknown'}")
263
+
264
+
265
+ def normalize_records_from_payload(data: dict[str, Any]) -> list[dict[str, Any]]:
266
+ if "records" in data and isinstance(data["records"], list):
267
+ records: list[dict[str, Any]] = []
268
+ for item in data["records"]:
269
+ if not isinstance(item, dict):
270
+ raise ReservationError("invalid record entry in snapshot")
271
+ kind = item.get("kind")
272
+ if kind == "ec2_reserved_instance":
273
+ records.append(_normalize_ec2_record_from_snapshot(item))
274
+ elif kind == "azure_reserved_vm":
275
+ records.append(normalize_azure_reserved_vm(item) or _reject_azure(item))
276
+ elif kind == "savings_plan":
277
+ continue
278
+ else:
279
+ raise ReservationError(f"unsupported record kind: {kind}")
280
+ return records
281
+ if "ReservedInstances" in data:
282
+ reserved = data.get("ReservedInstances")
283
+ if reserved is not None and not isinstance(reserved, list):
284
+ raise ReservationError("ReservedInstances is not a list")
285
+ return normalize_records_from_aws(
286
+ reserved if isinstance(reserved, list) else None,
287
+ )
288
+ raise ReservationError("unrecognized payer file shape")
289
+
290
+
291
+ def build_snapshot(
292
+ records: list[dict[str, Any]],
293
+ *,
294
+ source: str,
295
+ loaded_as_of: str | None = None,
296
+ region: str | None = None,
297
+ regions: list[str] | None = None,
298
+ ) -> dict[str, Any]:
299
+ ts = loaded_as_of or utc_now_iso()
300
+ payload: dict[str, Any] = {
301
+ "schema_version": SCHEMA_VERSION,
302
+ "loaded_as_of": ts,
303
+ "source": source,
304
+ "record_count": len(records),
305
+ "records": records,
306
+ }
307
+ region_list = list(regions) if regions is not None else regions_from_records(records)
308
+ if region and region not in region_list:
309
+ region_list = sorted({*region_list, region})
310
+ if len(region_list) == 1:
311
+ payload["region"] = region_list[0]
312
+ elif len(region_list) > 1:
313
+ payload["regions"] = region_list
314
+ elif region:
315
+ payload["region"] = region
316
+ return payload
@@ -0,0 +1,64 @@
1
+ """Reservation snapshot summary. The operator command is maproom inventory."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from maproom.doctor.inventory_display import (
6
+ RESERVATIONS_GET_HINT,
7
+ reservation_inventory_detail_lines,
8
+ reservation_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.reservations.status import doctor_reservations_message, read_inventory_state
13
+
14
+
15
+ def run_reservations_show(*, as_json: bool = False) -> int:
16
+ state = read_inventory_state()
17
+ if state.parse_error:
18
+ message = doctor_reservations_message(state)
19
+ if as_json:
20
+ print_json(
21
+ build_document(
22
+ schema_type="reservations",
23
+ schema_id="maproom.reservations",
24
+ metadata=command_metadata("reservations"),
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="reservations",
44
+ schema_id="maproom.reservations",
45
+ metadata=command_metadata("reservations"),
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 reservation_inventory_detail_lines(state):
59
+ print(line)
60
+ for line in reservation_record_lines(state):
61
+ print(line)
62
+ print()
63
+ print(RESERVATIONS_GET_HINT)
64
+ return SUCCESS
@@ -0,0 +1,181 @@
1
+ """Reservation 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.reservations import store
12
+ from maproom.reservations.model import ReservationError
13
+ from maproom.reservations.store import AccountSnapshotPart
14
+ from maproom.settings.model import cache_max_age_hours, snapshot_is_stale
15
+ from maproom.snapshot_time import as_of_date_label
16
+
17
+ RESERVATIONS_INVENTORY_REMEDIATION = "Refresh with: maproom inventory get"
18
+ RESERVATIONS_INVENTORY_REMEDIATION_AWS_ONLY = "Refresh with: maproom inventory get"
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class InventoryState:
23
+ snapshot_path: Path
24
+ exists: bool
25
+ loaded_as_of: str | None
26
+ record_count: int
27
+ is_stale: bool
28
+ cache_max_age_hours: int
29
+ parse_error: str | None = None
30
+ source: str | None = None
31
+ records: tuple[dict[str, Any], ...] = ()
32
+ region: str | None = None
33
+ regions: tuple[str, ...] = ()
34
+ account_parts: tuple[AccountSnapshotPart, ...] = ()
35
+ account_count: int = 0
36
+
37
+
38
+ def read_inventory_state(
39
+ settings_path: Path | None = None,
40
+ *,
41
+ now_utc: datetime | None = None,
42
+ ) -> InventoryState:
43
+ path = store.status_path()
44
+ settings_file_path = settings_path or settings_read_file()
45
+ max_age = cache_max_age_hours(settings_file_path)
46
+
47
+ parts_result = store.list_account_parts()
48
+ if isinstance(parts_result, ReservationError):
49
+ return InventoryState(
50
+ snapshot_path=path,
51
+ exists=True,
52
+ loaded_as_of=None,
53
+ record_count=0,
54
+ is_stale=False,
55
+ cache_max_age_hours=max_age,
56
+ parse_error=parts_result.message,
57
+ )
58
+
59
+ data = store.read_snapshot()
60
+ if isinstance(data, ReservationError):
61
+ return InventoryState(
62
+ snapshot_path=path,
63
+ exists=True,
64
+ loaded_as_of=None,
65
+ record_count=0,
66
+ is_stale=False,
67
+ cache_max_age_hours=max_age,
68
+ parse_error=data.message,
69
+ )
70
+ if data is None:
71
+ return InventoryState(
72
+ snapshot_path=path,
73
+ exists=False,
74
+ loaded_as_of=None,
75
+ record_count=0,
76
+ is_stale=False,
77
+ cache_max_age_hours=max_age,
78
+ )
79
+
80
+ parts = tuple(parts_result)
81
+ loaded_as_of = str(data.get("loaded_as_of") or "")
82
+ records_raw = data.get("records") or []
83
+ records = tuple(r for r in records_raw if isinstance(r, dict))
84
+ record_count = int(
85
+ data.get("record_count")
86
+ if data.get("record_count") is not None
87
+ else len(records)
88
+ )
89
+ source = str(data.get("source") or "") or None
90
+ region = str(data.get("region") or "") or None
91
+ regions_list = data.get("regions")
92
+ if isinstance(regions_list, list) and regions_list:
93
+ regions = tuple(str(item) for item in regions_list if str(item or "").strip())
94
+ elif region:
95
+ regions = (region,)
96
+ else:
97
+ regions = tuple(sorted({str(r.get("region") or "") for r in records if r.get("region")}))
98
+
99
+ # Overall fresh only when every contributing folder is within cache_max_age_hours.
100
+ if parts:
101
+ stale = any(
102
+ snapshot_is_stale(part.loaded_as_of, max_age, now=now_utc) for part in parts
103
+ )
104
+ else:
105
+ stale = snapshot_is_stale(loaded_as_of, max_age, now=now_utc)
106
+
107
+ account_ids = {part.account_id for part in parts if part.account_id}
108
+ account_count = len(account_ids) if account_ids else len(parts)
109
+
110
+ return InventoryState(
111
+ snapshot_path=path,
112
+ exists=True,
113
+ loaded_as_of=loaded_as_of or None,
114
+ record_count=record_count,
115
+ is_stale=stale,
116
+ cache_max_age_hours=max_age,
117
+ source=source,
118
+ records=records,
119
+ region=region,
120
+ regions=regions,
121
+ account_parts=parts,
122
+ account_count=account_count,
123
+ )
124
+
125
+
126
+ def inventory_snapshot_usable_for_analyze(state: InventoryState) -> bool:
127
+ return state.exists and state.parse_error is None
128
+
129
+
130
+ def reservation_coverage_missing(state: InventoryState) -> bool:
131
+ if state.parse_error:
132
+ return True
133
+ if not state.exists:
134
+ return True
135
+ if state.is_stale:
136
+ return True
137
+ # Fresh empty snapshot confirms the region and account were checked.
138
+ return False
139
+
140
+
141
+ def reservations_tty_segment(state: InventoryState) -> str:
142
+ if not state.exists or state.parse_error:
143
+ return "reservations: none loaded (on-demand pricing)"
144
+ as_of = as_of_date_label(state.loaded_as_of)
145
+ if state.is_stale:
146
+ return f"reservations: loaded (stale) (as of {as_of})"
147
+ if state.record_count == 0:
148
+ return f"reservations: none in snapshot (checked {as_of})"
149
+ if state.account_count > 1:
150
+ return (
151
+ f"reservations: loaded ({state.record_count} across "
152
+ f"{state.account_count} accounts, as of {as_of})"
153
+ )
154
+ return f"reservations: loaded (as of {as_of})"
155
+
156
+
157
+ def stale_reservation_warning(state: InventoryState) -> str | None:
158
+ if not state.exists or not state.is_stale or not state.loaded_as_of:
159
+ return None
160
+ as_of = as_of_date_label(state.loaded_as_of)
161
+ return (
162
+ f"Reservation inventory is stale (loaded {as_of}; reuse limit "
163
+ f"{state.cache_max_age_hours} hours). Re-run 'maproom inventory get'."
164
+ )
165
+
166
+
167
+ def doctor_reservations_message(state: InventoryState) -> str:
168
+ path = str(state.snapshot_path)
169
+ if state.parse_error:
170
+ return f"{path}; could not read snapshot: {state.parse_error}"
171
+ if not state.exists:
172
+ return f"No reservations snapshot file yet. Path: {path}"
173
+ parts = [path, f"loaded_as_of={state.loaded_as_of}"]
174
+ if state.account_count > 1:
175
+ parts.append(f"accounts={state.account_count}")
176
+ if state.regions:
177
+ parts.append(f"regions={','.join(state.regions)}")
178
+ warning = stale_reservation_warning(state)
179
+ if warning:
180
+ parts.append(warning)
181
+ return "; ".join(parts)