""" Shared TileServer configuration loader. """ import os from pathlib import Path import yaml DEFAULT_ENTRY = "node_modules/tileserver-gl-light/src/main.js" DEFAULT_CONFIG = "config.json" DEFAULT_STYLE = "server-map" def load_tileserver_config(project_root): project_root = Path(project_root).expanduser().resolve() config_file = project_root / "config" / "config.yaml" try: with config_file.open("r", encoding="utf-8") as file: application_config = yaml.safe_load(file) or {} except (OSError, yaml.YAMLError) as error: raise RuntimeError( f"Не удалось загрузить конфигурацию {config_file}: {error}" ) from error if not isinstance(application_config, dict): raise RuntimeError( "Корень config/config.yaml должен быть YAML-объектом." ) section = application_config.get("tileserver", {}) if not isinstance(section, dict): raise RuntimeError( "Раздел tileserver в config/config.yaml должен быть YAML-объектом." ) directory_value = os.environ.get( "WIFI_GPS_TILESERVER_DIR", section.get("directory", "map-server") ) directory = Path(directory_value).expanduser() if "WIFI_GPS_TILESERVER_DIR" not in os.environ and not directory.is_absolute(): directory = project_root / directory directory = directory.resolve() entry_from_environment = "WIFI_GPS_TILESERVER_ENTRY" in os.environ entry_value = os.environ.get( "WIFI_GPS_TILESERVER_ENTRY", section.get("entry", DEFAULT_ENTRY) ) entry = Path(entry_value).expanduser() if not entry.is_absolute() and not entry_from_environment: entry = directory / entry config_value = os.environ.get( "WIFI_GPS_TILESERVER_CONFIG", section.get("config", DEFAULT_CONFIG) ) config = Path(config_value).expanduser() config_path = config if config.is_absolute() else directory / config host = str(section.get("host", "127.0.0.1")).strip() try: port = int( os.environ.get( "WIFI_GPS_TILESERVER_PORT", section.get("port", 8080) ) ) except (TypeError, ValueError) as error: raise RuntimeError("Некорректный порт TileServer.") from error if not host: raise RuntimeError("Не задан host для TileServer.") if not 1 <= port <= 65535: raise RuntimeError(f"Некорректный порт TileServer: {port}") style = str(section.get("style", DEFAULT_STYLE)).strip().strip("/") if not style: raise RuntimeError("Не задан style для TileServer.") return { "host": host, "port": port, "directory": directory, "entry": entry, "config": str(config), "config_path": config_path, "style": style, "style_url": ( f"http://{host}:{port}/styles/{style}/style.json" ), }