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.
- maproom/__init__.py +14 -0
- maproom/__main__.py +10 -0
- maproom/analyze/__init__.py +1 -0
- maproom/analyze/accel_families.py +45 -0
- maproom/analyze/account_azure_activity.py +260 -0
- maproom/analyze/account_azure_quota_requests.py +177 -0
- maproom/analyze/account_cloudtrail.py +316 -0
- maproom/analyze/account_quota_requests.py +180 -0
- maproom/analyze/analyze_v1_orchestration.py +1194 -0
- maproom/analyze/catalog.py +353 -0
- maproom/analyze/change_detection.py +652 -0
- maproom/analyze/context_client.py +99 -0
- maproom/analyze/context_lookup.py +142 -0
- maproom/analyze/cover_analyze.py +344 -0
- maproom/analyze/cover_client.py +65 -0
- maproom/analyze/cover_lookup.py +242 -0
- maproom/analyze/engine.py +644 -0
- maproom/analyze/fleetfit_endpoints.py +217 -0
- maproom/analyze/fleetfit_policy.py +66 -0
- maproom/analyze/instance_price_analyze.py +221 -0
- maproom/analyze/instance_price_client.py +108 -0
- maproom/analyze/instance_price_lookup.py +60 -0
- maproom/analyze/local_reads.py +484 -0
- maproom/analyze/lookup_http.py +280 -0
- maproom/analyze/metric_format.py +20 -0
- maproom/analyze/migration_method.py +130 -0
- maproom/analyze/move_list.py +93 -0
- maproom/analyze/operator_context.py +156 -0
- maproom/analyze/performance_rank.py +97 -0
- maproom/analyze/primary_recommendation.py +422 -0
- maproom/analyze/provider_comparison.py +401 -0
- maproom/analyze/quota_analyze.py +481 -0
- maproom/analyze/quota_client.py +75 -0
- maproom/analyze/quota_lookup.py +110 -0
- maproom/analyze/quota_outcome_steer.py +105 -0
- maproom/analyze/recommend_batch.py +199 -0
- maproom/analyze/recommend_client.py +362 -0
- maproom/analyze/recommend_share.py +118 -0
- maproom/analyze/recommendation.py +591 -0
- maproom/analyze/reservation_pack.py +883 -0
- maproom/analyze/reservation_read.py +461 -0
- maproom/analyze/safe_analyze.py +1134 -0
- maproom/analyze/safe_move.py +195 -0
- maproom/analyze/safe_moves.py +571 -0
- maproom/analyze/safe_moves_catalog.py +127 -0
- maproom/analyze/safe_moves_client.py +70 -0
- maproom/analyze/series_analyze.py +491 -0
- maproom/analyze/series_client.py +106 -0
- maproom/analyze/series_lookup.py +663 -0
- maproom/analyze/shape.py +254 -0
- maproom/analyze/size_analyze.py +883 -0
- maproom/analyze/size_client.py +81 -0
- maproom/analyze/size_keep.py +409 -0
- maproom/analyze/size_lookup.py +368 -0
- maproom/analyze/specs.py +325 -0
- maproom/analyze/spot_analyze.py +392 -0
- maproom/analyze/spot_client.py +74 -0
- maproom/analyze/spot_lookup.py +213 -0
- maproom/analyze/token_client.py +97 -0
- maproom/analyze/utilization.py +190 -0
- maproom/analyze/workload.py +104 -0
- maproom/analyze/workset.py +762 -0
- maproom/aws_region.py +78 -0
- maproom/cache/__init__.py +1 -0
- maproom/cache/catalog.py +372 -0
- maproom/cache/commands.py +215 -0
- maproom/cache/instances.py +460 -0
- maproom/cli.py +2084 -0
- maproom/cli_argv.py +329 -0
- maproom/cli_floors.py +89 -0
- maproom/cliio/__init__.py +1 -0
- maproom/cliio/registry.py +377 -0
- maproom/cliio/runner.py +489 -0
- maproom/consent/__init__.py +33 -0
- maproom/consent/gate.py +238 -0
- maproom/consent/policy.py +20 -0
- maproom/consent/prompt.py +61 -0
- maproom/consent/service_upload_gate.py +318 -0
- maproom/consent/service_upload_prompt.py +62 -0
- maproom/consent/stdin.py +45 -0
- maproom/consent/storage.py +24 -0
- maproom/consent/write_token.py +29 -0
- maproom/contracts/__init__.py +6 -0
- maproom/contracts/schema_diff.py +119 -0
- maproom/contracts/validate.py +113 -0
- maproom/data/__init__.py +1 -0
- maproom/data/clear.py +76 -0
- maproom/data/commands.py +14 -0
- maproom/doctor/__init__.py +1 -0
- maproom/doctor/aws_session.py +226 -0
- maproom/doctor/checks.py +701 -0
- maproom/doctor/context.py +32 -0
- maproom/doctor/display.py +96 -0
- maproom/doctor/inventory_display.py +377 -0
- maproom/doctor/runner.py +1467 -0
- maproom/errors.py +43 -0
- maproom/exitcodes.py +70 -0
- maproom/inventory/__init__.py +1 -0
- maproom/inventory/account_identity.py +79 -0
- maproom/inventory/accounts.py +155 -0
- maproom/inventory/command.py +961 -0
- maproom/inventory/messages.py +264 -0
- maproom/inventory/reservations_refresh.py +37 -0
- maproom/mock_environment/__init__.py +28 -0
- maproom/mock_environment/load.py +241 -0
- maproom/mock_environment/runner.py +387 -0
- maproom/output/__init__.py +1 -0
- maproom/output/json_envelope.py +241 -0
- maproom/output/redact.py +11 -0
- maproom/output/terminal.py +129 -0
- maproom/parsers.py +284 -0
- maproom/paths.py +105 -0
- maproom/plan/__init__.py +1 -0
- maproom/plan/accept.py +59 -0
- maproom/plan/analysis_context.py +78 -0
- maproom/plan/analyze_selection.py +279 -0
- maproom/plan/commands.py +586 -0
- maproom/plan/current.py +59 -0
- maproom/plan/errors.py +10 -0
- maproom/plan/export.py +36 -0
- maproom/plan/formatting.py +91 -0
- maproom/plan/ids.py +13 -0
- maproom/plan/migration_options.py +75 -0
- maproom/plan/model.py +265 -0
- maproom/plan/names.py +24 -0
- maproom/plan/store.py +193 -0
- maproom/plan/tty.py +34 -0
- maproom/pricing/__init__.py +5 -0
- maproom/pricing/prices.py +119 -0
- maproom/privacy/__init__.py +6 -0
- maproom/privacy/commands.py +159 -0
- maproom/privacy/delete_uploads.py +204 -0
- maproom/privacy/fleetfit_policy.py +125 -0
- maproom/privacy/fleetfit_statement.py +104 -0
- maproom/privacy/format.py +76 -0
- maproom/privacy/manifests.py +342 -0
- maproom/privacy/statement.py +58 -0
- maproom/quotas/__init__.py +21 -0
- maproom/quotas/aws.py +204 -0
- maproom/quotas/azure.py +75 -0
- maproom/quotas/commands.py +240 -0
- maproom/quotas/family_coverage.py +122 -0
- maproom/quotas/fetch.py +124 -0
- maproom/quotas/load.py +41 -0
- maproom/quotas/model.py +178 -0
- maproom/quotas/outcome_ledger.py +245 -0
- maproom/quotas/quota_request_sync.py +221 -0
- maproom/quotas/show.py +73 -0
- maproom/quotas/status.py +206 -0
- maproom/quotas/store.py +161 -0
- maproom/redaction.py +157 -0
- maproom/reference_data/__init__.py +1 -0
- maproom/reference_data/aws/aws_prices.csv +25562 -0
- maproom/reference_data/aws/capabilities.csv +1346 -0
- maproom/reference_data/aws/instance_types.csv +1346 -0
- maproom/reference_data/azure/azure_prices.csv +1 -0
- maproom/reference_data/azure/vm_types.csv +1 -0
- maproom/reference_data/benchmarks/cpu-lscpu-v2-instances.json +27 -0
- maproom/reference_data/benchmarks/safe-moves-v1.json +328 -0
- maproom/reference_data/manifest.json +174 -0
- maproom/reference_data/manifest.py +69 -0
- maproom/reservations/__init__.py +17 -0
- maproom/reservations/aws.py +76 -0
- maproom/reservations/azure.py +36 -0
- maproom/reservations/commands.py +149 -0
- maproom/reservations/load.py +41 -0
- maproom/reservations/model.py +316 -0
- maproom/reservations/show.py +64 -0
- maproom/reservations/status.py +181 -0
- maproom/reservations/store.py +391 -0
- maproom/resources.py +54 -0
- maproom/root_help.py +251 -0
- maproom/saving_plans/__init__.py +15 -0
- maproom/saving_plans/aws.py +73 -0
- maproom/saving_plans/commands.py +122 -0
- maproom/saving_plans/load.py +41 -0
- maproom/saving_plans/model.py +101 -0
- maproom/saving_plans/show.py +64 -0
- maproom/saving_plans/status.py +118 -0
- maproom/saving_plans/store.py +173 -0
- maproom/secret_egress_gate.py +108 -0
- maproom/service/install_id.py +60 -0
- maproom/settings/__init__.py +1 -0
- maproom/settings/defaults.py +73 -0
- maproom/settings/init.py +143 -0
- maproom/settings/model.py +105 -0
- maproom/settings/product_version_change.py +343 -0
- maproom/settings/product_versions.py +68 -0
- maproom/settings/set.py +347 -0
- maproom/settings/show.py +227 -0
- maproom/settings/write.py +273 -0
- maproom/snapshot_time.py +27 -0
- maproom-0.2.0.dist-info/METADATA +263 -0
- maproom-0.2.0.dist-info/RECORD +199 -0
- maproom-0.2.0.dist-info/WHEEL +5 -0
- maproom-0.2.0.dist-info/entry_points.txt +2 -0
- maproom-0.2.0.dist-info/licenses/LICENSE +201 -0
- maproom-0.2.0.dist-info/licenses/NOTICE +72 -0
- maproom-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,484 @@
|
|
|
1
|
+
"""Persist and reuse redacted analyze cloud read payloads under the data root."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextvars
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
import re
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from maproom.inventory.account_identity import (
|
|
15
|
+
AccountIdentityError,
|
|
16
|
+
resolve_aws_account,
|
|
17
|
+
resolve_azure_account,
|
|
18
|
+
)
|
|
19
|
+
from maproom.inventory.accounts import CloudAccount
|
|
20
|
+
from maproom.paths import data_subdir
|
|
21
|
+
from maproom.redaction import redact_tree
|
|
22
|
+
from maproom.settings.model import cache_max_age_hours, snapshot_is_stale
|
|
23
|
+
|
|
24
|
+
_SAFE = re.compile(r"[^A-Za-z0-9_.-]+")
|
|
25
|
+
_ANALYZE_CACHE_REFRESH: contextvars.ContextVar[bool] = contextvars.ContextVar(
|
|
26
|
+
"analyze_cache_refresh",
|
|
27
|
+
default=False,
|
|
28
|
+
)
|
|
29
|
+
_CACHE_HIT_APIS: contextvars.ContextVar[set[str] | None] = contextvars.ContextVar(
|
|
30
|
+
"analyze_cache_hit_apis",
|
|
31
|
+
default=None,
|
|
32
|
+
)
|
|
33
|
+
_ACCOUNT_UNSET = object()
|
|
34
|
+
_ANALYZE_ACCOUNT: contextvars.ContextVar[Any] = contextvars.ContextVar(
|
|
35
|
+
"analyze_cache_account",
|
|
36
|
+
default=_ACCOUNT_UNSET,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def set_analyze_cache_refresh(refresh: bool) -> contextvars.Token[bool]:
|
|
41
|
+
"""Force live cloud reads for the current analyze run when True."""
|
|
42
|
+
return _ANALYZE_CACHE_REFRESH.set(bool(refresh))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def reset_analyze_cache_refresh(token: contextvars.Token[bool]) -> None:
|
|
46
|
+
_ANALYZE_CACHE_REFRESH.reset(token)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def analyze_cache_refresh() -> bool:
|
|
50
|
+
return bool(_ANALYZE_CACHE_REFRESH.get())
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def begin_analyze_cache_hit_tracking() -> contextvars.Token[set[str] | None]:
|
|
54
|
+
"""Start collecting api_ids served from disk for this analyze run."""
|
|
55
|
+
return _CACHE_HIT_APIS.set(set())
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def reset_analyze_cache_hit_tracking(token: contextvars.Token[set[str] | None]) -> None:
|
|
59
|
+
_CACHE_HIT_APIS.reset(token)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def begin_analyze_cache_account(cloud: str, runner: Any | None) -> contextvars.Token[Any]:
|
|
63
|
+
"""Resolve the signed-in account once per analyze run for analyze-reads scoping."""
|
|
64
|
+
account: CloudAccount | None = None
|
|
65
|
+
if runner is not None:
|
|
66
|
+
try:
|
|
67
|
+
if cloud == "aws":
|
|
68
|
+
account = resolve_aws_account(runner)
|
|
69
|
+
elif cloud == "azure":
|
|
70
|
+
account = resolve_azure_account(runner)
|
|
71
|
+
except AccountIdentityError:
|
|
72
|
+
account = None
|
|
73
|
+
return _ANALYZE_ACCOUNT.set(account)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def reset_analyze_cache_account(token: contextvars.Token[Any]) -> None:
|
|
77
|
+
_ANALYZE_ACCOUNT.reset(token)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _analyze_account_scope() -> tuple[CloudAccount | None, bool]:
|
|
81
|
+
value = _ANALYZE_ACCOUNT.get()
|
|
82
|
+
if value is _ACCOUNT_UNSET:
|
|
83
|
+
return None, True
|
|
84
|
+
if isinstance(value, CloudAccount):
|
|
85
|
+
return value, True
|
|
86
|
+
return None, True
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def analyze_cache_hit_apis() -> frozenset[str]:
|
|
90
|
+
hits = _CACHE_HIT_APIS.get()
|
|
91
|
+
if hits is None:
|
|
92
|
+
return frozenset()
|
|
93
|
+
return frozenset(hits)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _record_cache_hit(api_id: str) -> None:
|
|
97
|
+
hits = _CACHE_HIT_APIS.get()
|
|
98
|
+
if hits is not None:
|
|
99
|
+
hits.add(api_id)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _safe_segment(text: str) -> str:
|
|
103
|
+
cleaned = _SAFE.sub("_", (text or "").strip()).strip("._")
|
|
104
|
+
return cleaned or "unknown"
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def window_cache_suffix(
|
|
108
|
+
*,
|
|
109
|
+
start: str | datetime,
|
|
110
|
+
end: str | datetime,
|
|
111
|
+
granularity: str | None = None,
|
|
112
|
+
token: str | None = None,
|
|
113
|
+
label: str | None = None,
|
|
114
|
+
) -> str:
|
|
115
|
+
"""Stable analyze-reads stem token for a query window (and optional pagination)."""
|
|
116
|
+
|
|
117
|
+
def _stamp(value: str | datetime) -> str:
|
|
118
|
+
if isinstance(value, datetime):
|
|
119
|
+
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
120
|
+
return str(value).strip()
|
|
121
|
+
|
|
122
|
+
key = "|".join(
|
|
123
|
+
part
|
|
124
|
+
for part in (
|
|
125
|
+
_stamp(start),
|
|
126
|
+
_stamp(end),
|
|
127
|
+
(granularity or "").strip(),
|
|
128
|
+
(token or "").strip(),
|
|
129
|
+
)
|
|
130
|
+
if part
|
|
131
|
+
)
|
|
132
|
+
parts = [f"w_{hashlib.sha256(key.encode('utf-8')).hexdigest()[:16]}"]
|
|
133
|
+
if label:
|
|
134
|
+
parts.append(_safe_segment(label))
|
|
135
|
+
return "_".join(parts)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _payload_exit_code(raw: dict[str, Any]) -> int | None:
|
|
139
|
+
if str(raw.get("kind") or "") == "analyze_read" and isinstance(raw.get("payload"), dict):
|
|
140
|
+
payload = raw["payload"]
|
|
141
|
+
else:
|
|
142
|
+
payload = raw
|
|
143
|
+
if not isinstance(payload, dict):
|
|
144
|
+
return None
|
|
145
|
+
try:
|
|
146
|
+
return int(payload.get("exit_code", 0) or 0)
|
|
147
|
+
except (TypeError, ValueError):
|
|
148
|
+
return None
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _document_is_cacheable(document: dict[str, Any]) -> bool:
|
|
152
|
+
try:
|
|
153
|
+
code = int(document.get("exit_code", 0) or 0)
|
|
154
|
+
except (TypeError, ValueError):
|
|
155
|
+
return False
|
|
156
|
+
return code == 0
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def analyze_read_path(
|
|
160
|
+
*,
|
|
161
|
+
api_id: str,
|
|
162
|
+
region: str = "",
|
|
163
|
+
instance_id: str | None = None,
|
|
164
|
+
suffix: str | None = None,
|
|
165
|
+
account: CloudAccount | None = None,
|
|
166
|
+
) -> Path:
|
|
167
|
+
"""Return the on-disk path for one analyze-reads envelope.
|
|
168
|
+
|
|
169
|
+
With ``account`` set: ``analyze-reads/<account>/<region>/…/{api_id}.json``.
|
|
170
|
+
With ``account`` None: unscoped ``analyze-reads/<region>/…/{api_id}.json``
|
|
171
|
+
(no account folder). Fail-closed callers must refuse load/persist when the
|
|
172
|
+
signed-in account is unset or unknown so leftover unscoped files are not
|
|
173
|
+
treated as hits.
|
|
174
|
+
"""
|
|
175
|
+
root = data_subdir("analyze-reads")
|
|
176
|
+
parts: list[str] = []
|
|
177
|
+
if account is not None:
|
|
178
|
+
parts.append(account.folder_name())
|
|
179
|
+
parts.append(_safe_segment(region or "global"))
|
|
180
|
+
if instance_id:
|
|
181
|
+
parts.append(_safe_segment(instance_id))
|
|
182
|
+
stem = _safe_segment(api_id)
|
|
183
|
+
if suffix:
|
|
184
|
+
stem = f"{stem}_{_safe_segment(suffix)}"
|
|
185
|
+
return root.joinpath(*parts) / f"{stem}.json"
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def persist_analyze_read(
|
|
189
|
+
*,
|
|
190
|
+
api_id: str,
|
|
191
|
+
payload: dict[str, Any],
|
|
192
|
+
region: str = "",
|
|
193
|
+
instance_id: str | None = None,
|
|
194
|
+
suffix: str | None = None,
|
|
195
|
+
cli_version: str | None = None,
|
|
196
|
+
loaded_as_of: str | None = None,
|
|
197
|
+
account: CloudAccount | None = None,
|
|
198
|
+
) -> Path:
|
|
199
|
+
if not _document_is_cacheable(payload):
|
|
200
|
+
return analyze_read_path(
|
|
201
|
+
api_id=api_id,
|
|
202
|
+
region=region,
|
|
203
|
+
instance_id=instance_id,
|
|
204
|
+
suffix=suffix,
|
|
205
|
+
account=account,
|
|
206
|
+
)
|
|
207
|
+
path = analyze_read_path(
|
|
208
|
+
api_id=api_id,
|
|
209
|
+
region=region,
|
|
210
|
+
instance_id=instance_id,
|
|
211
|
+
suffix=suffix,
|
|
212
|
+
account=account,
|
|
213
|
+
)
|
|
214
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
215
|
+
as_of = loaded_as_of or datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
216
|
+
envelope: dict[str, Any] = {
|
|
217
|
+
"schema_version": 1,
|
|
218
|
+
"kind": "analyze_read",
|
|
219
|
+
"api_id": api_id,
|
|
220
|
+
"region": (region or "").strip(),
|
|
221
|
+
"loaded_as_of": as_of,
|
|
222
|
+
"payload": redact_tree(payload),
|
|
223
|
+
}
|
|
224
|
+
if instance_id:
|
|
225
|
+
envelope["instance_id"] = instance_id
|
|
226
|
+
if suffix:
|
|
227
|
+
envelope["suffix"] = suffix
|
|
228
|
+
if cli_version:
|
|
229
|
+
envelope["cli_version"] = cli_version
|
|
230
|
+
if account is not None:
|
|
231
|
+
envelope["account_id"] = account.account_id
|
|
232
|
+
path.write_text(json.dumps(envelope, indent=2), encoding="utf-8")
|
|
233
|
+
return path
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _unwrap_envelope(raw: dict[str, Any]) -> tuple[dict[str, Any], str | None, str | None]:
|
|
237
|
+
"""Return (payload, loaded_as_of, cli_version). Legacy raw payloads have no stamp."""
|
|
238
|
+
if str(raw.get("kind") or "") == "analyze_read" and isinstance(raw.get("payload"), dict):
|
|
239
|
+
loaded = str(raw.get("loaded_as_of") or "").strip() or None
|
|
240
|
+
version = raw.get("cli_version")
|
|
241
|
+
cli_version = str(version).strip() if isinstance(version, str) and version.strip() else None
|
|
242
|
+
return raw["payload"], loaded, cli_version
|
|
243
|
+
return raw, None, None
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def load_fresh_analyze_read(
|
|
247
|
+
*,
|
|
248
|
+
api_id: str,
|
|
249
|
+
region: str = "",
|
|
250
|
+
instance_id: str | None = None,
|
|
251
|
+
suffix: str | None = None,
|
|
252
|
+
max_age_hours: int | None = None,
|
|
253
|
+
now: datetime | None = None,
|
|
254
|
+
refresh: bool | None = None,
|
|
255
|
+
account: CloudAccount | None = None,
|
|
256
|
+
require_account: bool = False,
|
|
257
|
+
) -> dict[str, Any] | None:
|
|
258
|
+
"""Return a fresh cached payload document, or None when the cloud should be called."""
|
|
259
|
+
if refresh if refresh is not None else analyze_cache_refresh():
|
|
260
|
+
return None
|
|
261
|
+
if require_account and account is None:
|
|
262
|
+
return None
|
|
263
|
+
hours = cache_max_age_hours() if max_age_hours is None else max_age_hours
|
|
264
|
+
if hours <= 0:
|
|
265
|
+
return None
|
|
266
|
+
path = analyze_read_path(
|
|
267
|
+
api_id=api_id,
|
|
268
|
+
region=region,
|
|
269
|
+
instance_id=instance_id,
|
|
270
|
+
suffix=suffix,
|
|
271
|
+
account=account,
|
|
272
|
+
)
|
|
273
|
+
if not path.is_file():
|
|
274
|
+
return None
|
|
275
|
+
try:
|
|
276
|
+
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
277
|
+
except (OSError, json.JSONDecodeError):
|
|
278
|
+
return None
|
|
279
|
+
if not isinstance(raw, dict):
|
|
280
|
+
return None
|
|
281
|
+
exit_code = _payload_exit_code(raw)
|
|
282
|
+
if exit_code is not None and exit_code != 0:
|
|
283
|
+
return None
|
|
284
|
+
if account is not None:
|
|
285
|
+
stored = str(raw.get("account_id") or "").strip()
|
|
286
|
+
if stored and stored != account.account_id.strip():
|
|
287
|
+
return None
|
|
288
|
+
payload, loaded_as_of, cli_version = _unwrap_envelope(raw)
|
|
289
|
+
if loaded_as_of is None:
|
|
290
|
+
return None
|
|
291
|
+
if snapshot_is_stale(loaded_as_of, hours, now=now):
|
|
292
|
+
return None
|
|
293
|
+
if not _document_is_cacheable(payload if isinstance(payload, dict) else {}):
|
|
294
|
+
return None
|
|
295
|
+
document = dict(payload)
|
|
296
|
+
if cli_version and "cli_version" not in document:
|
|
297
|
+
document["_cached_cli_version"] = cli_version
|
|
298
|
+
_record_cache_hit(api_id)
|
|
299
|
+
return document
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def document_from_cli_result(result: Any) -> dict[str, Any]:
|
|
303
|
+
"""Normalize a CliResult into the analyze-reads payload shape."""
|
|
304
|
+
if isinstance(result, dict):
|
|
305
|
+
return result
|
|
306
|
+
stdout = getattr(result, "stdout", "") or ""
|
|
307
|
+
payload: dict[str, Any] = {
|
|
308
|
+
"exit_code": int(getattr(result, "exit_code", 0) or 0),
|
|
309
|
+
"stdout_json": {},
|
|
310
|
+
"stderr": getattr(result, "stderr", "") or "",
|
|
311
|
+
}
|
|
312
|
+
if stdout.strip():
|
|
313
|
+
try:
|
|
314
|
+
payload["stdout_json"] = json.loads(stdout)
|
|
315
|
+
except json.JSONDecodeError:
|
|
316
|
+
payload["stdout_json"] = {"_raw_stdout": stdout}
|
|
317
|
+
return payload
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
@dataclass(frozen=True)
|
|
321
|
+
class CachedCliResult:
|
|
322
|
+
"""Duck-typed CliResult rebuilt from a cached analyze-read payload."""
|
|
323
|
+
|
|
324
|
+
argv: list[str]
|
|
325
|
+
exit_code: int
|
|
326
|
+
stdout: str
|
|
327
|
+
stderr: str
|
|
328
|
+
duration_ms: int = 0
|
|
329
|
+
cloud: str = "aws"
|
|
330
|
+
cli_path: str = ""
|
|
331
|
+
cli_version: str | None = None
|
|
332
|
+
from_cache: bool = True
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def cli_result_from_document(
|
|
336
|
+
document: dict[str, Any],
|
|
337
|
+
*,
|
|
338
|
+
argv: list[str] | None = None,
|
|
339
|
+
cloud: str = "aws",
|
|
340
|
+
cli_version: str | None = None,
|
|
341
|
+
) -> CachedCliResult:
|
|
342
|
+
stdout_json = document.get("stdout_json")
|
|
343
|
+
if isinstance(stdout_json, dict) and "_raw_stdout" in stdout_json and len(stdout_json) == 1:
|
|
344
|
+
stdout = str(stdout_json.get("_raw_stdout") or "")
|
|
345
|
+
elif stdout_json is None:
|
|
346
|
+
stdout = ""
|
|
347
|
+
else:
|
|
348
|
+
stdout = json.dumps(stdout_json, ensure_ascii=False)
|
|
349
|
+
version = cli_version
|
|
350
|
+
if version is None:
|
|
351
|
+
cached = document.get("_cached_cli_version")
|
|
352
|
+
if isinstance(cached, str) and cached.strip():
|
|
353
|
+
version = cached.strip()
|
|
354
|
+
return CachedCliResult(
|
|
355
|
+
argv=list(argv or []),
|
|
356
|
+
exit_code=int(document.get("exit_code", 0) or 0),
|
|
357
|
+
stdout=stdout,
|
|
358
|
+
stderr=str(document.get("stderr") or ""),
|
|
359
|
+
cloud=cloud,
|
|
360
|
+
cli_version=version,
|
|
361
|
+
from_cache=True,
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def run_cached_analyze_read(
|
|
366
|
+
runner: Any,
|
|
367
|
+
cloud: str,
|
|
368
|
+
argv: list[str],
|
|
369
|
+
*,
|
|
370
|
+
api_id: str,
|
|
371
|
+
region: str = "",
|
|
372
|
+
instance_id: str | None = None,
|
|
373
|
+
suffix: str | None = None,
|
|
374
|
+
refresh: bool | None = None,
|
|
375
|
+
max_age_hours: int | None = None,
|
|
376
|
+
now: datetime | None = None,
|
|
377
|
+
**run_kwargs: Any,
|
|
378
|
+
) -> Any:
|
|
379
|
+
"""Return a CliResult from a fresh analyze-read cache hit, or run and persist."""
|
|
380
|
+
account, require_account = _analyze_account_scope()
|
|
381
|
+
cached = load_fresh_analyze_read(
|
|
382
|
+
api_id=api_id,
|
|
383
|
+
region=region,
|
|
384
|
+
instance_id=instance_id,
|
|
385
|
+
suffix=suffix,
|
|
386
|
+
max_age_hours=max_age_hours,
|
|
387
|
+
now=now,
|
|
388
|
+
refresh=refresh,
|
|
389
|
+
account=account,
|
|
390
|
+
require_account=require_account,
|
|
391
|
+
)
|
|
392
|
+
if cached is not None:
|
|
393
|
+
return cli_result_from_document(cached, argv=list(argv), cloud=cloud)
|
|
394
|
+
|
|
395
|
+
result = runner.run(cloud, argv, api_id=api_id, **run_kwargs)
|
|
396
|
+
document = document_from_cli_result(result)
|
|
397
|
+
if _document_is_cacheable(document) and (not require_account or account is not None):
|
|
398
|
+
persist_analyze_read(
|
|
399
|
+
api_id=api_id,
|
|
400
|
+
payload=document,
|
|
401
|
+
region=region,
|
|
402
|
+
instance_id=instance_id,
|
|
403
|
+
suffix=suffix,
|
|
404
|
+
cli_version=getattr(result, "cli_version", None),
|
|
405
|
+
account=account,
|
|
406
|
+
)
|
|
407
|
+
return result
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def _envelope_reuse_state(path: Path, max_age_hours: int, *, now: datetime) -> str | None:
|
|
411
|
+
try:
|
|
412
|
+
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
413
|
+
except (OSError, json.JSONDecodeError):
|
|
414
|
+
return None
|
|
415
|
+
if not isinstance(raw, dict):
|
|
416
|
+
return None
|
|
417
|
+
exit_code = _payload_exit_code(raw)
|
|
418
|
+
if exit_code is not None and exit_code != 0:
|
|
419
|
+
return None
|
|
420
|
+
payload, loaded_as_of, _ = _unwrap_envelope(raw)
|
|
421
|
+
if loaded_as_of is None:
|
|
422
|
+
return None
|
|
423
|
+
if not _document_is_cacheable(payload if isinstance(payload, dict) else {}):
|
|
424
|
+
return None
|
|
425
|
+
if snapshot_is_stale(loaded_as_of, max_age_hours, now=now):
|
|
426
|
+
return "stale"
|
|
427
|
+
return "fresh"
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def analyze_reads_cache_state(*, max_age_hours: int, now: datetime | None = None) -> str:
|
|
431
|
+
"""Return ``fresh``, ``stale``, or ``absent`` for persisted analyze-read envelopes."""
|
|
432
|
+
if max_age_hours <= 0:
|
|
433
|
+
return "absent"
|
|
434
|
+
account, _require = _analyze_account_scope()
|
|
435
|
+
root = data_subdir("analyze-reads")
|
|
436
|
+
if not root.is_dir():
|
|
437
|
+
return "absent"
|
|
438
|
+
if account is None:
|
|
439
|
+
return "absent"
|
|
440
|
+
moment = now or datetime.now(timezone.utc)
|
|
441
|
+
saw_fresh = False
|
|
442
|
+
saw_stale = False
|
|
443
|
+
bases: list[Path] = [root / account.folder_name()]
|
|
444
|
+
for base in bases:
|
|
445
|
+
if not base.is_dir():
|
|
446
|
+
continue
|
|
447
|
+
for path in base.rglob("*.json"):
|
|
448
|
+
state = _envelope_reuse_state(path, max_age_hours, now=moment)
|
|
449
|
+
if state == "fresh":
|
|
450
|
+
saw_fresh = True
|
|
451
|
+
elif state == "stale":
|
|
452
|
+
saw_stale = True
|
|
453
|
+
if saw_fresh:
|
|
454
|
+
return "fresh"
|
|
455
|
+
if saw_stale:
|
|
456
|
+
return "stale"
|
|
457
|
+
return "absent"
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
def interactive_local_cloud_reads_notice(
|
|
461
|
+
cloud: str,
|
|
462
|
+
region: str | None,
|
|
463
|
+
*,
|
|
464
|
+
max_age_hours: int,
|
|
465
|
+
runner: Any | None = None,
|
|
466
|
+
listing_state: str | None = None,
|
|
467
|
+
) -> str | None:
|
|
468
|
+
"""One interactive line about local cloud-read cache, or None when no cache exists."""
|
|
469
|
+
from maproom.cache.instances import listing_cache_state
|
|
470
|
+
|
|
471
|
+
listing = listing_state or listing_cache_state(
|
|
472
|
+
cloud, region, max_age_hours=max_age_hours, runner=runner
|
|
473
|
+
)
|
|
474
|
+
reads = analyze_reads_cache_state(max_age_hours=max_age_hours)
|
|
475
|
+
states = {listing, reads}
|
|
476
|
+
if "fresh" in states:
|
|
477
|
+
return "Reusing cached local cloud reads."
|
|
478
|
+
if "stale" in states:
|
|
479
|
+
age_phrase = "an hour" if max_age_hours == 1 else f"{max_age_hours} hours"
|
|
480
|
+
return (
|
|
481
|
+
"Local cloud reads cache is not being used because it is "
|
|
482
|
+
f"older than {age_phrase}."
|
|
483
|
+
)
|
|
484
|
+
return None
|