"""Compose the configured live material polling application.""" import math import os import tempfile from hashlib import sha256 from pathlib import Path from urllib.parse import urlsplit from production_analytics.calculations.config import MaterialCalculationConfig, finite_number from production_analytics.enlyze.exploration import ( ConfigurationError, ExplorationClient, ExplorationSettings, load_secret_file, ) from production_analytics.enlyze.gateway import EnlyzeApiGateway from production_analytics.erp import ErpSettings, ErpWorkplaceStatusGateway from production_analytics.service.material_context import ErpNominalWidthProvider from production_analytics.service.material_polling import ( MaterialPollingService, MaterialPollingState, ) from production_analytics.service.material_runner import MaterialPollingRunner, MaterialStateError from production_analytics.service.material_state_store import JsonMaterialStateStore from production_analytics.service.postgres_material import ( PostgresMaterialSnapshotWriter, PostgresSettings, ) from production_analytics.service.postgres_material_application import ( PostgresMaterialApplicationWriter, ) class _ReportingStateStore: def __init__(self, store: JsonMaterialStateStore) -> None: self.store = store def load(self, machine_id: str, production_order: str) -> MaterialPollingState | None: try: return self.store.load(machine_id, production_order) except Exception as exc: raise MaterialStateError(f"state loading: {type(exc).__name__}") from exc def save( self, machine_id: str, production_order: str, state: MaterialPollingState, ) -> None: try: self.store.save(machine_id, production_order, state) except Exception as exc: raise MaterialStateError(f"state saving: {type(exc).__name__}") from exc def build_material_runner( calculation: MaterialCalculationConfig, *, poll_interval_seconds: float, state_directory: Path, secrets_file: Path, erp_secrets_file: Path = Path("secrets/erp.env"), ) -> MaterialPollingRunner: finite_number(poll_interval_seconds, "poll interval", positive=True) environment = dict(os.environ) environment.update(load_secret_file(secrets_file)) settings = ExplorationSettings.from_environment(environment) parsed = urlsplit(settings.base_url) if parsed.scheme not in {"http", "https"} or not parsed.hostname or parsed.username: raise ConfigurationError( "ENLYZE_BASE_URL must be an HTTP(S) server URL without credentials" ) if not math.isfinite(settings.timeout_seconds): raise ConfigurationError("ENLYZE_HTTP_TIMEOUT_SECONDS must be finite") try: state_directory.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryFile(dir=state_directory): pass except OSError as exc: raise ConfigurationError( f"State directory startup check failed: {type(exc).__name__}" ) from exc postgres_settings = PostgresSettings.from_environment(environment) source_options = {} if calculation.source_mode in { "area_application", "rotational_discharge", "linear_signal_discharge", }: source_options = dict( application_variable_ids=calculation.application_signal_refs, nominal_width_provider=ErpNominalWidthProvider( ErpWorkplaceStatusGateway(ErpSettings.from_secret_file(erp_secrets_file)), workplace=calculation.erp_workplace, format_template=calculation.production_order_format, fallback_nominal_width_m=calculation.fallback_nominal_width_m, ), ) if calculation.source_mode == "linear_signal_discharge": source_options["specific_discharge_kg_per_signal_unit_m"] = ( calculation.specific_discharge_kg_per_signal_unit_m ) # Legacy runners retain their checkpoints; new calibrated sources are isolated. state_directory = state_directory / sha256(calculation.id.encode("utf-8")).hexdigest() if calculation.source_mode == "rotational_discharge": source_options.pop("application_variable_ids") source_options.update( rotational_speed_variable_ids=calculation.rotational_speed_signal_refs, specific_discharge_kg_per_rev_m=calculation.specific_discharge_kg_per_rev_m, ) if calculation.process_application_calculation_id is not None: source_options.update( process_application_calculation_id=calculation.process_application_calculation_id, application_writer=PostgresMaterialApplicationWriter(postgres_settings), ) service = MaterialPollingService( gateway=EnlyzeApiGateway(ExplorationClient(settings)), state_store=_ReportingStateStore(JsonMaterialStateStore(state_directory)), machine_id=calculation.machine_ref, rate_variable_id=calculation.rate_signal_ref, gate_variable_id=calculation.gate_signal_ref, gate_threshold=calculation.gate_threshold, max_sample_gap_seconds=calculation.max_sample_gap_seconds, **source_options, ) return MaterialPollingRunner( service, calculation_id=calculation.id, snapshot_writer=PostgresMaterialSnapshotWriter(postgres_settings), machine_id=calculation.machine_ref, poll_interval_seconds=poll_interval_seconds, )