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,124 @@
1
+ """Multi-cloud quota fetch orchestration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from typing import Any
7
+
8
+ from maproom.cliio.runner import CliBelowFloorError
9
+
10
+ from maproom.cli_floors import check_az_floor, format_below_floor
11
+ from maproom.quotas import aws, azure
12
+ from maproom.quotas.family_coverage import includes_general_on_demand_quotas
13
+ from maproom.quotas.model import LAUNCH_RELEVANT_QUOTA_CODES
14
+ from maproom.quotas.model import QuotaError
15
+
16
+ _VALID_CLOUDS = frozenset({"aws", "azure"})
17
+
18
+
19
+ def parse_clouds_arg(value: str | None) -> frozenset[str]:
20
+ text = (value or "all").strip().lower()
21
+ if text in {"all", "both", "*"}:
22
+ return frozenset({"aws", "azure"})
23
+ parts = {part.strip().lower() for part in text.split(",") if part.strip()}
24
+ unknown = parts - _VALID_CLOUDS
25
+ if unknown:
26
+ names = ", ".join(sorted(unknown))
27
+ raise QuotaError(f"unknown cloud(s): {names}")
28
+ if not parts:
29
+ raise QuotaError("clouds must include aws, azure, or all")
30
+ return frozenset(parts)
31
+
32
+
33
+ def fetch_quotas(
34
+ runner: Any,
35
+ *,
36
+ clouds: frozenset[str],
37
+ aws_region: str | None = None,
38
+ azure_location: str | None = None,
39
+ aws_launch_relevant_only: bool = False,
40
+ on_cloud_start: Callable[[str], None] | None = None,
41
+ ) -> tuple[list[dict[str, Any]], list[str]]:
42
+ records: list[dict[str, Any]] = []
43
+ errors: list[str] = []
44
+
45
+ if "aws" in clouds:
46
+ if on_cloud_start is not None:
47
+ on_cloud_start("aws")
48
+ try:
49
+ runner.detect_version("aws", check_floor=True)
50
+ except CliBelowFloorError as exc:
51
+ errors.append(format_below_floor(exc))
52
+ else:
53
+ try:
54
+ records.extend(
55
+ aws.fetch_aws_quotas(
56
+ runner,
57
+ region=aws_region,
58
+ launch_relevant_only=aws_launch_relevant_only,
59
+ )
60
+ )
61
+ except QuotaError as exc:
62
+ errors.append(exc.message)
63
+
64
+ if "azure" in clouds:
65
+ if on_cloud_start is not None:
66
+ on_cloud_start("azure")
67
+ az_status, az_message, _reason = check_az_floor(runner=runner)
68
+ if az_status == "skipped":
69
+ if clouds == frozenset({"azure"}):
70
+ errors.append(az_message or "Azure CLI not available")
71
+ elif az_status == "fail":
72
+ errors.append(az_message or "Azure CLI check failed")
73
+ else:
74
+ try:
75
+ records.extend(
76
+ azure.fetch_azure_quotas(runner, location=azure_location)
77
+ )
78
+ except QuotaError as exc:
79
+ errors.append(exc.message)
80
+
81
+ if not records:
82
+ if errors:
83
+ raise QuotaError("; ".join(errors))
84
+ return [], []
85
+
86
+ if errors and clouds != frozenset({"aws", "azure"}):
87
+ raise QuotaError("; ".join(errors))
88
+
89
+ return records, errors
90
+
91
+
92
+ def cloud_summaries_for_records(
93
+ records: list[dict[str, Any]],
94
+ ) -> tuple[tuple[str, int, str, bool], ...]:
95
+ """Build (cloud, count, region, show_general_line) tuples for human output."""
96
+ aws_records = [r for r in records if str(r.get("cloud") or "aws") != "azure"]
97
+ azure_records = [r for r in records if str(r.get("cloud") or "") == "azure"]
98
+ summaries: list[tuple[str, int, str, bool]] = []
99
+ if aws_records:
100
+ region = str(aws_records[0].get("region") or "unknown")
101
+ non_general = sum(
102
+ 1
103
+ for row in aws_records
104
+ if str(row.get("quota_code") or "") not in LAUNCH_RELEVANT_QUOTA_CODES
105
+ )
106
+ summaries.append(
107
+ (
108
+ "aws",
109
+ non_general,
110
+ region,
111
+ includes_general_on_demand_quotas(aws_records),
112
+ )
113
+ )
114
+ if azure_records:
115
+ region = str(azure_records[0].get("region") or "unknown")
116
+ summaries.append(
117
+ (
118
+ "azure",
119
+ len(azure_records),
120
+ region,
121
+ azure.includes_general_azure_quotas(azure_records),
122
+ )
123
+ )
124
+ return tuple(summaries)
maproom/quotas/load.py ADDED
@@ -0,0 +1,41 @@
1
+ """Payer-file quota snapshot 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.quotas.model import QuotaError, 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 QuotaError(f"file not found: {path}")
22
+ if path.is_dir():
23
+ raise QuotaError(f"path is a directory: {path}")
24
+ try:
25
+ text = path.read_text(encoding="utf-8")
26
+ except OSError as exc:
27
+ raise QuotaError(f"could not read {path}: {exc}") from exc
28
+ if not text.strip():
29
+ raise QuotaError(f"file is empty: {path}")
30
+ try:
31
+ data = json.loads(text)
32
+ except json.JSONDecodeError as exc:
33
+ raise QuotaError(f"invalid JSON in {path}: {exc}") from exc
34
+ if not isinstance(data, dict):
35
+ raise QuotaError(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,178 @@
1
+ """Quota 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
+ # EC2 launch-relevant vCPU quotas. maproom inventory get stores the full catalog.
11
+ EC2_STANDARD_QUOTA_CODE = "L-1216C47A"
12
+ EC2_G_VT_ON_DEMAND_VCPU_QUOTA_CODE = "L-DB2E81BA"
13
+ EC2_STANDARD_SPOT_VCPU_QUOTA_CODE = "L-34B43A08"
14
+
15
+ LAUNCH_RELEVANT_QUOTA_CODES: frozenset[str] = frozenset(
16
+ {
17
+ EC2_STANDARD_QUOTA_CODE,
18
+ EC2_G_VT_ON_DEMAND_VCPU_QUOTA_CODE,
19
+ EC2_STANDARD_SPOT_VCPU_QUOTA_CODE,
20
+ }
21
+ )
22
+
23
+
24
+ class QuotaError(Exception):
25
+ """Validation or normalization failure."""
26
+
27
+ def __init__(self, message: str) -> None:
28
+ self.message = message
29
+ super().__init__(message)
30
+
31
+
32
+ def utc_now_iso() -> str:
33
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
34
+
35
+
36
+ def normalize_service_quota(item: dict[str, Any], *, region: str) -> dict[str, Any]:
37
+ quota = item.get("Quota") if "Quota" in item else item
38
+ if not isinstance(quota, dict):
39
+ raise QuotaError("invalid quota entry")
40
+ code = str(quota.get("QuotaCode") or quota.get("quota_code") or "")
41
+ return {
42
+ "kind": "service_quota",
43
+ "cloud": "aws",
44
+ "region": region,
45
+ "service_code": str(quota.get("ServiceCode") or quota.get("service_code") or "ec2"),
46
+ "quota_code": code,
47
+ "quota_name": str(quota.get("QuotaName") or quota.get("quota_name") or code),
48
+ "value": float(quota.get("Value") if quota.get("Value") is not None else quota.get("value") or 0),
49
+ "usage": float(
50
+ quota.get("Usage")
51
+ if quota.get("Usage") is not None
52
+ else quota.get("usage")
53
+ if quota.get("usage") is not None
54
+ else 0
55
+ ),
56
+ }
57
+
58
+
59
+ def normalize_records_from_aws(
60
+ quotas: list[dict[str, Any]] | None,
61
+ *,
62
+ region: str,
63
+ ) -> list[dict[str, Any]]:
64
+ records: list[dict[str, Any]] = []
65
+ for item in quotas or []:
66
+ if isinstance(item, dict):
67
+ records.append(normalize_service_quota(item, region=region))
68
+ return records
69
+
70
+
71
+ def normalize_azure_vm_usage(item: dict[str, Any], *, location: str) -> dict[str, Any]:
72
+ name_obj = item.get("name")
73
+ code = ""
74
+ localized = ""
75
+ if isinstance(name_obj, dict):
76
+ code = str(name_obj.get("value") or "")
77
+ localized = str(name_obj.get("localizedValue") or "")
78
+ quota_name = str(item.get("localName") or localized or code or "unknown")
79
+ return {
80
+ "kind": "azure_compute_usage",
81
+ "cloud": "azure",
82
+ "region": location,
83
+ "service_code": "Microsoft.Compute",
84
+ "quota_code": code,
85
+ "quota_name": quota_name,
86
+ "value": float(item.get("limit") or 0),
87
+ "usage": float(item.get("currentValue") or 0),
88
+ }
89
+
90
+
91
+ def normalize_records_from_azure_vm_usage(
92
+ rows: list[dict[str, Any]] | None,
93
+ *,
94
+ location: str,
95
+ ) -> list[dict[str, Any]]:
96
+ records: list[dict[str, Any]] = []
97
+ for item in rows or []:
98
+ if isinstance(item, dict):
99
+ records.append(normalize_azure_vm_usage(item, location=location))
100
+ return records
101
+
102
+
103
+ def normalize_records_from_payload(data: dict[str, Any]) -> list[dict[str, Any]]:
104
+ if "records" in data and isinstance(data["records"], list):
105
+ records: list[dict[str, Any]] = []
106
+ for item in data["records"]:
107
+ if not isinstance(item, dict):
108
+ raise QuotaError("invalid record entry in snapshot")
109
+ kind = str(item.get("kind") or "")
110
+ if kind == "service_quota":
111
+ records.append(
112
+ {
113
+ "kind": "service_quota",
114
+ "cloud": str(item.get("cloud") or "aws"),
115
+ "region": str(item.get("region") or "unknown"),
116
+ "service_code": str(item.get("service_code") or "ec2"),
117
+ "quota_code": str(item.get("quota_code") or ""),
118
+ "quota_name": str(
119
+ item.get("quota_name") or item.get("quota_code") or ""
120
+ ),
121
+ "value": float(item.get("value") or 0),
122
+ "usage": float(item.get("usage") or 0),
123
+ }
124
+ )
125
+ continue
126
+ if kind == "azure_compute_usage":
127
+ records.append(
128
+ {
129
+ "kind": "azure_compute_usage",
130
+ "cloud": "azure",
131
+ "region": str(item.get("region") or "unknown"),
132
+ "service_code": str(
133
+ item.get("service_code") or "Microsoft.Compute"
134
+ ),
135
+ "quota_code": str(item.get("quota_code") or ""),
136
+ "quota_name": str(
137
+ item.get("quota_name") or item.get("quota_code") or ""
138
+ ),
139
+ "value": float(item.get("value") or 0),
140
+ "usage": float(item.get("usage") or 0),
141
+ }
142
+ )
143
+ continue
144
+ raise QuotaError(f"unsupported record kind: {kind}")
145
+ return records
146
+ if isinstance(data, list):
147
+ return normalize_records_from_azure_vm_usage(
148
+ [r for r in data if isinstance(r, dict)],
149
+ location="unknown",
150
+ )
151
+ if "Quotas" in data and isinstance(data["Quotas"], list):
152
+ region = str(data.get("region") or data.get("Region") or "us-east-1")
153
+ return normalize_records_from_aws(data["Quotas"], region=region)
154
+ raise QuotaError("unrecognized payer file shape")
155
+
156
+
157
+ def build_snapshot(
158
+ records: list[dict[str, Any]],
159
+ *,
160
+ source: str,
161
+ loaded_as_of: str | None = None,
162
+ ) -> dict[str, Any]:
163
+ ts = loaded_as_of or utc_now_iso()
164
+ return {
165
+ "schema_version": SCHEMA_VERSION,
166
+ "loaded_as_of": ts,
167
+ "source": source,
168
+ "record_count": len(records),
169
+ "records": records,
170
+ }
171
+
172
+
173
+ def count_launch_relevant_records(records: tuple[dict[str, Any], ...] | list[dict[str, Any]]) -> int:
174
+ return sum(
175
+ 1
176
+ for record in records
177
+ if isinstance(record, dict) and str(record.get("quota_code") or "") in LAUNCH_RELEVANT_QUOTA_CODES
178
+ )
@@ -0,0 +1,245 @@
1
+ """Local quota-request outcomes that steer analyze at product_version 7+."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass
7
+ from datetime import datetime, timedelta, timezone
8
+ from pathlib import Path
9
+ from typing import Any, Iterator
10
+
11
+ from maproom.paths import data_subdir
12
+
13
+
14
+ def _quota_ledger_root() -> Path:
15
+ return data_subdir("request_ledger") / "quota-requests"
16
+
17
+
18
+ def _herd_outcomes_path() -> Path:
19
+ return data_subdir("quotas") / "herd_quota_outcomes.json"
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class QuotaOutcomeRecord:
24
+ cloud: str
25
+ region: str
26
+ quota_code: str
27
+ requested_value: float
28
+ outcome: str
29
+ denied_at: datetime | None
30
+ instance_type: str | None = None
31
+ quota_family: str | None = None
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class HerdQuotaEvidence:
36
+ cloud: str
37
+ region: str
38
+ quota_code: str
39
+ min_requested_value: float
40
+ strength: str # "weak" | "strong"
41
+
42
+
43
+ def quota_outcome_ledger_dir() -> Path:
44
+ return _quota_ledger_root()
45
+
46
+
47
+ def _parse_denied_at(raw: object) -> datetime | None:
48
+ if not isinstance(raw, str) or not raw.strip():
49
+ return None
50
+ text = raw.strip()
51
+ if text.endswith("Z"):
52
+ text = text[:-1] + "+00:00"
53
+ try:
54
+ parsed = datetime.fromisoformat(text)
55
+ except ValueError:
56
+ return None
57
+ if parsed.tzinfo is None:
58
+ parsed = parsed.replace(tzinfo=timezone.utc)
59
+ return parsed.astimezone(timezone.utc)
60
+
61
+
62
+ def _coerce_record(raw: dict[str, Any]) -> QuotaOutcomeRecord | None:
63
+ if str(raw.get("kind") or "") not in {"", "quota_request"}:
64
+ return None
65
+ cloud = str(raw.get("cloud") or "").strip().lower()
66
+ region = str(raw.get("region") or "").strip().lower()
67
+ quota_code = str(raw.get("quota_code") or "").strip()
68
+ if not cloud or not region or not quota_code:
69
+ return None
70
+ try:
71
+ requested = float(raw.get("requested_value"))
72
+ except (TypeError, ValueError):
73
+ return None
74
+ outcome = str(raw.get("outcome") or "").strip().lower()
75
+ if outcome != "denied":
76
+ return None
77
+ denied_at = _parse_denied_at(raw.get("denied_at"))
78
+ instance_type = raw.get("instance_type")
79
+ type_name = instance_type.strip() if isinstance(instance_type, str) else None
80
+ family = raw.get("quota_family")
81
+ family_name = family.strip() if isinstance(family, str) else None
82
+ return QuotaOutcomeRecord(
83
+ cloud=cloud,
84
+ region=region,
85
+ quota_code=quota_code,
86
+ requested_value=requested,
87
+ outcome=outcome,
88
+ denied_at=denied_at,
89
+ instance_type=type_name or None,
90
+ quota_family=family_name or None,
91
+ )
92
+
93
+
94
+ def iter_denial_records(*, ledger_dir: Path | None = None) -> Iterator[QuotaOutcomeRecord]:
95
+ root = ledger_dir or _quota_ledger_root()
96
+ if not root.is_dir():
97
+ return
98
+ for path in sorted(root.glob("*.json")):
99
+ try:
100
+ raw = json.loads(path.read_text(encoding="utf-8"))
101
+ except (OSError, json.JSONDecodeError):
102
+ continue
103
+ if not isinstance(raw, dict):
104
+ continue
105
+ record = _coerce_record(raw)
106
+ if record is not None:
107
+ yield record
108
+
109
+
110
+ def local_denial_reason(
111
+ *,
112
+ cloud: str,
113
+ region: str,
114
+ quota_code: str,
115
+ required_value: float,
116
+ instance_type: str | None,
117
+ suppress_days: int,
118
+ now: datetime | None = None,
119
+ ledger_dir: Path | None = None,
120
+ ) -> str | None:
121
+ """Return a suppression reason when a fresh denial blocks this candidate."""
122
+ if suppress_days <= 0:
123
+ return None
124
+ moment = now or datetime.now(timezone.utc)
125
+ cloud_key = cloud.strip().lower()
126
+ region_key = region.strip().lower()
127
+ code = quota_code.strip()
128
+ type_key = (instance_type or "").strip().lower()
129
+ for record in iter_denial_records(ledger_dir=ledger_dir):
130
+ if record.cloud != cloud_key or record.region != region_key:
131
+ continue
132
+ family_match = (
133
+ record.quota_family
134
+ and record.quota_family.strip().lower() == code.lower()
135
+ )
136
+ if record.quota_code != code and not family_match:
137
+ continue
138
+ if record.denied_at is not None:
139
+ age = moment - record.denied_at
140
+ if age > timedelta(days=suppress_days):
141
+ continue
142
+ if type_key and record.instance_type:
143
+ if record.instance_type.lower() != type_key:
144
+ continue
145
+ elif required_value + 1e-9 < record.requested_value:
146
+ continue
147
+ if record.denied_at is not None:
148
+ stamp = record.denied_at.strftime("%Y-%m-%d")
149
+ return f"quota increase denied {stamp}"
150
+ return "quota increase denied"
151
+ return None
152
+
153
+
154
+ def iter_herd_evidence() -> Iterator[HerdQuotaEvidence]:
155
+ herd_path = _herd_outcomes_path()
156
+ if not herd_path.is_file():
157
+ return
158
+ try:
159
+ raw = json.loads(herd_path.read_text(encoding="utf-8"))
160
+ except (OSError, json.JSONDecodeError):
161
+ return
162
+ if not isinstance(raw, dict):
163
+ return
164
+ entries = raw.get("entries")
165
+ if not isinstance(entries, list):
166
+ return
167
+ for item in entries:
168
+ if not isinstance(item, dict):
169
+ continue
170
+ cloud = str(item.get("cloud") or "").strip().lower()
171
+ region = str(item.get("region") or "").strip().lower()
172
+ quota_code = str(item.get("quota_code") or "").strip()
173
+ if not cloud or not region or not quota_code:
174
+ continue
175
+ try:
176
+ minimum = float(item.get("min_requested_value", 0))
177
+ except (TypeError, ValueError):
178
+ minimum = 0.0
179
+ strength = str(item.get("strength") or "weak").strip().lower()
180
+ yield HerdQuotaEvidence(
181
+ cloud=cloud,
182
+ region=region,
183
+ quota_code=quota_code,
184
+ min_requested_value=minimum,
185
+ strength=strength,
186
+ )
187
+
188
+
189
+ def record_quota_denial(
190
+ *,
191
+ cloud: str,
192
+ region: str,
193
+ quota_code: str,
194
+ requested_value: float,
195
+ instance_type: str | None = None,
196
+ quota_family: str | None = None,
197
+ denied_at: datetime | None = None,
198
+ ) -> Path:
199
+ """Persist a denied quota request for local steering at product_version 7+."""
200
+ root = _quota_ledger_root()
201
+ root.mkdir(parents=True, exist_ok=True)
202
+ moment = denied_at or datetime.now(timezone.utc)
203
+ safe_region = region.strip().lower().replace(":", "_")
204
+ safe_code = quota_code.strip().replace("/", "_")
205
+ path = root / f"{cloud.strip().lower()}_{safe_region}_{safe_code}.json"
206
+ body: dict[str, Any] = {
207
+ "kind": "quota_request",
208
+ "cloud": cloud.strip().lower(),
209
+ "region": region.strip().lower(),
210
+ "quota_code": quota_code.strip(),
211
+ "requested_value": float(requested_value),
212
+ "outcome": "denied",
213
+ "denied_at": moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
214
+ }
215
+ if instance_type:
216
+ body["instance_type"] = instance_type.strip()
217
+ if quota_family:
218
+ body["quota_family"] = quota_family.strip()
219
+ path.write_text(json.dumps(body, indent=2), encoding="utf-8")
220
+ return path
221
+
222
+
223
+ def herd_denial_reason(
224
+ *,
225
+ cloud: str,
226
+ region: str,
227
+ quota_code: str,
228
+ required_value: float,
229
+ quota_telemetry: bool,
230
+ ) -> str | None:
231
+ if not quota_telemetry:
232
+ return None
233
+ cloud_key = cloud.strip().lower()
234
+ region_key = region.strip().lower()
235
+ code = quota_code.strip()
236
+ for evidence in iter_herd_evidence():
237
+ if evidence.cloud != cloud_key or evidence.region != region_key:
238
+ continue
239
+ if evidence.quota_code != code:
240
+ continue
241
+ if required_value + 1e-9 < evidence.min_requested_value:
242
+ continue
243
+ if evidence.strength == "strong":
244
+ return "similar or smaller quota requests are usually denied"
245
+ return None