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,387 @@
1
+ """Answer cloud CLI reads from a loaded mock account. Never spawns aws or az."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections.abc import Mapping, Sequence
7
+ from typing import Any
8
+
9
+ from maproom.cliio.registry import authorize_cli_call
10
+ from maproom.cliio.runner import CliResult, Runner
11
+ from maproom.mock_environment.load import MockAccount, MockInstance, load_mock_account
12
+
13
+ _AWS_VERSION = "2.34.25"
14
+ _AZURE_VERSION = "2.67.0"
15
+ _ACCOUNT_ID = "123456789012"
16
+ _AZURE_SUBSCRIPTION = "00000000-0000-0000-0000-000000000000"
17
+ _WRITE_IDS = frozenset(
18
+ {
19
+ "aws_service_quotas_request_service_quota_increase",
20
+ "aws_support_create_case",
21
+ }
22
+ )
23
+
24
+
25
+ def command_runner() -> Runner:
26
+ """Real runner, or a mock runner when ``MAPROOM_MOCK_ENVIRONMENT`` is set."""
27
+ account = load_mock_account()
28
+ if account is None:
29
+ return Runner()
30
+ return MockEnvironmentRunner(account)
31
+
32
+
33
+ class MockEnvironmentRunner(Runner):
34
+ """CLI stand-in for one composed mock account."""
35
+
36
+ def __init__(self, account: MockAccount) -> None:
37
+ super().__init__()
38
+ self.account = account
39
+
40
+ def probe_copy(self) -> MockEnvironmentRunner:
41
+ return self
42
+
43
+ def run(
44
+ self,
45
+ cloud: str,
46
+ argv: Sequence[str],
47
+ *,
48
+ api_id: str,
49
+ timeout_s: float | None = None,
50
+ extra_env: Mapping[str, str] | None = None,
51
+ pagination: str | None = None,
52
+ ensure_json: bool = False,
53
+ record: bool = True,
54
+ state_id: str | None = None,
55
+ write_token: str | None = None,
56
+ ) -> CliResult:
57
+ authorize_cli_call(cloud, argv, api_id, write_token=write_token)
58
+ stdout, exit_code, stderr = self._reply(api_id, argv)
59
+ return CliResult(
60
+ argv=[cloud, *argv],
61
+ exit_code=exit_code,
62
+ stdout=stdout,
63
+ stderr=stderr,
64
+ duration_ms=0,
65
+ cloud=cloud, # type: ignore[arg-type]
66
+ cli_path="mock",
67
+ cli_version=_AWS_VERSION if cloud == "aws" else None,
68
+ )
69
+
70
+ def _reply(self, api_id: str, argv: Sequence[str] = ()) -> tuple[str, int, str]:
71
+ if api_id in _WRITE_IDS:
72
+ return "", 1, "mock environment does not perform cloud writes"
73
+ account = self.account
74
+ if account.cloud == "azure":
75
+ return self._reply_azure(api_id, argv)
76
+ return self._reply_aws(api_id, argv)
77
+
78
+ def _reply_aws(self, api_id: str, argv: Sequence[str]) -> tuple[str, int, str]:
79
+ account = self.account
80
+ if api_id == "aws_cli_version":
81
+ return f"aws-cli/{_AWS_VERSION} Python/3.11.0 source/mock", 0, ""
82
+ if api_id == "aws_sts_get_caller_identity":
83
+ return _dump(
84
+ {
85
+ "Account": _ACCOUNT_ID,
86
+ "Arn": f"arn:aws:iam::{_ACCOUNT_ID}:user/mock",
87
+ "UserId": "AIDAMOCKENVIRONMENT",
88
+ }
89
+ ), 0, ""
90
+ if api_id == "aws_iam_list_account_aliases":
91
+ return _dump({"AccountAliases": ["mom-and-pop"]}), 0, ""
92
+ if api_id == "azure_cli_version":
93
+ return "", 1, "Azure CLI not installed"
94
+ if api_id == "azure_account_show":
95
+ return "", 1, "Azure CLI not installed"
96
+ if api_id == "aws_configure_get_region":
97
+ return account.region, 0, ""
98
+ if api_id == "aws_ec2_describe_instances":
99
+ return _dump(_describe_instances(account.instances)), 0, ""
100
+ if api_id == "aws_ec2_describe_instance_type_offerings":
101
+ return _dump(_offerings(account)), 0, ""
102
+ if api_id == "aws_ec2_describe_instance_types":
103
+ return _dump(_instance_types(account)), 0, ""
104
+ if api_id == "aws_ec2_describe_reserved_instances":
105
+ return _dump({"ReservedInstances": [_reserved(row) for row in account.reservations]}), 0, ""
106
+ if api_id == "aws_savingsplans_describe_savings_plans":
107
+ return _dump({"savingsPlans": [_savings_plan(row) for row in account.savings_plans]}), 0, ""
108
+ if api_id == "aws_service_quotas_list_service_quotas":
109
+ return _dump({"Quotas": [_quota(row) for row in account.quotas]}), 0, ""
110
+ if api_id == "aws_service_quotas_list_requested_service_quota_change_history":
111
+ return (
112
+ _dump(
113
+ {
114
+ "RequestedQuotas": [
115
+ {
116
+ "Status": "PENDING",
117
+ "QuotaCode": "L-1216C47A",
118
+ "Created": "2026-11-20T00:00:00Z",
119
+ },
120
+ {
121
+ "Status": "CASE_OPENED",
122
+ "QuotaCode": "L-1216C47A",
123
+ "Created": "2026-11-15T00:00:00Z",
124
+ },
125
+ ]
126
+ }
127
+ ),
128
+ 0,
129
+ "",
130
+ )
131
+ if api_id == "aws_service_quotas_get_requested_service_quota_change":
132
+ request_id = _argv_value(argv, "--request-id") or "mock-request"
133
+ return (
134
+ _dump(
135
+ {
136
+ "RequestedQuota": {
137
+ "Id": request_id,
138
+ "Status": "DENIED",
139
+ "QuotaCode": "L-1216C47A",
140
+ "DesiredValue": 32.0,
141
+ "Created": "2026-11-01T00:00:00Z",
142
+ }
143
+ }
144
+ ),
145
+ 0,
146
+ "",
147
+ )
148
+ if api_id == "aws_cloudwatch_usage_get_metric_data":
149
+ return _dump({"MetricDataResults": []}), 0, ""
150
+ if api_id == "aws_cloudwatch_get_metric_data":
151
+ return _dump(_cpu_metric_data(account, argv)), 0, ""
152
+ if api_id == "aws_cloudtrail_lookup_events":
153
+ return _dump({"Events": []}), 0, ""
154
+ if api_id == "aws_config_get_resource_config_history":
155
+ return _dump({"configurationItems": []}), 0, ""
156
+ if api_id == "aws_compute_optimizer_get_ec2_instance_recommendations":
157
+ return _dump({"instanceRecommendations": []}), 0, ""
158
+ if api_id == "aws_ce_get_reservation_utilization":
159
+ return _dump(_reservation_utilization(account, argv)), 0, ""
160
+ return "", 1, "mock environment has no reply for this call"
161
+
162
+ def _reply_azure(self, api_id: str, argv: Sequence[str]) -> tuple[str, int, str]:
163
+ del argv
164
+ account = self.account
165
+ if api_id == "aws_cli_version":
166
+ return f"aws-cli/{_AWS_VERSION} Python/3.11.0 source/mock", 0, ""
167
+ if api_id in {"aws_sts_get_caller_identity", "aws_iam_list_account_aliases"}:
168
+ return "", 1, "mock environment has no AWS identity for this account"
169
+ if api_id == "azure_cli_version":
170
+ return _dump({"azure-cli": _AZURE_VERSION}), 0, ""
171
+ if api_id == "azure_account_show":
172
+ return _dump(
173
+ {
174
+ "id": _AZURE_SUBSCRIPTION,
175
+ "name": "azure-shop",
176
+ "tenantId": "11111111-1111-1111-1111-111111111111",
177
+ }
178
+ ), 0, ""
179
+ if api_id == "azure_configure_get_location":
180
+ return account.region, 0, ""
181
+ if api_id == "azure_vm_list":
182
+ return _dump(_azure_vms(account)), 0, ""
183
+ if api_id == "azure_vm_list_skus":
184
+ return _dump(list(_offered_names(account))), 0, ""
185
+ if api_id == "azure_vm_list_usage":
186
+ return _dump([]), 0, ""
187
+ if api_id == "azure_monitor_activity_log_list":
188
+ return _dump([]), 0, ""
189
+ if api_id == "azure_quota_request_list":
190
+ return _dump({"value": []}), 0, ""
191
+ if api_id == "azure_reservations_list":
192
+ return _dump([]), 0, ""
193
+ return "", 1, "mock environment has no reply for this call"
194
+
195
+
196
+ def _dump(payload: Any) -> str:
197
+ return json.dumps(payload)
198
+
199
+
200
+ def _argv_value(argv: Sequence[str], flag: str) -> str | None:
201
+ parts = list(argv)
202
+ for index, part in enumerate(parts):
203
+ if part == flag and index + 1 < len(parts):
204
+ return str(parts[index + 1])
205
+ return None
206
+
207
+
208
+ def _cpu_metric_data(account: MockAccount, argv: Sequence[str]) -> dict[str, Any]:
209
+ """Flat CPUUtilization series so p99 equals the mock instance's cpu_percent."""
210
+ text = " ".join(str(part) for part in argv)
211
+ instance = next((row for row in account.instances if row.id and row.id in text), None)
212
+ if instance is None and len(account.instances) == 1:
213
+ instance = account.instances[0]
214
+ if instance is None or instance.cpu_percent is None:
215
+ return {"MetricDataResults": [{"Id": "cpu", "Timestamps": [], "Values": []}]}
216
+ return {
217
+ "MetricDataResults": [
218
+ {
219
+ "Id": "cpu",
220
+ "Timestamps": ["2026-10-29T00:00:00Z"],
221
+ "Values": [instance.cpu_percent],
222
+ }
223
+ ]
224
+ }
225
+
226
+
227
+ def _describe_instances(instances: tuple[MockInstance, ...]) -> dict[str, Any]:
228
+ rows: list[dict[str, Any]] = []
229
+ for instance in instances:
230
+ row: dict[str, Any] = {
231
+ "InstanceId": instance.id,
232
+ "InstanceType": instance.instance_type,
233
+ "Placement": {
234
+ "AvailabilityZone": instance.az,
235
+ "AvailabilityZoneId": instance.az_id,
236
+ },
237
+ "State": {"Name": "running"},
238
+ "PlatformDetails": "Linux/UNIX",
239
+ "VirtualizationType": "hvm",
240
+ "RootDeviceType": "ebs",
241
+ }
242
+ if instance.ena_support:
243
+ row["EnaSupport"] = True
244
+ if instance.lifecycle == "spot":
245
+ row["InstanceLifecycle"] = "spot"
246
+ rows.append(row)
247
+ return {"Reservations": [{"Instances": rows}]}
248
+
249
+
250
+ def _offered_names(account: MockAccount) -> tuple[str, ...]:
251
+ names = account.offered_instance_types or tuple(
252
+ instance.instance_type for instance in account.instances if instance.instance_type
253
+ )
254
+ seen: list[str] = []
255
+ for instance in account.instances:
256
+ if instance.instance_type and instance.instance_type not in names and instance.instance_type not in seen:
257
+ seen.append(instance.instance_type)
258
+ return tuple(names) + tuple(seen)
259
+
260
+
261
+ def _instance_types(account: MockAccount) -> dict[str, Any]:
262
+ return {"InstanceTypes": [_instance_type_row(name) for name in _offered_names(account)]}
263
+
264
+
265
+ def _instance_type_row(name: str) -> dict[str, Any]:
266
+ size = name.split(".")[-1] if "." in name else ""
267
+ vcpus = {"large": 2, "xlarge": 4, "2xlarge": 8}.get(size, 2)
268
+ row: dict[str, Any] = {
269
+ "InstanceType": name,
270
+ "ProcessorInfo": {"SupportedArchitectures": ["x86_64"]},
271
+ "VCpuInfo": {"DefaultVCpus": vcpus},
272
+ "MemoryInfo": {"SizeInMiB": vcpus * 4096},
273
+ "NetworkInfo": {"NetworkPerformance": "Up to 10 Gigabit"},
274
+ "CurrentGeneration": not name.startswith("m4"),
275
+ }
276
+ if name.startswith("g"):
277
+ row["GpuInfo"] = {"Gpus": [{"Name": "mock", "Count": 1}]}
278
+ return row
279
+
280
+
281
+ def _azure_vms(account: MockAccount) -> list[dict[str, Any]]:
282
+ rows: list[dict[str, Any]] = []
283
+ for instance in account.instances:
284
+ name = instance.id.rstrip("/").split("/")[-1] or instance.id
285
+ rows.append(
286
+ {
287
+ "id": instance.id,
288
+ "name": name,
289
+ "location": account.region,
290
+ "hardwareProfile": {"vmSize": instance.instance_type},
291
+ "storageProfile": {"osDisk": {"osType": "Linux"}},
292
+ }
293
+ )
294
+ return rows
295
+
296
+
297
+ def _offerings(account: MockAccount) -> dict[str, Any]:
298
+ names = _offered_names(account)
299
+ return {
300
+ "InstanceTypeOfferings": [
301
+ {
302
+ "InstanceType": name,
303
+ "LocationType": "region",
304
+ "Location": account.region,
305
+ }
306
+ for name in names
307
+ ]
308
+ }
309
+
310
+
311
+ def _reservation_utilization(account: MockAccount, argv: Sequence[str]) -> dict[str, Any]:
312
+ """CE utilization buckets for mock reservations (0% used unless the row sets utilization_percentage)."""
313
+ text = " ".join(str(part) for part in argv)
314
+ if "SUBSCRIPTION_ID" in text:
315
+ return {"UtilizationsByTime": []}
316
+ region = account.region.strip().lower()
317
+ groups: list[dict[str, Any]] = []
318
+ for row in account.reservations:
319
+ instance_type = str(row.get("instance_type") or "").strip()
320
+ if not instance_type:
321
+ continue
322
+ platform = str(row.get("platform") or "Linux/UNIX").strip()
323
+ quantity = int(row.get("quantity") or 1)
324
+ percentage = str(row.get("utilization_percentage") or "0")
325
+ unused_hours = row.get("unused_hours")
326
+ if unused_hours is None:
327
+ try:
328
+ fraction = max(0.0, min(float(percentage), 100.0)) / 100.0
329
+ except ValueError:
330
+ fraction = 0.0
331
+ unused_hours = quantity * max(0.0, 1.0 - fraction) * 720.0
332
+ groups.append(
333
+ {
334
+ "Attributes": {
335
+ "region": region,
336
+ "instanceType": instance_type,
337
+ "platform": platform,
338
+ },
339
+ "Utilization": {
340
+ "UtilizationPercentage": percentage,
341
+ "UnusedHours": str(unused_hours),
342
+ },
343
+ }
344
+ )
345
+ if not groups:
346
+ return {"UtilizationsByTime": []}
347
+ return {"UtilizationsByTime": [{"Groups": groups}]}
348
+
349
+
350
+ def _reserved(row: dict[str, Any]) -> dict[str, Any]:
351
+ return {
352
+ "InstanceType": str(row.get("instance_type") or ""),
353
+ "InstanceCount": int(row.get("quantity") or 1),
354
+ "State": str(row.get("state") or "active"),
355
+ "AvailabilityZone": str(row.get("az") or ""),
356
+ "ProductDescription": str(row.get("platform") or "Linux/UNIX"),
357
+ "OfferingClass": str(row.get("offering_class") or "standard"),
358
+ "Scope": str(row.get("scope") or "Region"),
359
+ "InstanceTenancy": str(row.get("tenancy") or "default"),
360
+ "End": str(row.get("end") or ""),
361
+ }
362
+
363
+
364
+ def _savings_plan(row: dict[str, Any]) -> dict[str, Any]:
365
+ return {
366
+ "savingsPlanType": str(row.get("plan_type") or ""),
367
+ "state": str(row.get("state") or "active"),
368
+ "paymentOption": str(row.get("payment_option") or ""),
369
+ "commitment": str(row.get("commitment") or ""),
370
+ "region": str(row.get("region") or ""),
371
+ "start": str(row.get("start") or ""),
372
+ "end": str(row.get("end") or ""),
373
+ }
374
+
375
+
376
+ def _quota(row: dict[str, Any]) -> dict[str, Any]:
377
+ code = str(row.get("quota_code") or "")
378
+ return {
379
+ "ServiceCode": "ec2",
380
+ "QuotaCode": code,
381
+ "QuotaName": str(row.get("quota_name") or code),
382
+ "Value": float(row.get("value") or 0),
383
+ "Usage": float(row.get("usage") or 0),
384
+ }
385
+
386
+
387
+ __all__ = ["MockEnvironmentRunner", "command_runner"]
@@ -0,0 +1 @@
1
+ """JSON output helpers for maproom CLI."""
@@ -0,0 +1,241 @@
1
+ """Build and print JSON documents for maproom --json output.
2
+
3
+ Every document uses the same envelope, then a payload that depends on
4
+ schema_type. schema_version stays 1. schema_id is the $id of that command's
5
+ schema file. Key order puts schema_type first. Other key order is not a
6
+ contract beyond that.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import sys
13
+ from datetime import datetime, timezone
14
+ from typing import Any
15
+
16
+ from maproom.exitcodes import exit_code_for_error
17
+ from maproom.redaction import redact_tree
18
+
19
+ SCHEMA_VERSION = 1
20
+
21
+ ENVELOPE_KEYS = (
22
+ "schema_type",
23
+ "schema_version",
24
+ "schema_id",
25
+ "metadata",
26
+ "errors",
27
+ "warnings",
28
+ )
29
+
30
+
31
+ def command_metadata(
32
+ invoked: str,
33
+ *,
34
+ started_at: datetime | None = None,
35
+ now: datetime | None = None,
36
+ duration_ms: int | None = None,
37
+ extra: dict[str, Any] | None = None,
38
+ ) -> dict[str, Any]:
39
+ """Shared metadata. ``invoked_at`` is the start time, UTC, RFC 3339."""
40
+ end = now or datetime.now(timezone.utc)
41
+ started = started_at or end
42
+ if started.tzinfo is None:
43
+ started = started.replace(tzinfo=timezone.utc)
44
+ if end.tzinfo is None:
45
+ end = end.replace(tzinfo=timezone.utc)
46
+ started = started.astimezone(timezone.utc)
47
+ end = end.astimezone(timezone.utc)
48
+ if duration_ms is None:
49
+ duration_ms = max(0, int((end - started).total_seconds() * 1000))
50
+ else:
51
+ duration_ms = max(0, int(duration_ms))
52
+ meta: dict[str, Any] = {
53
+ "invoked": invoked,
54
+ "invoked_at": started.strftime("%Y-%m-%dT%H:%M:%SZ"),
55
+ "duration_ms": duration_ms,
56
+ }
57
+ if extra:
58
+ meta.update(extra)
59
+ return meta
60
+
61
+
62
+ def error_item(code: str, message: str, **extra: Any) -> dict[str, Any]:
63
+ item: dict[str, Any] = {"code": code, "message": message}
64
+ item.update(extra)
65
+ return item
66
+
67
+
68
+ def warning_item(code: str, message: str, **extra: Any) -> dict[str, Any]:
69
+ item: dict[str, Any] = {"code": code, "message": message}
70
+ item.update(extra)
71
+ return item
72
+
73
+
74
+ def build_document(
75
+ *,
76
+ schema_type: str,
77
+ schema_id: str,
78
+ metadata: dict[str, Any],
79
+ errors: list[dict[str, Any]] | None = None,
80
+ warnings: list[dict[str, Any]] | None = None,
81
+ payload: dict[str, Any] | None = None,
82
+ schema_version: int = SCHEMA_VERSION,
83
+ ) -> dict[str, Any]:
84
+ """Envelope first, then payload keys. Payload must not reuse envelope keys."""
85
+ document: dict[str, Any] = {
86
+ "schema_type": schema_type,
87
+ "schema_version": schema_version,
88
+ "schema_id": schema_id,
89
+ "metadata": metadata,
90
+ "errors": list(errors or []),
91
+ "warnings": list(warnings or []),
92
+ }
93
+ for key, value in (payload or {}).items():
94
+ if key in document:
95
+ raise ValueError(f"payload key {key!r} collides with the envelope")
96
+ document[key] = value
97
+ return document
98
+
99
+
100
+ def build_error_document(
101
+ code: str,
102
+ message: str,
103
+ *,
104
+ invoked: str = "",
105
+ metadata: dict[str, Any] | None = None,
106
+ hint: str | None = None,
107
+ ) -> dict[str, Any]:
108
+ """Failure document. There is no command payload. Exit codes read errors[0].code."""
109
+ err = error_item(code, message)
110
+ if hint:
111
+ err["hint"] = hint
112
+ return build_document(
113
+ schema_type="error",
114
+ schema_id="maproom.error",
115
+ metadata=metadata if metadata is not None else command_metadata(invoked),
116
+ errors=[err],
117
+ warnings=[],
118
+ )
119
+
120
+
121
+ def build_error_envelope(
122
+ code: str,
123
+ message: str,
124
+ *,
125
+ invoked: str = "",
126
+ metadata: dict[str, Any] | None = None,
127
+ hint: str | None = None,
128
+ ) -> dict[str, Any]:
129
+ """Alias for ``build_error_document``. Failure documents have no command payload."""
130
+ return build_error_document(
131
+ code,
132
+ message,
133
+ invoked=invoked,
134
+ metadata=metadata,
135
+ hint=hint,
136
+ )
137
+
138
+
139
+ def build_recommendation_with_plan_envelope(
140
+ recommendation: dict[str, Any],
141
+ *,
142
+ plan_mutation: dict[str, Any],
143
+ ) -> dict[str, Any]:
144
+ return build_recommendation_with_plan_document(
145
+ recommendation, plan_mutation=plan_mutation
146
+ )
147
+
148
+
149
+ def build_recommendation_with_plan_document(
150
+ recommendation: dict[str, Any],
151
+ *,
152
+ plan_mutation: dict[str, Any],
153
+ ) -> dict[str, Any]:
154
+ """Rightsizer document plus plan_mutation. Drops the nested envelope."""
155
+ payload = {
156
+ key: value
157
+ for key, value in recommendation.items()
158
+ if key not in ENVELOPE_KEYS
159
+ }
160
+ payload["plan_mutation"] = plan_mutation
161
+ return build_document(
162
+ schema_type="recommendation_with_plan",
163
+ schema_id="maproom.recommendation_with_plan",
164
+ metadata=dict(recommendation.get("metadata") or command_metadata("analyze")),
165
+ errors=list(recommendation.get("errors") or []),
166
+ warnings=list(recommendation.get("warnings") or []),
167
+ payload=payload,
168
+ )
169
+
170
+
171
+ def print_json(doc: dict[str, Any]) -> None:
172
+ print(json.dumps(redact_tree(doc), ensure_ascii=False))
173
+
174
+
175
+ def print_command_error(
176
+ message: str,
177
+ *,
178
+ as_json: bool,
179
+ invoked: str,
180
+ code: str = "runtime",
181
+ ) -> int:
182
+ """Human stderr or JSON error envelope. Returns the matching exit code."""
183
+ if as_json:
184
+ return print_error_envelope(code, message, invoked=invoked)
185
+ print(f"error: {message}", file=sys.stderr)
186
+ return exit_code_for_error(code)
187
+
188
+
189
+ def print_command_success(
190
+ schema_type: str,
191
+ schema_id: str,
192
+ invoked: str,
193
+ payload: dict[str, Any],
194
+ *,
195
+ warnings: list[dict[str, Any]] | None = None,
196
+ ) -> None:
197
+ print_json(
198
+ build_document(
199
+ schema_type=schema_type,
200
+ schema_id=schema_id,
201
+ metadata=command_metadata(invoked),
202
+ warnings=warnings or [],
203
+ payload=payload,
204
+ )
205
+ )
206
+
207
+
208
+ def print_error_envelope(
209
+ code: str,
210
+ message: str,
211
+ *,
212
+ invoked: str = "",
213
+ metadata: dict[str, Any] | None = None,
214
+ hint: str | None = None,
215
+ ) -> int:
216
+ """Print one error document and return its exit code from exit_codes.json."""
217
+ print(
218
+ json.dumps(
219
+ redact_tree(
220
+ build_error_document(
221
+ code,
222
+ message,
223
+ invoked=invoked,
224
+ metadata=metadata,
225
+ hint=hint,
226
+ )
227
+ ),
228
+ indent=2,
229
+ ensure_ascii=False,
230
+ )
231
+ )
232
+ return exit_code_for_error(code)
233
+
234
+
235
+ def finish_consent_gate(gate: Any, *, as_json: bool, invoked: str = "") -> int:
236
+ """Emit a consent refusal. ``quiet`` must already have suppressed human text."""
237
+ code = gate.reason_code or "consent_declined"
238
+ message = gate.message or code
239
+ if as_json:
240
+ return print_error_envelope(code, message, invoked=invoked)
241
+ return exit_code_for_error(code)
@@ -0,0 +1,11 @@
1
+ """Credential pattern redaction for doctor JSON output."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from maproom.redaction import redact_text
6
+
7
+
8
+ def redact(text: str | None) -> str | None:
9
+ if text is None:
10
+ return None
11
+ return redact_text(text)