infrahub-server 1.2.9rc0__py3-none-any.whl → 1.3.0a0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. infrahub/actions/constants.py +86 -0
  2. infrahub/actions/gather.py +114 -0
  3. infrahub/actions/models.py +241 -0
  4. infrahub/actions/parsers.py +104 -0
  5. infrahub/actions/schema.py +382 -0
  6. infrahub/actions/tasks.py +126 -0
  7. infrahub/actions/triggers.py +21 -0
  8. infrahub/cli/db.py +1 -2
  9. infrahub/computed_attribute/models.py +13 -0
  10. infrahub/computed_attribute/tasks.py +48 -26
  11. infrahub/config.py +9 -0
  12. infrahub/core/account.py +24 -47
  13. infrahub/core/attribute.py +53 -14
  14. infrahub/core/branch/models.py +8 -9
  15. infrahub/core/branch/tasks.py +0 -2
  16. infrahub/core/constants/infrahubkind.py +8 -0
  17. infrahub/core/constraint/node/runner.py +1 -1
  18. infrahub/core/convert_object_type/__init__.py +0 -0
  19. infrahub/core/convert_object_type/conversion.py +122 -0
  20. infrahub/core/convert_object_type/schema_mapping.py +56 -0
  21. infrahub/core/diff/calculator.py +65 -11
  22. infrahub/core/diff/combiner.py +38 -31
  23. infrahub/core/diff/coordinator.py +44 -28
  24. infrahub/core/diff/data_check_synchronizer.py +3 -2
  25. infrahub/core/diff/enricher/hierarchy.py +36 -27
  26. infrahub/core/diff/ipam_diff_parser.py +5 -4
  27. infrahub/core/diff/merger/merger.py +46 -16
  28. infrahub/core/diff/merger/serializer.py +1 -0
  29. infrahub/core/diff/model/field_specifiers_map.py +64 -0
  30. infrahub/core/diff/model/path.py +58 -58
  31. infrahub/core/diff/parent_node_adder.py +14 -16
  32. infrahub/core/diff/query/all_conflicts.py +1 -5
  33. infrahub/core/diff/query/artifact.py +10 -20
  34. infrahub/core/diff/query/diff_get.py +3 -6
  35. infrahub/core/diff/query/drop_nodes.py +42 -0
  36. infrahub/core/diff/query/field_specifiers.py +8 -7
  37. infrahub/core/diff/query/field_summary.py +2 -4
  38. infrahub/core/diff/query/filters.py +15 -1
  39. infrahub/core/diff/query/merge.py +284 -101
  40. infrahub/core/diff/query/save.py +26 -34
  41. infrahub/core/diff/query/summary_counts_enricher.py +34 -54
  42. infrahub/core/diff/query_parser.py +55 -65
  43. infrahub/core/diff/repository/deserializer.py +38 -24
  44. infrahub/core/diff/repository/repository.py +31 -12
  45. infrahub/core/diff/tasks.py +3 -3
  46. infrahub/core/graph/__init__.py +1 -1
  47. infrahub/core/manager.py +14 -11
  48. infrahub/core/migrations/graph/__init__.py +2 -0
  49. infrahub/core/migrations/graph/m003_relationship_parent_optional.py +1 -2
  50. infrahub/core/migrations/graph/m013_convert_git_password_credential.py +2 -4
  51. infrahub/core/migrations/graph/m019_restore_rels_to_time.py +11 -22
  52. infrahub/core/migrations/graph/m020_duplicate_edges.py +3 -6
  53. infrahub/core/migrations/graph/m021_missing_hierarchy_merge.py +1 -2
  54. infrahub/core/migrations/graph/m024_missing_hierarchy_backfill.py +1 -2
  55. infrahub/core/migrations/graph/m027_delete_isolated_nodes.py +50 -0
  56. infrahub/core/migrations/graph/m028_delete_diffs.py +38 -0
  57. infrahub/core/migrations/query/attribute_add.py +1 -2
  58. infrahub/core/migrations/query/attribute_rename.py +3 -6
  59. infrahub/core/migrations/query/delete_element_in_schema.py +3 -6
  60. infrahub/core/migrations/query/node_duplicate.py +3 -6
  61. infrahub/core/migrations/query/relationship_duplicate.py +3 -6
  62. infrahub/core/migrations/schema/node_attribute_remove.py +3 -6
  63. infrahub/core/migrations/schema/node_remove.py +3 -6
  64. infrahub/core/models.py +29 -2
  65. infrahub/core/node/__init__.py +18 -4
  66. infrahub/core/node/create.py +211 -0
  67. infrahub/core/protocols.py +51 -0
  68. infrahub/core/protocols_base.py +3 -0
  69. infrahub/core/query/__init__.py +2 -2
  70. infrahub/core/query/branch.py +27 -17
  71. infrahub/core/query/diff.py +186 -81
  72. infrahub/core/query/ipam.py +10 -20
  73. infrahub/core/query/node.py +65 -49
  74. infrahub/core/query/relationship.py +156 -58
  75. infrahub/core/query/resource_manager.py +1 -2
  76. infrahub/core/query/subquery.py +4 -6
  77. infrahub/core/relationship/model.py +4 -1
  78. infrahub/core/schema/__init__.py +2 -1
  79. infrahub/core/schema/attribute_parameters.py +36 -0
  80. infrahub/core/schema/attribute_schema.py +83 -8
  81. infrahub/core/schema/basenode_schema.py +25 -1
  82. infrahub/core/schema/definitions/core/__init__.py +21 -0
  83. infrahub/core/schema/definitions/internal.py +13 -3
  84. infrahub/core/schema/generated/attribute_schema.py +9 -3
  85. infrahub/core/schema/schema_branch.py +15 -7
  86. infrahub/core/validators/__init__.py +5 -1
  87. infrahub/core/validators/attribute/choices.py +1 -2
  88. infrahub/core/validators/attribute/enum.py +1 -2
  89. infrahub/core/validators/attribute/kind.py +1 -2
  90. infrahub/core/validators/attribute/length.py +13 -6
  91. infrahub/core/validators/attribute/optional.py +1 -2
  92. infrahub/core/validators/attribute/regex.py +5 -5
  93. infrahub/core/validators/attribute/unique.py +1 -3
  94. infrahub/core/validators/determiner.py +18 -2
  95. infrahub/core/validators/enum.py +7 -0
  96. infrahub/core/validators/node/hierarchy.py +3 -6
  97. infrahub/core/validators/query.py +1 -3
  98. infrahub/core/validators/relationship/count.py +6 -12
  99. infrahub/core/validators/relationship/optional.py +2 -4
  100. infrahub/core/validators/relationship/peer.py +3 -8
  101. infrahub/core/validators/tasks.py +1 -1
  102. infrahub/core/validators/uniqueness/query.py +12 -9
  103. infrahub/database/__init__.py +1 -3
  104. infrahub/events/group_action.py +1 -0
  105. infrahub/graphql/analyzer.py +139 -18
  106. infrahub/graphql/app.py +1 -1
  107. infrahub/graphql/loaders/node.py +1 -1
  108. infrahub/graphql/loaders/peers.py +1 -1
  109. infrahub/graphql/manager.py +4 -0
  110. infrahub/graphql/mutations/action.py +164 -0
  111. infrahub/graphql/mutations/convert_object_type.py +62 -0
  112. infrahub/graphql/mutations/main.py +24 -175
  113. infrahub/graphql/mutations/proposed_change.py +21 -18
  114. infrahub/graphql/queries/convert_object_type_mapping.py +36 -0
  115. infrahub/graphql/queries/diff/tree.py +2 -1
  116. infrahub/graphql/queries/relationship.py +1 -1
  117. infrahub/graphql/resolvers/many_relationship.py +4 -4
  118. infrahub/graphql/resolvers/resolver.py +4 -4
  119. infrahub/graphql/resolvers/single_relationship.py +2 -2
  120. infrahub/graphql/schema.py +6 -0
  121. infrahub/graphql/subscription/graphql_query.py +2 -2
  122. infrahub/graphql/types/branch.py +1 -1
  123. infrahub/menu/menu.py +31 -0
  124. infrahub/message_bus/messages/__init__.py +0 -10
  125. infrahub/message_bus/operations/__init__.py +0 -8
  126. infrahub/message_bus/operations/refresh/registry.py +1 -1
  127. infrahub/patch/queries/consolidate_duplicated_nodes.py +3 -6
  128. infrahub/patch/queries/delete_duplicated_edges.py +5 -10
  129. infrahub/prefect_server/models.py +1 -19
  130. infrahub/proposed_change/models.py +68 -3
  131. infrahub/proposed_change/tasks.py +907 -30
  132. infrahub/task_manager/models.py +10 -6
  133. infrahub/telemetry/database.py +1 -1
  134. infrahub/telemetry/tasks.py +1 -1
  135. infrahub/trigger/catalogue.py +2 -0
  136. infrahub/trigger/models.py +29 -3
  137. infrahub/trigger/setup.py +51 -15
  138. infrahub/trigger/tasks.py +4 -5
  139. infrahub/types.py +1 -1
  140. infrahub/webhook/models.py +2 -1
  141. infrahub/workflows/catalogue.py +85 -0
  142. infrahub/workflows/initialization.py +1 -3
  143. infrahub_sdk/timestamp.py +2 -2
  144. {infrahub_server-1.2.9rc0.dist-info → infrahub_server-1.3.0a0.dist-info}/METADATA +4 -4
  145. {infrahub_server-1.2.9rc0.dist-info → infrahub_server-1.3.0a0.dist-info}/RECORD +153 -146
  146. infrahub_testcontainers/container.py +0 -1
  147. infrahub_testcontainers/docker-compose.test.yml +4 -4
  148. infrahub_testcontainers/helpers.py +8 -2
  149. infrahub_testcontainers/performance_test.py +6 -3
  150. infrahub/message_bus/messages/check_generator_run.py +0 -26
  151. infrahub/message_bus/messages/finalize_validator_execution.py +0 -15
  152. infrahub/message_bus/messages/proposed_change/base_with_diff.py +0 -16
  153. infrahub/message_bus/messages/proposed_change/request_proposedchange_refreshartifacts.py +0 -11
  154. infrahub/message_bus/messages/request_generatordefinition_check.py +0 -20
  155. infrahub/message_bus/messages/request_proposedchange_pipeline.py +0 -23
  156. infrahub/message_bus/operations/check/__init__.py +0 -3
  157. infrahub/message_bus/operations/check/generator.py +0 -156
  158. infrahub/message_bus/operations/finalize/__init__.py +0 -3
  159. infrahub/message_bus/operations/finalize/validator.py +0 -133
  160. infrahub/message_bus/operations/requests/__init__.py +0 -9
  161. infrahub/message_bus/operations/requests/generator_definition.py +0 -140
  162. infrahub/message_bus/operations/requests/proposed_change.py +0 -629
  163. /infrahub/{message_bus/messages/proposed_change → actions}/__init__.py +0 -0
  164. {infrahub_server-1.2.9rc0.dist-info → infrahub_server-1.3.0a0.dist-info}/LICENSE.txt +0 -0
  165. {infrahub_server-1.2.9rc0.dist-info → infrahub_server-1.3.0a0.dist-info}/WHEEL +0 -0
  166. {infrahub_server-1.2.9rc0.dist-info → infrahub_server-1.3.0a0.dist-info}/entry_points.txt +0 -0
@@ -158,12 +158,11 @@ class NodeUniqueAttributeConstraintQuery(Query):
158
158
  # ruff: noqa: E501
159
159
  query = """
160
160
  // get attributes for node and its relationships
161
- CALL {
161
+ CALL () {
162
162
  %(select_subqueries_str)s
163
163
  }
164
- CALL {
164
+ CALL (potential_path) {
165
165
  WITH potential_path
166
- WITH potential_path // workaround for neo4j not allowing WHERE in a WITH of a subquery
167
166
  // only the branches and times we care about
168
167
  WHERE all(
169
168
  r IN relationships(potential_path) WHERE (
@@ -183,8 +182,7 @@ class NodeUniqueAttributeConstraintQuery(Query):
183
182
  start_node,
184
183
  rel_identifier,
185
184
  potential_attr
186
- CALL {
187
- WITH enriched_paths
185
+ CALL (enriched_paths) {
188
186
  UNWIND enriched_paths as path_to_check
189
187
  RETURN path_to_check[0] as current_path, path_to_check[4] as latest_value
190
188
  ORDER BY
@@ -194,16 +192,14 @@ class NodeUniqueAttributeConstraintQuery(Query):
194
192
  path_to_check[3] DESC
195
193
  LIMIT 1
196
194
  }
197
- CALL {
195
+ CALL (current_path) {
198
196
  // only active paths
199
197
  WITH current_path
200
- WITH current_path // workaround for neo4j not allowing WHERE in a WITH of a subquery
201
198
  WHERE all(r IN relationships(current_path) WHERE r.status = "active")
202
199
  RETURN current_path as active_path
203
200
  }
204
- CALL {
201
+ CALL (active_path) {
205
202
  // get deepest branch name
206
- WITH active_path
207
203
  UNWIND %(branch_name_and_level)s as branch_name_and_level
208
204
  RETURN branch_name_and_level[0] as branch_name
209
205
  ORDER BY branch_name_and_level[1] DESC
@@ -225,6 +221,13 @@ class NodeUniqueAttributeConstraintQuery(Query):
225
221
  attr_name,
226
222
  attr_value,
227
223
  relationship_identifier
224
+ ORDER BY
225
+ node_id,
226
+ deepest_branch_name,
227
+ node_count,
228
+ attr_name,
229
+ attr_value,
230
+ relationship_identifier
228
231
  """ % {
229
232
  "select_subqueries_str": select_subqueries_str,
230
233
  "branch_filter": branch_filter,
@@ -476,8 +476,6 @@ async def validate_database(
476
476
 
477
477
 
478
478
  async def get_db(retry: int = 0) -> AsyncDriver:
479
- URI = f"{config.SETTINGS.database.protocol}://{config.SETTINGS.database.address}:{config.SETTINGS.database.port}"
480
-
481
479
  trusted_certificates = TrustSystemCAs()
482
480
  if config.SETTINGS.database.tls_insecure:
483
481
  trusted_certificates = TrustAll()
@@ -485,7 +483,7 @@ async def get_db(retry: int = 0) -> AsyncDriver:
485
483
  trusted_certificates = TrustCustomCAs(config.SETTINGS.database.tls_ca_file)
486
484
 
487
485
  driver = AsyncGraphDatabase.driver(
488
- URI,
486
+ config.SETTINGS.database.database_uri,
489
487
  auth=(config.SETTINGS.database.username, config.SETTINGS.database.password),
490
488
  encrypted=config.SETTINGS.database.tls_enabled,
491
489
  trusted_certificates=trusted_certificates,
@@ -89,6 +89,7 @@ class GroupMutatedEvent(InfrahubEvent):
89
89
  "infrahub.node.id": self.node_id,
90
90
  "infrahub.node.action": self.action.value,
91
91
  "infrahub.node.root_id": self.node_id,
92
+ "infrahub.branch.name": self.meta.context.branch.name,
92
93
  }
93
94
 
94
95
 
@@ -13,11 +13,27 @@ from graphql import (
13
13
  FragmentSpreadNode,
14
14
  GraphQLSchema,
15
15
  InlineFragmentNode,
16
+ ListTypeNode,
16
17
  NamedTypeNode,
17
18
  NonNullTypeNode,
18
19
  OperationDefinitionNode,
19
20
  OperationType,
20
21
  SelectionSetNode,
22
+ TypeNode,
23
+ )
24
+ from graphql.language.ast import (
25
+ BooleanValueNode,
26
+ ConstListValueNode,
27
+ ConstObjectValueNode,
28
+ EnumValueNode,
29
+ FloatValueNode,
30
+ IntValueNode,
31
+ ListValueNode,
32
+ NullValueNode,
33
+ ObjectValueNode,
34
+ StringValueNode,
35
+ ValueNode,
36
+ VariableNode,
21
37
  )
22
38
  from infrahub_sdk.analyzer import GraphQLQueryAnalyzer
23
39
  from infrahub_sdk.utils import extract_fields
@@ -91,9 +107,24 @@ class GraphQLSelectionSet:
91
107
  @dataclass
92
108
  class GraphQLArgument:
93
109
  name: str
94
- value: str
110
+ value: Any
95
111
  kind: str
96
112
 
113
+ @property
114
+ def is_variable(self) -> bool:
115
+ return self.kind == "variable"
116
+
117
+ @property
118
+ def as_variable_name(self) -> str:
119
+ """Return the name without a $ prefix"""
120
+ return str(self.value).removeprefix("$")
121
+
122
+ @property
123
+ def fields(self) -> list[str]:
124
+ if self.kind != "object_value" or not isinstance(self.value, dict):
125
+ return []
126
+ return sorted(self.value.keys())
127
+
97
128
 
98
129
  @dataclass
99
130
  class ObjectAccess:
@@ -106,6 +137,9 @@ class GraphQLVariable:
106
137
  name: str
107
138
  type: str
108
139
  required: bool
140
+ is_list: bool = False
141
+ inner_required: bool = False
142
+ default: Any | None = None
109
143
 
110
144
 
111
145
  @dataclass
@@ -266,6 +300,28 @@ class GraphQLQueryReport:
266
300
 
267
301
  return fields
268
302
 
303
+ @cached_property
304
+ def variables(self) -> list[GraphQLVariable]:
305
+ """Return input variables defined on the query document
306
+
307
+ All subqueries will use the same document level queries,
308
+ so only the first entry is required
309
+ """
310
+ if self.queries:
311
+ return self.queries[0].variables
312
+ return []
313
+
314
+ def required_argument(self, argument: GraphQLArgument) -> bool:
315
+ if not argument.is_variable:
316
+ # If the argument isn't a variable it would have been
317
+ # statically defined in the input and as such required
318
+ return True
319
+ for variable in self.variables:
320
+ if variable.name == argument.as_variable_name and variable.required:
321
+ return True
322
+
323
+ return False
324
+
269
325
  @cached_property
270
326
  def top_level_kinds(self) -> list[str]:
271
327
  return [query.infrahub_model.kind for query in self.queries if query.infrahub_model]
@@ -298,6 +354,22 @@ class GraphQLQueryReport:
298
354
 
299
355
  return access
300
356
 
357
+ @property
358
+ def only_has_unique_targets(self) -> bool:
359
+ """Indicate if the query document is defined so that it will return a single root level object"""
360
+ for query in self.queries:
361
+ targets_single_query = False
362
+ if query.infrahub_model and query.infrahub_model.uniqueness_constraints:
363
+ for argument in query.arguments:
364
+ if [[argument.name]] == query.infrahub_model.uniqueness_constraints:
365
+ if self.required_argument(argument=argument):
366
+ targets_single_query = True
367
+
368
+ if not targets_single_query:
369
+ return False
370
+
371
+ return True
372
+
301
373
 
302
374
  class InfrahubGraphQLQueryAnalyzer(GraphQLQueryAnalyzer):
303
375
  def __init__(
@@ -603,31 +675,80 @@ class InfrahubGraphQLQueryAnalyzer(GraphQLQueryAnalyzer):
603
675
  ],
604
676
  )
605
677
 
606
- @staticmethod
607
- def _get_variables(operation: OperationDefinitionNode) -> list[GraphQLVariable]:
608
- variables = []
609
- for variable in operation.variable_definitions:
610
- if isinstance(variable.type, NamedTypeNode):
611
- variables.append(
612
- GraphQLVariable(name=variable.variable.name.value, type=variable.type.name.value, required=False)
678
+ def _get_variables(self, operation: OperationDefinitionNode) -> list[GraphQLVariable]:
679
+ variables: list[GraphQLVariable] = []
680
+
681
+ for variable in operation.variable_definitions or []:
682
+ type_node: TypeNode = variable.type
683
+ required = False
684
+ is_list = False
685
+ inner_required = False
686
+
687
+ if isinstance(type_node, NonNullTypeNode):
688
+ required = True
689
+ type_node = type_node.type
690
+
691
+ if isinstance(type_node, ListTypeNode):
692
+ is_list = True
693
+ inner_type = type_node.type
694
+
695
+ if isinstance(inner_type, NonNullTypeNode):
696
+ inner_required = True
697
+ inner_type = inner_type.type
698
+
699
+ if isinstance(inner_type, NamedTypeNode):
700
+ type_name = inner_type.name.value
701
+ else:
702
+ raise TypeError(f"Unsupported inner type node: {inner_type}")
703
+ elif isinstance(type_node, NamedTypeNode):
704
+ type_name = type_node.name.value
705
+ else:
706
+ raise TypeError(f"Unsupported type node: {type_node}")
707
+
708
+ variables.append(
709
+ GraphQLVariable(
710
+ name=variable.variable.name.value,
711
+ type=type_name,
712
+ required=required,
713
+ is_list=is_list,
714
+ inner_required=inner_required,
715
+ default=self._parse_value(variable.default_value) if variable.default_value else None,
613
716
  )
614
- elif isinstance(variable.type, NonNullTypeNode):
615
- if isinstance(variable.type.type, NamedTypeNode):
616
- variables.append(
617
- GraphQLVariable(
618
- name=variable.variable.name.value, type=variable.type.type.name.value, required=True
619
- )
620
- )
717
+ )
621
718
 
622
719
  return variables
623
720
 
624
- @staticmethod
625
- def _parse_arguments(field_node: FieldNode) -> list[GraphQLArgument]:
721
+ def _parse_arguments(self, field_node: FieldNode) -> list[GraphQLArgument]:
626
722
  return [
627
723
  GraphQLArgument(
628
724
  name=argument.name.value,
629
- value=getattr(argument.value, "value", ""),
725
+ value=self._parse_value(argument.value),
630
726
  kind=argument.value.kind,
631
727
  )
632
728
  for argument in field_node.arguments
633
729
  ]
730
+
731
+ def _parse_value(self, node: ValueNode) -> Any:
732
+ match node:
733
+ case VariableNode():
734
+ value: Any = f"${node.name.value}"
735
+ case IntValueNode():
736
+ value = int(node.value)
737
+ case FloatValueNode():
738
+ value = float(node.value)
739
+ case StringValueNode():
740
+ value = node.value
741
+ case BooleanValueNode():
742
+ value = node.value
743
+ case NullValueNode():
744
+ value = None
745
+ case EnumValueNode():
746
+ value = node.value
747
+ case ListValueNode() | ConstListValueNode():
748
+ value = [self._parse_value(item) for item in node.values]
749
+ case ObjectValueNode() | ConstObjectValueNode():
750
+ value = {field.name.value: self._parse_value(field.value) for field in node.fields}
751
+ case _:
752
+ raise TypeError(f"Unsupported value node: {node}")
753
+
754
+ return value
infrahub/graphql/app.py CHANGED
@@ -155,7 +155,7 @@ class InfrahubGraphQLApp:
155
155
 
156
156
  db = websocket.app.state.db
157
157
 
158
- async with db.start_session() as db:
158
+ async with db.start_session(read_only=True) as db:
159
159
  branch_name = websocket.path_params.get("branch_name", registry.default_branch)
160
160
  branch = await registry.get_branch(db=db, branch=branch_name)
161
161
 
@@ -53,7 +53,7 @@ class NodeDataLoader(DataLoader[str, Node | None]):
53
53
  self.db = db
54
54
 
55
55
  async def batch_load_fn(self, keys: list[Any]) -> list[Node | None]:
56
- async with self.db.start_session() as db:
56
+ async with self.db.start_session(read_only=True) as db:
57
57
  nodes_by_id = await NodeManager.get_many(
58
58
  db=db,
59
59
  ids=keys,
@@ -51,7 +51,7 @@ class PeerRelationshipsDataLoader(DataLoader[str, list[Relationship]]):
51
51
  self.db = db
52
52
 
53
53
  async def batch_load_fn(self, keys: list[Any]) -> list[list[Relationship]]: # pylint: disable=method-hidden
54
- async with self.db.start_session() as db:
54
+ async with self.db.start_session(read_only=True) as db:
55
55
  peer_rels = await NodeManager.query_peers(
56
56
  db=db,
57
57
  ids=keys,
@@ -25,6 +25,7 @@ from infrahub.types import ATTRIBUTE_TYPES, InfrahubDataType, get_attribute_type
25
25
  from .directives import DIRECTIVES
26
26
  from .enums import generate_graphql_enum, get_enum_attribute_type_name
27
27
  from .metrics import SCHEMA_GENERATE_GRAPHQL_METRICS
28
+ from .mutations.action import InfrahubTriggerRuleMatchMutation, InfrahubTriggerRuleMutation
28
29
  from .mutations.artifact_definition import InfrahubArtifactDefinitionMutation
29
30
  from .mutations.ipam import (
30
31
  InfrahubIPAddressMutation,
@@ -524,6 +525,9 @@ class GraphQLSchemaManager:
524
525
  InfrahubKind.MENUITEM: InfrahubCoreMenuMutation,
525
526
  InfrahubKind.STANDARDWEBHOOK: InfrahubWebhookMutation,
526
527
  InfrahubKind.CUSTOMWEBHOOK: InfrahubWebhookMutation,
528
+ InfrahubKind.NODETRIGGERRULE: InfrahubTriggerRuleMutation,
529
+ InfrahubKind.NODETRIGGERATTRIBUTEMATCH: InfrahubTriggerRuleMatchMutation,
530
+ InfrahubKind.NODETRIGGERRELATIONSHIPMATCH: InfrahubTriggerRuleMatchMutation,
527
531
  }
528
532
 
529
533
  if isinstance(node_schema, NodeSchema) and node_schema.is_ip_prefix():
@@ -0,0 +1,164 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any, cast
4
+
5
+ from graphene import InputObjectType, Mutation
6
+ from typing_extensions import Self
7
+
8
+ from infrahub.core.protocols import CoreNodeTriggerAttributeMatch, CoreNodeTriggerRelationshipMatch, CoreNodeTriggerRule
9
+ from infrahub.exceptions import SchemaNotFoundError, ValidationError
10
+ from infrahub.log import get_logger
11
+
12
+ from .main import InfrahubMutationMixin, InfrahubMutationOptions
13
+
14
+ if TYPE_CHECKING:
15
+ from graphql import GraphQLResolveInfo
16
+
17
+ from infrahub.core.branch import Branch
18
+ from infrahub.core.node import Node
19
+ from infrahub.core.schema import NodeSchema
20
+ from infrahub.database import InfrahubDatabase
21
+
22
+ from ..initialization import GraphqlContext
23
+
24
+ log = get_logger()
25
+
26
+
27
+ class InfrahubTriggerRuleMutation(InfrahubMutationMixin, Mutation):
28
+ @classmethod
29
+ def __init_subclass_with_meta__(
30
+ cls,
31
+ schema: NodeSchema,
32
+ _meta: Any | None = None,
33
+ **options: dict[str, Any],
34
+ ) -> None:
35
+ if not _meta:
36
+ _meta = InfrahubMutationOptions(cls)
37
+
38
+ _meta.schema = schema
39
+
40
+ super().__init_subclass_with_meta__(_meta=_meta, **options)
41
+
42
+ @classmethod
43
+ async def mutate_create(
44
+ cls,
45
+ info: GraphQLResolveInfo,
46
+ data: InputObjectType,
47
+ branch: Branch,
48
+ database: InfrahubDatabase | None = None,
49
+ ) -> tuple[Node, Self]:
50
+ graphql_context: GraphqlContext = info.context
51
+ db = database or graphql_context.db
52
+ _validate_node_kind(data=data, db=db)
53
+ trigger_rule_definition, result = await super().mutate_create(info=info, data=data, branch=branch, database=db)
54
+
55
+ return trigger_rule_definition, result
56
+
57
+ @classmethod
58
+ async def mutate_update(
59
+ cls,
60
+ info: GraphQLResolveInfo,
61
+ data: InputObjectType,
62
+ branch: Branch,
63
+ database: InfrahubDatabase | None = None,
64
+ node: Node | None = None, # noqa: ARG003
65
+ ) -> tuple[Node, Self]:
66
+ graphql_context: GraphqlContext = info.context
67
+ db = database or graphql_context.db
68
+ _validate_node_kind(data=data, db=db)
69
+ trigger_rule_definition, result = await super().mutate_update(info=info, data=data, branch=branch, database=db)
70
+
71
+ return trigger_rule_definition, result
72
+
73
+
74
+ class InfrahubTriggerRuleMatchMutation(InfrahubMutationMixin, Mutation):
75
+ @classmethod
76
+ def __init_subclass_with_meta__(
77
+ cls,
78
+ schema: NodeSchema,
79
+ _meta: Any | None = None,
80
+ **options: dict[str, Any],
81
+ ) -> None:
82
+ if not _meta:
83
+ _meta = InfrahubMutationOptions(cls)
84
+
85
+ _meta.schema = schema
86
+
87
+ super().__init_subclass_with_meta__(_meta=_meta, **options)
88
+
89
+ @classmethod
90
+ async def mutate_create(
91
+ cls,
92
+ info: GraphQLResolveInfo,
93
+ data: InputObjectType,
94
+ branch: Branch,
95
+ database: InfrahubDatabase | None = None, # noqa: ARG003
96
+ ) -> tuple[Node, Self]:
97
+ graphql_context: GraphqlContext = info.context
98
+
99
+ async with graphql_context.db.start_transaction() as dbt:
100
+ trigger_match, result = await super().mutate_create(info=info, data=data, branch=branch, database=dbt)
101
+ trigger_match_model = cast(CoreNodeTriggerAttributeMatch | CoreNodeTriggerRelationshipMatch, trigger_match)
102
+ node_trigger_rule = await trigger_match_model.trigger.get_peer(db=dbt, raise_on_error=True)
103
+ node_trigger_rule_model = cast(CoreNodeTriggerRule, node_trigger_rule)
104
+ node_schema = dbt.schema.get_node_schema(name=node_trigger_rule_model.node_kind.value, duplicate=False)
105
+ _validate_node_kind_field(data=data, node_schema=node_schema)
106
+
107
+ return trigger_match, result
108
+
109
+ @classmethod
110
+ async def mutate_update(
111
+ cls,
112
+ info: GraphQLResolveInfo,
113
+ data: InputObjectType,
114
+ branch: Branch,
115
+ database: InfrahubDatabase | None = None, # noqa: ARG003
116
+ node: Node | None = None, # noqa: ARG003
117
+ ) -> tuple[Node, Self]:
118
+ graphql_context: GraphqlContext = info.context
119
+ async with graphql_context.db.start_transaction() as dbt:
120
+ trigger_match, result = await super().mutate_update(info=info, data=data, branch=branch, database=dbt)
121
+ trigger_match_model = cast(CoreNodeTriggerAttributeMatch | CoreNodeTriggerRelationshipMatch, trigger_match)
122
+ node_trigger_rule = await trigger_match_model.trigger.get_peer(db=dbt, raise_on_error=True)
123
+ node_trigger_rule_model = cast(CoreNodeTriggerRule, node_trigger_rule)
124
+ node_schema = dbt.schema.get_node_schema(name=node_trigger_rule_model.node_kind.value, duplicate=False)
125
+ _validate_node_kind_field(data=data, node_schema=node_schema)
126
+
127
+ return trigger_match, result
128
+
129
+
130
+ def _validate_node_kind(data: InputObjectType, db: InfrahubDatabase) -> None:
131
+ input_data = cast(dict[str, dict[str, Any]], data)
132
+ if node_kind := input_data.get("node_kind"):
133
+ value = node_kind.get("value")
134
+ if isinstance(value, str):
135
+ try:
136
+ db.schema.get_node_schema(name=value, duplicate=False)
137
+ except SchemaNotFoundError as exc:
138
+ raise ValidationError(
139
+ input_value={"node_kind": "The requested node_kind schema was not found"}
140
+ ) from exc
141
+ except ValueError as exc:
142
+ raise ValidationError(input_value={"node_kind": "The requested node_kind is not a valid node"}) from exc
143
+
144
+
145
+ def _validate_node_kind_field(data: InputObjectType, node_schema: NodeSchema) -> None:
146
+ input_data = cast(dict[str, dict[str, Any]], data)
147
+ if attribute_name := input_data.get("attribute_name"):
148
+ value = attribute_name.get("value")
149
+ if isinstance(value, str):
150
+ if value not in node_schema.attribute_names:
151
+ raise ValidationError(
152
+ input_value={
153
+ "attribute_name": f"The attribute {value} doesn't exist on related node trigger using {node_schema.kind}"
154
+ }
155
+ )
156
+ if relationship_name := input_data.get("relationship_name"):
157
+ value = relationship_name.get("value")
158
+ if isinstance(value, str):
159
+ if value not in node_schema.relationship_names:
160
+ raise ValidationError(
161
+ input_value={
162
+ "relationship_name": f"The relationship {value} doesn't exist on related node trigger using {node_schema.kind}"
163
+ }
164
+ )
@@ -0,0 +1,62 @@
1
+ from typing import TYPE_CHECKING, Any, Self
2
+
3
+ from graphene import Boolean, InputObjectType, Mutation, String
4
+ from graphene.types.generic import GenericScalar
5
+ from graphql import GraphQLResolveInfo
6
+
7
+ from infrahub.core import registry
8
+ from infrahub.core.convert_object_type.conversion import InputForDestField, convert_object_type
9
+ from infrahub.core.manager import NodeManager
10
+
11
+ if TYPE_CHECKING:
12
+ from infrahub.graphql.initialization import GraphqlContext
13
+
14
+
15
+ class ConvertObjectTypeInput(InputObjectType):
16
+ node_id = String(required=True)
17
+ target_kind = String(required=True)
18
+ fields_mapping = GenericScalar(required=True) # keys are destination attributes/relationships names.
19
+ branch = String(required=True)
20
+
21
+
22
+ class ConvertObjectType(Mutation):
23
+ class Arguments:
24
+ data = ConvertObjectTypeInput(required=True)
25
+
26
+ ok = Boolean()
27
+ node = GenericScalar()
28
+
29
+ @classmethod
30
+ async def mutate(
31
+ cls,
32
+ root: dict, # noqa: ARG003
33
+ info: GraphQLResolveInfo,
34
+ data: ConvertObjectTypeInput,
35
+ ) -> Self:
36
+ """Convert an input node to a given compatible kind."""
37
+
38
+ graphql_context: GraphqlContext = info.context
39
+
40
+ fields_mapping: dict[str, InputForDestField] = {}
41
+ if not isinstance(data.fields_mapping, dict):
42
+ raise ValueError(f"Expected `fields_mapping` to be a `dict`, got {type(fields_mapping)}")
43
+
44
+ for field, input_for_dest_field_str in data.fields_mapping.items():
45
+ fields_mapping[field] = InputForDestField(**input_for_dest_field_str)
46
+
47
+ node_to_convert = await NodeManager.get_one(
48
+ id=str(data.node_id), db=graphql_context.db, branch=str(data.branch)
49
+ )
50
+ target_schema = registry.get_node_schema(name=str(data.target_kind), branch=data.branch)
51
+ new_node = await convert_object_type(
52
+ node=node_to_convert,
53
+ target_schema=target_schema,
54
+ mapping=fields_mapping,
55
+ branch=graphql_context.branch,
56
+ db=graphql_context.db,
57
+ )
58
+
59
+ dict_node = await new_node.to_graphql(db=graphql_context.db, fields={})
60
+ result: dict[str, Any] = {"ok": True, "node": dict_node}
61
+
62
+ return cls(**result)