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
+ """Account-wide CloudTrail reads for the analyze operator-context phase."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import re
7
+ from collections import defaultdict
8
+ from dataclasses import dataclass, field
9
+ from datetime import datetime, timedelta, timezone
10
+ from typing import Any
11
+
12
+ from maproom.analyze.utilization import _iso_z
13
+ from maproom.errors import AccessDeniedError
14
+ from maproom.parsers import parse_cloudtrail_lookup_events
15
+
16
+ _CONTEXT_LOOKBACK_DAYS = 30
17
+ _EVENT_RUN_INSTANCES = "RunInstances"
18
+ _EVENT_BID_EVICTED = "BidEvictedEvent"
19
+
20
+ _FORBIDDEN_VALUE = re.compile(
21
+ r"(^arn:|^i-[0-9a-f]{8,}$|^\d{12}$|^\d{1,3}(?:\.\d{1,3}){3}$)",
22
+ re.IGNORECASE,
23
+ )
24
+
25
+
26
+ @dataclass
27
+ class SpotHistoryCounts:
28
+ """Spot launches and forced terminations per region and instance type."""
29
+
30
+ launches: dict[tuple[str, str], int] = field(default_factory=lambda: defaultdict(int))
31
+ terminations: dict[tuple[str, str], int] = field(
32
+ default_factory=lambda: defaultdict(int)
33
+ )
34
+
35
+
36
+ @dataclass
37
+ class LaunchAttemptCounts:
38
+ """Launched and failed launch counts by purchase option and error code."""
39
+
40
+ launched: dict[tuple[str, str, str], int] = field(
41
+ default_factory=lambda: defaultdict(int)
42
+ )
43
+ failed: dict[tuple[str, str, str, str], int] = field(
44
+ default_factory=lambda: defaultdict(int)
45
+ )
46
+
47
+
48
+ def context_trail_window(
49
+ now: datetime | None = None,
50
+ ) -> tuple[datetime, datetime]:
51
+ end = (now or datetime.now(timezone.utc)).astimezone(timezone.utc).replace(microsecond=0)
52
+ start = end - timedelta(days=_CONTEXT_LOOKBACK_DAYS)
53
+ return start, end
54
+
55
+
56
+ def build_account_cloudtrail_argv(
57
+ *,
58
+ event_name: str,
59
+ start: datetime,
60
+ end: datetime,
61
+ region: str,
62
+ next_token: str | None = None,
63
+ ) -> list[str]:
64
+ argv = [
65
+ "cloudtrail",
66
+ "lookup-events",
67
+ "--lookup-attributes",
68
+ f"AttributeKey=EventName,AttributeValue={event_name}",
69
+ "--start-time",
70
+ _iso_z(start),
71
+ "--end-time",
72
+ _iso_z(end),
73
+ "--region",
74
+ region,
75
+ "--output",
76
+ "json",
77
+ ]
78
+ if next_token:
79
+ argv.extend(["--next-token", next_token])
80
+ return argv
81
+
82
+
83
+ def _runner_response(result: Any) -> dict[str, Any]:
84
+ stdout_json: dict[str, Any] | list[Any] | None = None
85
+ raw = (getattr(result, "stdout", "") or "").strip()
86
+ if raw:
87
+ try:
88
+ parsed = json.loads(raw)
89
+ if isinstance(parsed, dict):
90
+ stdout_json = parsed
91
+ except json.JSONDecodeError:
92
+ stdout_json = None
93
+ return {
94
+ "exit_code": int(getattr(result, "exit_code", 1)),
95
+ "stderr": (getattr(result, "stderr", "") or ""),
96
+ "stdout_json": stdout_json or {},
97
+ }
98
+
99
+
100
+ def _load_cloudtrail_event(record: dict[str, Any]) -> dict[str, Any] | None:
101
+ raw = record.get("CloudTrailEvent")
102
+ if isinstance(raw, dict):
103
+ return raw
104
+ if not isinstance(raw, str) or not raw.strip():
105
+ return None
106
+ try:
107
+ payload = json.loads(raw)
108
+ except json.JSONDecodeError:
109
+ return None
110
+ return payload if isinstance(payload, dict) else None
111
+
112
+
113
+ def _instance_type_from_params(params: dict[str, Any]) -> str | None:
114
+ for key in ("instanceType", "InstanceType"):
115
+ value = params.get(key)
116
+ if isinstance(value, str) and value.strip():
117
+ return value.strip()
118
+ if isinstance(value, dict):
119
+ inner = value.get("value")
120
+ if isinstance(inner, str) and inner.strip():
121
+ return inner.strip()
122
+ for container_key in ("instancesSet", "instances", "instanceSet"):
123
+ instances = params.get(container_key)
124
+ if isinstance(instances, dict):
125
+ items = instances.get("items")
126
+ if isinstance(items, list) and items:
127
+ first = items[0]
128
+ if isinstance(first, dict):
129
+ itype = first.get("instanceType") or first.get("InstanceType")
130
+ if isinstance(itype, str) and itype.strip():
131
+ return itype.strip()
132
+ return None
133
+
134
+
135
+ def _instance_type_from_event(payload: dict[str, Any]) -> str | None:
136
+ params = payload.get("requestParameters")
137
+ if isinstance(params, dict):
138
+ itype = _instance_type_from_params(params)
139
+ if itype:
140
+ return itype
141
+ response = payload.get("responseElements")
142
+ if isinstance(response, dict):
143
+ return _instance_type_from_params(response)
144
+ return None
145
+
146
+
147
+ def _is_spot_request(params: dict[str, Any]) -> bool:
148
+ market = params.get("instanceMarketOptions") or params.get("instanceMarketType")
149
+ if isinstance(market, dict):
150
+ spot = market.get("marketType") or market.get("MarketType")
151
+ if isinstance(spot, str) and spot.lower() == "spot":
152
+ return True
153
+ if isinstance(market, str) and market.lower() == "spot":
154
+ return True
155
+ return False
156
+
157
+
158
+ def _purchase_option(params: dict[str, Any], *, error_code: str | None) -> str:
159
+ if error_code:
160
+ if _is_spot_request(params):
161
+ return "spot"
162
+ return "on_demand"
163
+ if _is_spot_request(params):
164
+ return "spot"
165
+ return "on_demand"
166
+
167
+
168
+ def _error_code(record: dict[str, Any], payload: dict[str, Any]) -> str | None:
169
+ for source in (record, payload):
170
+ if not isinstance(source, dict):
171
+ continue
172
+ for key in ("errorCode", "ErrorCode"):
173
+ code = source.get(key)
174
+ if isinstance(code, str) and code.strip():
175
+ return code.strip()
176
+ response = payload.get("responseElements")
177
+ if isinstance(response, dict):
178
+ for key in ("errorCode", "ErrorCode"):
179
+ code = response.get(key)
180
+ if isinstance(code, str) and code.strip():
181
+ return code.strip()
182
+ return None
183
+
184
+
185
+ def _event_succeeded(record: dict[str, Any], payload: dict[str, Any]) -> bool:
186
+ if _error_code(record, payload):
187
+ return False
188
+ if record.get("errorCode") or record.get("ErrorCode"):
189
+ return False
190
+ return True
191
+
192
+
193
+ def collect_account_cloudtrail(
194
+ runner: Any,
195
+ regions: set[str],
196
+ *,
197
+ now: datetime | None = None,
198
+ ) -> tuple[SpotHistoryCounts, LaunchAttemptCounts]:
199
+ """Read RunInstances and BidEvictedEvent in each region for the last 30 days."""
200
+ start, end = context_trail_window(now)
201
+ spot = SpotHistoryCounts()
202
+ launches = LaunchAttemptCounts()
203
+ for region in sorted(r for r in regions if r.strip()):
204
+ for event_name in (_EVENT_RUN_INSTANCES, _EVENT_BID_EVICTED):
205
+ next_token: str | None = None
206
+ while True:
207
+ argv = build_account_cloudtrail_argv(
208
+ event_name=event_name,
209
+ start=start,
210
+ end=end,
211
+ region=region,
212
+ next_token=next_token,
213
+ )
214
+ from maproom.analyze.local_reads import run_cached_analyze_read, window_cache_suffix
215
+
216
+ result = run_cached_analyze_read(
217
+ runner,
218
+ "aws",
219
+ argv,
220
+ api_id="aws_cloudtrail_lookup_events",
221
+ region=region,
222
+ suffix=window_cache_suffix(
223
+ start=start.date().isoformat(),
224
+ end=end.date().isoformat(),
225
+ granularity="account_context",
226
+ label=event_name,
227
+ ),
228
+ record=False,
229
+ now=now,
230
+ )
231
+ response = _runner_response(result)
232
+ try:
233
+ events, next_token = parse_cloudtrail_lookup_events(response)
234
+ except AccessDeniedError:
235
+ events, next_token = [], None
236
+ except Exception:
237
+ events, next_token = [], None
238
+ for record in events:
239
+ if not isinstance(record, dict):
240
+ continue
241
+ payload = _load_cloudtrail_event(record)
242
+ if not payload:
243
+ continue
244
+ params = payload.get("requestParameters")
245
+ if not isinstance(params, dict):
246
+ params = {}
247
+ itype = _instance_type_from_event(payload)
248
+ if not itype:
249
+ continue
250
+ key = (region.lower(), itype)
251
+ if event_name == _EVENT_BID_EVICTED:
252
+ spot.terminations[key] += 1
253
+ continue
254
+ error = _error_code(record, payload)
255
+ purchase = _purchase_option(params, error_code=error)
256
+ if _event_succeeded(record, payload):
257
+ launches.launched[(region.lower(), itype, purchase)] += 1
258
+ if purchase == "spot":
259
+ spot.launches[key] += 1
260
+ elif error:
261
+ launches.failed[(region.lower(), itype, purchase, error)] += 1
262
+ if not next_token:
263
+ break
264
+ return spot, launches
265
+
266
+
267
+ def spot_history_rows(counts: SpotHistoryCounts) -> list[dict[str, Any]]:
268
+ rows: list[dict[str, Any]] = []
269
+ keys = set(counts.launches) | set(counts.terminations)
270
+ for region, itype in sorted(keys):
271
+ row: dict[str, Any] = {
272
+ "region": region,
273
+ "instance_type": itype,
274
+ "spot_launches": int(counts.launches.get((region, itype), 0)),
275
+ "spot_terminations": int(counts.terminations.get((region, itype), 0)),
276
+ }
277
+ rows.append(row)
278
+ return rows
279
+
280
+
281
+ def launch_attempt_rows(counts: LaunchAttemptCounts) -> list[dict[str, Any]]:
282
+ grouped: dict[tuple[str, str, str], dict[str, int]] = defaultdict(lambda: defaultdict(int))
283
+ for key, value in counts.launched.items():
284
+ region, itype, purchase = key
285
+ grouped[(region, itype, purchase)]["launched"] += int(value)
286
+ for key, value in counts.failed.items():
287
+ region, itype, purchase, code = key
288
+ grouped[(region, itype, purchase)][f"failed:{code}"] += int(value)
289
+ rows: list[dict[str, Any]] = []
290
+ for (region, itype, purchase), stats in sorted(grouped.items()):
291
+ launched = int(stats.pop("launched", 0))
292
+ failures = {k.split(":", 1)[1]: v for k, v in stats.items() if k.startswith("failed:")}
293
+ row: dict[str, Any] = {
294
+ "region": region,
295
+ "instance_type": itype,
296
+ "purchase_option": purchase,
297
+ "launched_count": launched,
298
+ }
299
+ if failures:
300
+ row["failed_by_error_code"] = dict(sorted(failures.items()))
301
+ rows.append(row)
302
+ return rows
303
+
304
+
305
+ def assert_no_identity_values(section: object, *, path: str = "") -> None:
306
+ """Reject values that look like ids, ARNs, or addresses in context output."""
307
+ if isinstance(section, dict):
308
+ for key, value in section.items():
309
+ assert_no_identity_values(value, path=f"{path}.{key}" if path else str(key))
310
+ return
311
+ if isinstance(section, list):
312
+ for index, value in enumerate(section):
313
+ assert_no_identity_values(value, path=f"{path}[{index}]")
314
+ return
315
+ if isinstance(section, str) and _FORBIDDEN_VALUE.search(section.strip()):
316
+ raise ValueError(f"identity-shaped value in operator context at {path or 'root'}")
@@ -0,0 +1,180 @@
1
+ """Account-wide EC2 quota increase history for the operator-context phase."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from collections import defaultdict
7
+ from dataclasses import dataclass, field
8
+ from datetime import datetime, timezone
9
+ from typing import Any
10
+
11
+ from maproom.analyze.account_cloudtrail import context_trail_window
12
+ from maproom.quotas.quota_request_sync import _parse_quota_timestamp
13
+
14
+ _EC2_SERVICE_CODE = "ec2"
15
+
16
+
17
+ @dataclass
18
+ class QuotaRequestCounts:
19
+ """Quota increase request counts by region, quota code, and outcome bucket."""
20
+
21
+ counts: dict[tuple[str, str, str], int] = field(
22
+ default_factory=lambda: defaultdict(int)
23
+ )
24
+
25
+
26
+ def _context_status_bucket(requested: dict[str, Any]) -> str | None:
27
+ """Map AWS quota request status to context buckets requested/pending/approved/denied."""
28
+ status = str(requested.get("Status") or "").strip().upper()
29
+ if status == "PENDING":
30
+ return "requested"
31
+ if status in {"CASE_OPENED", "IN_PROGRESS"}:
32
+ return "pending"
33
+ if status == "APPROVED":
34
+ return "approved"
35
+ if status in {"DENIED", "NOT_APPROVED"}:
36
+ return "denied"
37
+ if status == "CASE_CLOSED":
38
+ case_status = str(requested.get("CaseStatus") or "").strip().upper()
39
+ if case_status == "APPROVED":
40
+ return "approved"
41
+ if case_status in {"DENIED", "NOT_APPROVED", "UNAPPROVED"}:
42
+ return "denied"
43
+ return "denied"
44
+ return None
45
+
46
+
47
+ def _is_open_bucket(bucket: str) -> bool:
48
+ return bucket in {"requested", "pending"}
49
+
50
+
51
+ def _include_history_item(
52
+ requested: dict[str, Any],
53
+ *,
54
+ window_start: datetime,
55
+ ) -> bool:
56
+ bucket = _context_status_bucket(requested)
57
+ if bucket is None:
58
+ return False
59
+ if _is_open_bucket(bucket):
60
+ return True
61
+ created = _parse_quota_timestamp(requested.get("Created"))
62
+ if created is None:
63
+ return False
64
+ return created >= window_start
65
+
66
+
67
+ def build_quota_request_history_argv(*, region: str, next_token: str | None = None) -> list[str]:
68
+ argv = [
69
+ "service-quotas",
70
+ "list-requested-service-quota-change-history",
71
+ "--service-code",
72
+ _EC2_SERVICE_CODE,
73
+ "--region",
74
+ region,
75
+ "--output",
76
+ "json",
77
+ ]
78
+ if next_token:
79
+ argv.extend(["--next-token", next_token])
80
+ return argv
81
+
82
+
83
+ def _runner_response(result: Any) -> dict[str, Any]:
84
+ raw = (getattr(result, "stdout", "") or "").strip()
85
+ parsed: dict[str, Any] = {}
86
+ if raw:
87
+ try:
88
+ loaded = json.loads(raw)
89
+ if isinstance(loaded, dict):
90
+ parsed = loaded
91
+ except json.JSONDecodeError:
92
+ parsed = {}
93
+ return {
94
+ "exit_code": int(getattr(result, "exit_code", 1)),
95
+ "stderr": (getattr(result, "stderr", "") or ""),
96
+ "stdout_json": parsed,
97
+ }
98
+
99
+
100
+ def _history_items(response: dict[str, Any]) -> tuple[list[dict[str, Any]], str | None]:
101
+ data = response.get("stdout_json") or {}
102
+ if not isinstance(data, dict):
103
+ return [], None
104
+ items = data.get("RequestedQuotas")
105
+ if items is None:
106
+ return [], None
107
+ if not isinstance(items, list):
108
+ return [], None
109
+ next_token = data.get("NextToken")
110
+ token = str(next_token).strip() if isinstance(next_token, str) and next_token.strip() else None
111
+ return [item for item in items if isinstance(item, dict)], token
112
+
113
+
114
+ def collect_account_quota_requests(
115
+ runner: Any,
116
+ regions: set[str],
117
+ *,
118
+ now: datetime | None = None,
119
+ ) -> QuotaRequestCounts:
120
+ """Read EC2 quota increase history per region for the last 30 days plus open requests."""
121
+ window_start, _window_end = context_trail_window(now)
122
+ counts = QuotaRequestCounts()
123
+ for region in sorted(r for r in regions if r.strip()):
124
+ next_token: str | None = None
125
+ while True:
126
+ argv = build_quota_request_history_argv(region=region, next_token=next_token)
127
+ from maproom.analyze.local_reads import run_cached_analyze_read, window_cache_suffix
128
+
129
+ result = run_cached_analyze_read(
130
+ runner,
131
+ "aws",
132
+ argv,
133
+ api_id="aws_service_quotas_list_requested_service_quota_change_history",
134
+ region=region,
135
+ suffix=window_cache_suffix(
136
+ start=window_start.date().isoformat(),
137
+ end=_window_end.date().isoformat(),
138
+ granularity="account_context",
139
+ label="quota_requests",
140
+ ),
141
+ record=False,
142
+ now=now,
143
+ )
144
+ response = _runner_response(result)
145
+ if response["exit_code"] != 0:
146
+ break
147
+ items, next_token = _history_items(response)
148
+ for requested in items:
149
+ if not _include_history_item(requested, window_start=window_start):
150
+ continue
151
+ quota_code = str(requested.get("QuotaCode") or "").strip()
152
+ bucket = _context_status_bucket(requested)
153
+ if not quota_code or bucket is None:
154
+ continue
155
+ key = (region.lower(), quota_code, bucket)
156
+ counts.counts[key] += 1
157
+ if not next_token:
158
+ break
159
+ return counts
160
+
161
+
162
+ def quota_request_rows(counts: QuotaRequestCounts) -> list[dict[str, Any]]:
163
+ """Rows for the quota_requests account-context section (no request ids)."""
164
+ grouped: dict[tuple[str, str], dict[str, int]] = defaultdict(
165
+ lambda: defaultdict(int)
166
+ )
167
+ for (region, quota_code, bucket), value in counts.counts.items():
168
+ grouped[(region, quota_code)][bucket] += int(value)
169
+ rows: list[dict[str, Any]] = []
170
+ for (region, quota_code), buckets in sorted(grouped.items()):
171
+ row: dict[str, Any] = {
172
+ "region": region,
173
+ "quota_code": quota_code,
174
+ "requested": int(buckets.get("requested", 0)),
175
+ "pending": int(buckets.get("pending", 0)),
176
+ "approved": int(buckets.get("approved", 0)),
177
+ "denied": int(buckets.get("denied", 0)),
178
+ }
179
+ rows.append(row)
180
+ return rows