-
Notifications
You must be signed in to change notification settings - Fork 31
refactor(server): break cfstore.py into recceiver/cf/ subpackage #160
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
anderslindho
wants to merge
12
commits into
master
Choose a base branch
from
refactor-cf-subpackage
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
46b8f5d
chore(server): bump version to 1.9.5
anderslindho 90d1bb2
refactor(server): extract recceiver/cf model and config
anderslindho 87bf844
refactor(server): collapse module-level functions into CFProcessor
anderslindho 0cfa05d
refactor(server): introduce ChannelFinderAdapter, move mock to tests
anderslindho 13d98d6
refactor(server): move CFProcessor to recceiver/cf, delete cfstore.py
anderslindho 027981e
refactor(server): clean up cf package: direct imports, f-string, docs…
anderslindho be1320c
refactor(server): split adapter query methods by purpose
anderslindho d3811dc
refactor(server): reduce cognitive complexity in processor.py
anderslindho 9133c8a
ci(server): report unit test coverage to sonar
anderslindho c9a65e1
fix(server): clean up unused params, dead code, and style in cf package
anderslindho 98b30db
test(server): add unit tests for cf model types and mock adapter
anderslindho c89d65e
ci(server): generate and upload unit test coverage report
anderslindho File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| from typing import Any, Dict, List, runtime_checkable | ||
|
|
||
| try: | ||
| from typing import Protocol | ||
| except ImportError: | ||
| from typing_extensions import Protocol # type: ignore[assignment] | ||
|
|
||
| from recceiver.cf.model import CFChannel, CFProperty, CFPropertyName, PVStatus | ||
|
|
||
|
|
||
| @runtime_checkable | ||
| class ChannelFinderAdapter(Protocol): | ||
| """Typed boundary between CFProcessor and the ChannelFinder HTTP client. | ||
|
|
||
| All methods accept and return domain objects (CFChannel, CFProperty). | ||
| Dict serialisation is handled inside the implementation, not at callsites. | ||
| """ | ||
|
|
||
| def find_by_ioc_id(self, iocid: str) -> List[CFChannel]: | ||
| """Return all channels registered under the given IOC ID.""" | ||
| ... | ||
|
|
||
| def find_by_names(self, name_pattern: str) -> List[CFChannel]: | ||
| """Return channels whose names match a pipe-separated pattern string.""" | ||
| ... | ||
|
|
||
| def find_active_for_recceiver(self, recceiverid: str) -> List[CFChannel]: | ||
| """Return all channels marked Active for the given recceiver.""" | ||
| ... | ||
|
|
||
| def set_channels(self, channels: List[CFChannel]) -> None: | ||
| """Create or overwrite channels.""" | ||
| ... | ||
|
|
||
| def update_property(self, prop: CFProperty, channel_names: List[str]) -> None: | ||
| """Update a single property value across the named channels.""" | ||
| ... | ||
|
|
||
| def get_all_properties(self) -> List[Dict[str, Any]]: | ||
| """Return all property definitions registered in ChannelFinder.""" | ||
| ... | ||
|
|
||
| def set_property(self, name: str, owner: str) -> None: | ||
| """Register a property definition if it does not already exist.""" | ||
| ... | ||
|
|
||
|
|
||
| class PyCFClientAdapter: | ||
| """Wraps pyCFClient's ChannelFinderClient to implement ChannelFinderAdapter.""" | ||
|
|
||
| def __init__(self, client, size_limit: int = 0): | ||
| self._client = client | ||
| self._size_limit = size_limit | ||
|
|
||
| def _find(self, args: List) -> List[CFChannel]: | ||
| if self._size_limit > 0: | ||
| args = args + [("~size", self._size_limit)] | ||
| return [CFChannel.from_dict(ch) for ch in self._client.findByArgs(args)] | ||
|
|
||
| def find_by_ioc_id(self, iocid: str) -> List[CFChannel]: | ||
| return self._find([(CFPropertyName.IOC_ID, iocid)]) | ||
|
|
||
| def find_by_names(self, name_pattern: str) -> List[CFChannel]: | ||
| return self._find([("~name", name_pattern)]) | ||
|
|
||
| def find_active_for_recceiver(self, recceiverid: str) -> List[CFChannel]: | ||
| return self._find( | ||
| [ | ||
| (CFPropertyName.PV_STATUS.value, PVStatus.ACTIVE.value), | ||
| (CFPropertyName.RECCEIVER_ID.value, recceiverid), | ||
| ] | ||
| ) | ||
|
|
||
| def set_channels(self, channels: List[CFChannel]) -> None: | ||
| self._client.set(channels=[ch.as_dict() for ch in channels]) | ||
|
|
||
| def update_property(self, prop: CFProperty, channel_names: List[str]) -> None: | ||
| self._client.update(property=prop.as_dict(), channelNames=channel_names) | ||
|
|
||
| def get_all_properties(self) -> List[Dict[str, Any]]: | ||
| return self._client.getAllProperties() | ||
|
|
||
| def set_property(self, name: str, owner: str) -> None: | ||
| self._client.set(property={"name": name, "owner": owner}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| import socket | ||
| from dataclasses import dataclass, fields | ||
| from typing import Optional | ||
|
|
||
| from recceiver.processors import ConfigAdapter | ||
|
|
||
| RECCEIVERID_DEFAULT = socket.gethostname() | ||
| DEFAULT_QUERY_LIMIT = 10_000 | ||
|
|
||
|
|
||
| @dataclass | ||
| class CFConfig: | ||
| """Configuration options for the CF Processor.""" | ||
|
|
||
| alias_enabled: bool = False | ||
| record_type_enabled: bool = False | ||
| environment_variables: str = "" | ||
| info_tags: str = "" | ||
| ioc_connection_info: bool = True | ||
| record_description_enabled: bool = False | ||
| clean_on_start: bool = True | ||
| clean_on_stop: bool = True | ||
| username: str = "cfstore" | ||
| env_owner_variable: str = "ENGINEER" | ||
| recceiver_id: str = RECCEIVERID_DEFAULT | ||
| timezone: Optional[str] = None | ||
| cf_query_limit: int = DEFAULT_QUERY_LIMIT | ||
| base_url: Optional[str] = None | ||
| cf_username: Optional[str] = None | ||
| cf_password: Optional[str] = None | ||
| verify_ssl: Optional[bool] = None | ||
| push_max_retries: int = 10 | ||
| push_always_retry: bool = True | ||
|
|
||
| @classmethod | ||
| def loads(cls, conf: ConfigAdapter) -> "CFConfig": | ||
| """Load configuration from a ConfigAdapter instance.""" | ||
| return CFConfig( | ||
| alias_enabled=conf.getboolean("alias", False), | ||
| record_type_enabled=conf.getboolean("recordType", False), | ||
| environment_variables=conf.get("environment_vars", ""), | ||
| info_tags=conf.get("infotags", ""), | ||
| ioc_connection_info=conf.getboolean("iocConnectionInfo", True), | ||
| record_description_enabled=conf.getboolean("recordDesc", False), | ||
| clean_on_start=conf.getboolean("cleanOnStart", True), | ||
| clean_on_stop=conf.getboolean("cleanOnStop", True), | ||
| username=conf.get("username", "cfstore"), | ||
| recceiver_id=conf.get("recceiverId", RECCEIVERID_DEFAULT), | ||
| timezone=conf.get("timezone", ""), | ||
| cf_query_limit=conf.get("findSizeLimit", DEFAULT_QUERY_LIMIT), | ||
| base_url=conf.get("baseUrl"), | ||
| cf_username=conf.get("cfUsername"), | ||
| cf_password=conf.get("cfPassword"), | ||
| verify_ssl=conf.getboolean("verifySSL"), | ||
| push_max_retries=conf.getint("pushMaxRetries", 10), | ||
| push_always_retry=conf.getboolean("pushAlwaysRetry", True), | ||
| ) | ||
|
|
||
| def __repr__(self) -> str: | ||
| parts = [] | ||
| for f in fields(self): | ||
| value = getattr(self, f.name) | ||
| if f.name == "cf_password": | ||
| value = "***" if value else None | ||
| parts.append(f"{f.name}={value!r}") | ||
| return f"CFConfig({', '.join(parts)})" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| import enum | ||
| from dataclasses import dataclass, field | ||
| from typing import Any, Dict, List, Optional | ||
|
|
||
|
|
||
| class PVStatus(str, enum.Enum): | ||
| """Active/Inactive status values as used in the pvStatus CF property.""" | ||
|
|
||
| ACTIVE = "Active" | ||
| INACTIVE = "Inactive" | ||
|
|
||
|
|
||
| class CFPropertyName(str, enum.Enum): | ||
| """Canonical property names registered and managed in Channelfinder.""" | ||
|
|
||
| HOSTNAME = "hostName" | ||
| IOC_NAME = "iocName" | ||
| IOC_ID = "iocid" | ||
| IOC_IP = "iocIP" | ||
| PV_STATUS = "pvStatus" | ||
| TIME = "time" | ||
| RECCEIVER_ID = "recceiverID" | ||
| ALIAS = "alias" | ||
| RECORD_TYPE = "recordType" | ||
| RECORD_DESC = "recordDesc" | ||
| CA_PORT = "caPort" | ||
| PVA_PORT = "pvaPort" | ||
|
|
||
|
|
||
| @dataclass | ||
| class CFProperty: | ||
| """A single named property attached to a Channelfinder channel.""" | ||
|
|
||
| name: str | ||
| owner: str | ||
| value: Optional[str] = None | ||
|
|
||
| def as_dict(self) -> Dict[str, str]: | ||
| """Serialise to the dict shape expected by pyCFClient.""" | ||
| return {"name": self.name, "owner": self.owner, "value": self.value or ""} | ||
|
|
||
| @classmethod | ||
| def from_dict(cls, prop_dict: Dict[str, str]) -> "CFProperty": | ||
| """Deserialise from the dict shape returned by pyCFClient.""" | ||
| return cls( | ||
| name=prop_dict.get("name", ""), | ||
| owner=prop_dict.get("owner", ""), | ||
| value=prop_dict.get("value"), | ||
| ) | ||
|
|
||
| @classmethod | ||
| def record_type(cls, owner: str, record_type: str) -> "CFProperty": | ||
| return cls(CFPropertyName.RECORD_TYPE.value, owner, record_type) | ||
|
|
||
| @classmethod | ||
| def alias(cls, owner: str, alias: str) -> "CFProperty": | ||
| return cls(CFPropertyName.ALIAS.value, owner, alias) | ||
|
|
||
| @classmethod | ||
| def pv_status(cls, owner: str, pv_status: PVStatus) -> "CFProperty": | ||
| return cls(CFPropertyName.PV_STATUS.value, owner, pv_status.value) | ||
|
|
||
| @classmethod | ||
| def active(cls, owner: str) -> "CFProperty": | ||
| return cls.pv_status(owner, PVStatus.ACTIVE) | ||
|
|
||
| @classmethod | ||
| def inactive(cls, owner: str) -> "CFProperty": | ||
| return cls.pv_status(owner, PVStatus.INACTIVE) | ||
|
|
||
| @classmethod | ||
| def time(cls, owner: str, time: str) -> "CFProperty": | ||
| return cls(CFPropertyName.TIME.value, owner, time) | ||
|
|
||
|
|
||
| @dataclass | ||
| class CFChannel: | ||
| """A Channelfinder channel with its associated properties.""" | ||
|
|
||
| name: str | ||
| owner: str | ||
| properties: List[CFProperty] | ||
|
|
||
| def as_dict(self) -> Dict[str, Any]: | ||
| """Serialise to the dict shape expected by pyCFClient.""" | ||
| return { | ||
| "name": self.name, | ||
| "owner": self.owner, | ||
| "properties": [p.as_dict() for p in self.properties], | ||
| } | ||
|
|
||
| @classmethod | ||
| def from_dict(cls, channel_dict: Dict[str, Any]) -> "CFChannel": | ||
| """Deserialise from the dict shape returned by pyCFClient.""" | ||
| return cls( | ||
| name=channel_dict.get("name", ""), | ||
| owner=channel_dict.get("owner", ""), | ||
| properties=[CFProperty.from_dict(p) for p in channel_dict.get("properties", [])], | ||
| ) | ||
|
|
||
|
|
||
| @dataclass | ||
| class IocInfo: | ||
| """Runtime state for a connected IOC. The ioc_id property is the primary key.""" | ||
|
|
||
| host: str | ||
| hostname: str | ||
| ioc_name: str | ||
| ioc_ip: str | ||
| owner: str | ||
| time: str | ||
| port: int | ||
| channelcount: int = 0 | ||
|
|
||
| @property | ||
| def ioc_id(self) -> str: | ||
| return f"{self.host}:{self.port}" | ||
|
|
||
|
|
||
| @dataclass | ||
| class RecordInfo: | ||
| """Per-record data extracted from a transaction before pushing to CF.""" | ||
|
|
||
| pv_name: str | ||
| record_type: Optional[str] = None | ||
| info_properties: List[CFProperty] = field(default_factory=list) | ||
| aliases: List[str] = field(default_factory=list) | ||
|
|
||
|
|
||
| class IOCMissingInfoError(Exception): | ||
| """Raised when an IOC is missing required information.""" | ||
|
|
||
| def __init__(self, ioc_info: IocInfo): | ||
| super().__init__(f"Missing hostName {ioc_info.hostname} or iocName {ioc_info.ioc_name}") | ||
| self.ioc_info = ioc_info |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.