|
| 1 | +from typing import Any, Optional |
| 2 | + |
| 3 | +from pydantic import BaseModel, Field |
| 4 | + |
| 5 | +from infrahub_sdk.client import InfrahubClient |
| 6 | +from infrahub_sdk.schema import MainSchemaTypes |
| 7 | +from infrahub_sdk.yaml import InfrahubFile, InfrahubFileKind |
| 8 | + |
| 9 | + |
| 10 | +class InfrahubObjectFileData(BaseModel): |
| 11 | + kind: str | None = None |
| 12 | + data: list[dict[str, Any]] = Field(default_factory=list) |
| 13 | + |
| 14 | + @classmethod |
| 15 | + def enrich_node(cls, data: dict) -> dict: |
| 16 | + return data |
| 17 | + |
| 18 | + @classmethod |
| 19 | + async def create_node( |
| 20 | + cls, |
| 21 | + client: InfrahubClient, |
| 22 | + schema: MainSchemaTypes, |
| 23 | + data: dict, |
| 24 | + context: Optional[dict] = None, |
| 25 | + branch: Optional[str] = None, |
| 26 | + default_schema_kind: Optional[str] = None, |
| 27 | + ) -> None: |
| 28 | + # First validate of all mandatory fields are present |
| 29 | + for element in schema.mandatory_attribute_names + schema.mandatory_relationship_names: |
| 30 | + if element not in data.keys(): |
| 31 | + raise ValueError(f"{element} is mandatory") |
| 32 | + |
| 33 | + clean_data: dict[str, Any] = {} |
| 34 | + |
| 35 | + remaining_rels = [] |
| 36 | + for key, value in data.items(): |
| 37 | + if key in schema.attribute_names: |
| 38 | + # NOTE we could validate the format of the data but the API will do it as well |
| 39 | + clean_data[key] = value |
| 40 | + |
| 41 | + if key in schema.relationship_names: |
| 42 | + rel_schema = schema.get_relationship(name=key) |
| 43 | + |
| 44 | + if not isinstance(value, dict) and "data" in value: |
| 45 | + raise ValueError(f"relationship {key} must be a dict with 'data'") |
| 46 | + |
| 47 | + if rel_schema.cardinality == "one" or rel_schema.optional is False: |
| 48 | + raise ValueError( |
| 49 | + "Not supported yet, we need to have a way to define connect object before they exist" |
| 50 | + ) |
| 51 | + # clean_data[key] = value[data] |
| 52 | + remaining_rels.append(key) |
| 53 | + |
| 54 | + if context: |
| 55 | + clean_data.update(context) |
| 56 | + |
| 57 | + clean_data = cls.enrich_node(data=clean_data) |
| 58 | + |
| 59 | + node = await client.create(kind=schema.kind, branch=branch, data=clean_data) |
| 60 | + await node.save(allow_upsert=True) |
| 61 | + print(f"Created Node: {node.get_human_friendly_id_as_string()}") |
| 62 | + |
| 63 | + for rel in remaining_rels: |
| 64 | + # identify what is the name of the relationship on the other side |
| 65 | + if not isinstance(data[rel], dict) and "data" in data[rel]: |
| 66 | + raise ValueError(f"relationship {rel} must be a dict with 'data'") |
| 67 | + |
| 68 | + rel_schema = schema.get_relationship(name=rel) |
| 69 | + peer_kind = data[rel].get("kind", default_schema_kind) or rel_schema.peer |
| 70 | + peer_schema = await client.schema.get(kind=peer_kind, branch=branch) |
| 71 | + |
| 72 | + if rel_schema.identifier is None: |
| 73 | + raise ValueError("identifier must be defined") |
| 74 | + |
| 75 | + peer_rel = peer_schema.get_relationship_by_identifier(id=rel_schema.identifier) |
| 76 | + |
| 77 | + rel_data = data[rel]["data"] |
| 78 | + context = {} |
| 79 | + if peer_rel: |
| 80 | + context[peer_rel.name] = node.id |
| 81 | + |
| 82 | + if rel_schema.cardinality == "one" and isinstance(rel_data, dict): |
| 83 | + await cls.create_node( |
| 84 | + client=client, |
| 85 | + schema=peer_schema, |
| 86 | + data=rel_data, |
| 87 | + context=context, |
| 88 | + branch=branch, |
| 89 | + default_schema_kind=default_schema_kind, |
| 90 | + ) |
| 91 | + |
| 92 | + elif rel_schema.cardinality == "many" and isinstance(rel_data, list): |
| 93 | + for peer_data in rel_data: |
| 94 | + await cls.create_node( |
| 95 | + client=client, |
| 96 | + schema=peer_schema, |
| 97 | + data=peer_data, |
| 98 | + context=context, |
| 99 | + branch=branch, |
| 100 | + default_schema_kind=default_schema_kind, |
| 101 | + ) |
| 102 | + else: |
| 103 | + raise ValueError( |
| 104 | + f"Relationship {rel_schema.name} doesn't have the right format {rel_schema.cardinality} / {type(rel_data)}" |
| 105 | + ) |
| 106 | + |
| 107 | + |
| 108 | +class ObjectFile(InfrahubFile): |
| 109 | + _spec: Optional[InfrahubObjectFileData] = None |
| 110 | + |
| 111 | + @property |
| 112 | + def spec(self) -> InfrahubObjectFileData: |
| 113 | + if not self._spec: |
| 114 | + self._spec = InfrahubObjectFileData(**self.data.spec) |
| 115 | + return self._spec |
| 116 | + |
| 117 | + def validate_content(self) -> None: |
| 118 | + super().validate_content() |
| 119 | + if self.kind != InfrahubFileKind.OBJECT: |
| 120 | + raise ValueError("File is not an Infrahub Object file") |
| 121 | + self._spec = InfrahubObjectFileData(**self.data.spec) |
0 commit comments