refactor: add paths, services ctx, and extract models to own files

This commit is contained in:
Benjamin Labrecque
2026-07-22 12:04:55 +02:00
parent e324e3abed
commit 7e690a907e
16 changed files with 474 additions and 524 deletions
+20
View File
@@ -0,0 +1,20 @@
# Order matters to avoid circular imports
# ruff: isort: off
from .service import Service
from .iocs_overview import IocsOverview
from .master_hla_names import MasterHLANames
from .master_ioc_subs import MasterIocSubs
from .service_manager_ui import ServiceManagerUI
from .service_registry import ServiceRegistry
from .context import ServicesContext
# ruff: isort: on
__all__ = [
"ServicesContext",
"IocsOverview",
"MasterHLANames",
"MasterIocSubs",
"Service",
"ServiceManagerUI",
"ServiceRegistry",
]
+54
View File
@@ -0,0 +1,54 @@
from typing import Any, Dict
from pydantic import BaseModel
from config.paths import Paths
from models import IocsOverview, MasterHLANames, MasterIocSubs, ServiceManagerUI, ServiceRegistry
class ServicesContext(BaseModel):
paths: Paths
service_registry: ServiceRegistry
master_hla_names: MasterHLANames
iocs_overview: IocsOverview
master_ioc_subs: MasterIocSubs
service_manager_ui: ServiceManagerUI
@classmethod
def load_from_disk(cls, paths: Paths) -> "ServicesContext":
return cls(
paths=paths,
service_registry=ServiceRegistry.read_from_file(paths.service_registry_file),
master_hla_names=MasterHLANames.read_from_file(paths.master_hla_names_file),
iocs_overview=IocsOverview.read_from_file(paths.iocs_overview_filename),
master_ioc_subs=MasterIocSubs.read_from_file(paths.master_ioc_subs_file),
service_manager_ui=ServiceManagerUI.read_from_file(paths.service_manager_ui_file),
)
def snapshot(self) -> "ServicesContext":
"""Creates an in-memory backup of all configs for rollback."""
return ServicesContext(
paths=self.paths,
service_registry=self.service_registry.model_copy(),
master_hla_names=self.master_hla_names.model_copy(),
iocs_overview=self.iocs_overview.model_copy(),
master_ioc_subs=self.master_ioc_subs.model_copy(),
service_manager_ui=self.service_manager_ui.model_copy(),
)
def restore_snapshot(self, snapshot: Dict[str, Any]) -> None:
"""Restores state from a backup dictionary."""
self.service_registry = snapshot["service_registry"]
self.master_hla_names = snapshot["master_hla_names"]
self.iocs_overview = snapshot["iocs_overview"]
self.master_ioc_subs = snapshot["master_ioc_subs"]
self.service_manager_ui = snapshot["service_manager_ui"]
def write_all(self) -> None:
"""Persists all modified objects to disk."""
self.service_registry.write_to_file(self.paths.service_registry_file)
self.master_hla_names.write_to_file(self.paths.master_hla_names_file)
self.iocs_overview.write_to_file(self.paths.iocs_overview_filename)
self.master_ioc_subs.write_to_file(self.paths.master_ioc_subs_file)
self.service_manager_ui.write_to_file(self.paths.service_manager_ui_file)
+29
View File
@@ -0,0 +1,29 @@
from pathlib import Path
from pydantic import BaseModel
from models import Service
class IocsOverview(BaseModel):
content: str
@classmethod
def read_from_file(cls, path: Path) -> "IocsOverview":
with open(path, "r", encoding="utf-8") as f:
s = f.read()
return IocsOverview(content=s)
def add_ioc(self, service: Service, description: str):
new_row = f"| AGEBD-CPCL-{service.name_upper} | {description} |\n"
# Ensuring it starts on a clean new line if the file didn't end with one
if not self.content.endswith("\n"):
self.content += "\n"
self.content += new_row
def write_to_file(self, path: Path):
with open(path, "w") as f:
f.write(self.content)
+23
View File
@@ -0,0 +1,23 @@
from pathlib import Path
import yaml
from pydantic import BaseModel
class MasterHLANames(BaseModel):
hla_apps: list[str]
@classmethod
def read_from_file(cls, path: Path) -> "MasterHLANames":
with open(path) as f:
d = yaml.safe_load(f)
hla_names = MasterHLANames.model_validate(d)
return hla_names
def add_hla_name(self, name: str):
self.hla_apps.append(name)
def write_to_file(self, path: Path) -> None:
with open(path, "w") as f:
yaml.safe_dump(self.model_dump(), f, indent=4)
+45
View File
@@ -0,0 +1,45 @@
import re
from pathlib import Path
from pydantic import BaseModel
class MasterIocSubs(BaseModel):
content: str
@classmethod
def read_from_file(cls, path: Path) -> "MasterIocSubs":
with open(path) as f:
file_content = f.read()
return MasterIocSubs(content=file_content)
def update_content(
self,
service_name: str,
starton: str = "0", # TODO: ok defaults?
autooff: str = "0", # TODO: ok defaults?
):
"""
Parses the configuration text and appends a new row before the closing bracket.
"""
quoted_service = f'"{service_name}"'
new_row = f' {{ "{{{{ agebd_env }}}}", {quoted_service:<22} , "{starton}", "{autooff}" }}'
# Use regex to find the last closing curly brace of the configuration block
# This targets the line that contains only a lone closing brace, optional spaces, and maybe a comma/semicolon.
pattern = r"(\s*\n\s*\}(?:;|,)?\s*$)"
if re.search(pattern, self.content, re.MULTILINE):
# Insert our new row right before that closing brace line
self.content = re.sub(
pattern, f"\n{new_row}\\1", self.content, count=1, flags=re.MULTILINE
)
else:
raise ValueError(
"Could not locate the closing structure format '}' inside the configuration."
)
def write_to_file(self, path: Path) -> None:
with open(path, "w") as f:
f.write(self.content)
+40
View File
@@ -0,0 +1,40 @@
import re
from pydantic import BaseModel, field_validator
from core.enums import ServiceStatus
class Service(BaseModel):
name: str
ioc_port: int
status: ServiceStatus
@property
def name_upper(self):
return self.name.upper()
@property
def name_lower(self):
return self.name.lower()
@property
def name_lower_underscores(self):
return self.name.replace("-", "_").lower()
@property
def dir_name(self):
return self.name.lower()
def to_dict(self):
return {"name": self.name_lower, "ioc_port": self.ioc_port, "status": str(self.status)}
class Config:
use_enum_values = True
@field_validator("name")
@classmethod
def validate_name_chars(cls, value: str) -> str:
if not re.match(r"^[a-z0-9-]+$", value):
raise ValueError("name can only contain lowercase letters, numbers, and dashes")
return value
+136
View File
@@ -0,0 +1,136 @@
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Any
from pydantic import BaseModel, ConfigDict
from models import Service
class ServiceManagerUI(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
tree: Any
@classmethod
def read_from_file(cls, path: Path) -> "ServiceManagerUI":
tree = ET.parse(path)
return ServiceManagerUI(tree=tree)
def update_xml(self, service: Service, ui_name: str, ui_filename: str) -> None:
num_macro_elements = self._update_macro(
service=service, ui_name=ui_name, ui_filename=ui_filename
)
self._update_heights(num_macro_elements=num_macro_elements)
def _update_macro(self, service: Service, ui_name: str, ui_filename: str) -> int:
new_macro_element = _ServiceManagerUIMacroElement(
service_name_upper=service.name_upper, ui_name=ui_name, ui_filename=ui_filename
)
num_macro_elements = None
root = self.tree.getroot()
for widget in root.iter("widget"):
if widget.get("class") == "caInclude" and widget.get("name") == "cainclude":
for prop in widget.findall("property"):
# Update the macro data string
if prop.get("name") == "macro":
string_elem = prop.find("string")
if string_elem is not None and string_elem.text is not None:
string_elem.text = (
string_elem.text + ";" + new_macro_element.to_string()
)
# Dynamically update the count match so caInclude renders all rows
if prop.get("name") == "numberOfItems":
number_elem = prop.find("number")
assert number_elem is not None and number_elem.text is not None
num_macro_elements = int(number_elem.text)
number_elem.text = str(num_macro_elements + 1)
assert num_macro_elements is not None, "could not find number of macro elements in xml"
return num_macro_elements
def _update_heights(self, num_macro_elements: int) -> None:
"""
There are 3 heights to be adjusted:
1. Main window
2. Tab widget
3. Widget inside the tab widget
"""
root = self.tree.getroot()
ca_include_height = self._get_height_cainclude()
height_to_add = int(
(ca_include_height / num_macro_elements * (num_macro_elements + 1)) - ca_include_height
)
# 1. Main window
mainwindow = root.find(".//widget[@class='QMainWindow']")
if mainwindow is not None:
rect = mainwindow.find("./property[@name='geometry']/rect")
assert rect is not None
height = rect.find("height")
assert height is not None and height.text is not None
height.text = str(int(height.text) + height_to_add)
for widget in root.iter("widget"):
widget_name = widget.get("name")
# 2. Tab widget
if widget_name == "tabWidget":
rect = widget.find("./property[@name='geometry']/rect")
assert rect is not None
height = rect.find("height")
assert height is not None and height.text is not None
height.text = str(int(height.text) + height_to_add)
# 3. Widget inside the tab widget
elif widget_name == "cainclude":
rect = widget.find("./property[@name='geometry']/rect")
assert rect is not None
height = rect.find("height")
assert height is not None and height.text is not None
height.text = str(int(height.text) + height_to_add)
def _get_height_cainclude(self) -> int:
"""
Get the height of the area that includes all the services
"""
root = self.tree.getroot()
cainclude_height = None
for widget in root.iter("widget"):
widget_name = widget.get("name")
# Target the caInclude Widget of Required Services
if widget_name == "cainclude":
rect = widget.find("./property[@name='geometry']/rect")
assert rect is not None
height = rect.find("height")
assert height is not None and height.text is not None
cainclude_height = int(height.text)
assert cainclude_height, "could not get height of cainclude widget"
return cainclude_height
def write_to_file(self, path: Path) -> None:
self.tree.write(path, encoding="utf-8", xml_declaration=True)
class _ServiceManagerUIMacroElement(BaseModel):
service_name_upper: str
ui_name: str
panel: int = 1
svc_exist: int = 1
ui_filename: str
def to_string(self) -> str:
return (
f"IOC=AGEBD-CPCL-{self.service_name_upper},"
f"service={self.service_name_upper},"
f"name={self.ui_name},"
f"panel={self.panel},"
f"svc_exist={self.svc_exist},"
f"panelcmd=A_BD_{self.ui_filename}.ui"
)
+46
View File
@@ -0,0 +1,46 @@
from pathlib import Path
import yaml
from pydantic import BaseModel
from core.enums import ServiceStatus
from models.service import Service
class ServiceRegistry(BaseModel):
next_available_ioc_port: int
services: list[dict]
@classmethod
def read_from_file(cls, path: Path) -> "ServiceRegistry":
with open(path) as f:
d = yaml.safe_load(f)
registry = ServiceRegistry.model_validate(d)
return registry
def get_service(self, name: str) -> Service:
for svc_data in self.services:
service = Service(**svc_data)
if name == service.name_lower:
return service
raise ValueError(f"Could not find service with name: {name}")
def get_services(self) -> list[Service]:
return [Service(**svc_data) for svc_data in self.services]
def add_service(self, name: str) -> Service:
svc = Service(
name=name,
ioc_port=self.next_available_ioc_port,
status=ServiceStatus.ACTIVE,
)
self.services.append(svc.to_dict())
self.next_available_ioc_port += 1
return svc
def write_to_file(self, path: Path) -> None:
with open(path, "w") as f:
yaml.safe_dump(self.model_dump(), f, sort_keys=False)