from pathlib import Path import sys PROJECT_ROOT = Path(__file__).resolve().parents[2] if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) from knoe.core.cluster_storage_browser import ( ClusterStorageRequest, QuotaMetricHeadroom, RegionLatencyResult, RegionQuotaSnapshot, StaticQuotaProvider, build_cluster_storage_browser_result, evaluate_region_feasibility, ) class RecordingLatencyProvider: def __init__(self, values: dict[str, RegionLatencyResult]): self.values = dict(values) self.calls: list[list[str]] = [] def probe(self, regions: list[str]) -> dict[str, RegionLatencyResult]: self.calls.append(list(regions)) return {r: self.values[r] for r in regions if r in self.values} def _quota(region: str, premium_headroom: float, standard_headroom: float) -> RegionQuotaSnapshot: return RegionQuotaSnapshot( region=region, premium=QuotaMetricHeadroom( metric="SSD_TOTAL_GB", limit_gb=premium_headroom + 100.0, usage_gb=100.0, ), standard=QuotaMetricHeadroom( metric="DISKS_TOTAL_GB", limit_gb=standard_headroom + 100.0, usage_gb=100.0, ), ) def test_browser_filters_timezone_probes_only_viable_and_ranks_by_feasibility_then_latency(): quotas = { "us-central1": _quota("us-central1", premium_headroom=200.0, standard_headroom=20.0), "us-east1": _quota("us-east1", premium_headroom=10.0, standard_headroom=180.0), "southamerica-east1": _quota("southamerica-east1", premium_headroom=5.0, standard_headroom=5.0), } quota_provider = StaticQuotaProvider(quotas) latency_provider = RecordingLatencyProvider( { "us-central1": RegionLatencyResult(region="us-central1", latency_ms=40.0, ok=True), "us-east1": RegionLatencyResult(region="us-east1", latency_ms=15.0, ok=True), } ) result = build_cluster_storage_browser_result( project_id="p-1", requested=ClusterStorageRequest(pgdata_gb=100.0, wal_gb=25.0), available_regions=["us-central1", "us-east1", "southamerica-east1", "europe-west1"], timezone_group="americas", quota_provider=quota_provider, latency_provider=latency_provider, ) assert latency_provider.calls == [["us-central1", "us-east1"]] assert [c.feasibility.region for c in result.candidates] == [ "us-central1", "us-east1", "southamerica-east1", ] assert result.candidates[0].feasibility.default_pgdata_class == "premium-rwo" assert result.candidates[1].feasibility.default_pgdata_class == "standard-rwo" assert result.candidates[2].latency_ms is None def test_feasibility_defaults_to_premium_when_quota_is_missing(): f = evaluate_region_feasibility( region="us-west1", timezone_group="americas", quota=None, requested=ClusterStorageRequest(pgdata_gb=80.0, wal_gb=20.0), ) assert f.can_premium is False assert f.can_standard is False assert f.default_pgdata_class == "premium-rwo" assert "quota-unavailable" in f.notes