infrahub-server 1.2.10__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 (134) 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/config.py +9 -0
  10. infrahub/core/account.py +24 -47
  11. infrahub/core/attribute.py +10 -12
  12. infrahub/core/constants/infrahubkind.py +8 -0
  13. infrahub/core/constraint/node/runner.py +1 -1
  14. infrahub/core/convert_object_type/__init__.py +0 -0
  15. infrahub/core/convert_object_type/conversion.py +122 -0
  16. infrahub/core/convert_object_type/schema_mapping.py +56 -0
  17. infrahub/core/diff/query/all_conflicts.py +1 -5
  18. infrahub/core/diff/query/artifact.py +10 -20
  19. infrahub/core/diff/query/diff_get.py +3 -6
  20. infrahub/core/diff/query/field_summary.py +2 -4
  21. infrahub/core/diff/query/merge.py +70 -123
  22. infrahub/core/diff/query/save.py +20 -32
  23. infrahub/core/diff/query/summary_counts_enricher.py +34 -54
  24. infrahub/core/diff/query_parser.py +5 -1
  25. infrahub/core/diff/tasks.py +3 -3
  26. infrahub/core/manager.py +14 -11
  27. infrahub/core/migrations/graph/m003_relationship_parent_optional.py +1 -2
  28. infrahub/core/migrations/graph/m013_convert_git_password_credential.py +2 -4
  29. infrahub/core/migrations/graph/m019_restore_rels_to_time.py +11 -22
  30. infrahub/core/migrations/graph/m020_duplicate_edges.py +3 -6
  31. infrahub/core/migrations/graph/m021_missing_hierarchy_merge.py +1 -2
  32. infrahub/core/migrations/graph/m024_missing_hierarchy_backfill.py +1 -2
  33. infrahub/core/migrations/query/attribute_add.py +1 -2
  34. infrahub/core/migrations/query/attribute_rename.py +3 -6
  35. infrahub/core/migrations/query/delete_element_in_schema.py +3 -6
  36. infrahub/core/migrations/query/node_duplicate.py +3 -6
  37. infrahub/core/migrations/query/relationship_duplicate.py +3 -6
  38. infrahub/core/migrations/schema/node_attribute_remove.py +3 -6
  39. infrahub/core/migrations/schema/node_remove.py +3 -6
  40. infrahub/core/models.py +29 -2
  41. infrahub/core/node/__init__.py +18 -4
  42. infrahub/core/node/create.py +211 -0
  43. infrahub/core/protocols.py +51 -0
  44. infrahub/core/protocols_base.py +3 -0
  45. infrahub/core/query/__init__.py +2 -2
  46. infrahub/core/query/diff.py +26 -32
  47. infrahub/core/query/ipam.py +10 -20
  48. infrahub/core/query/node.py +28 -46
  49. infrahub/core/query/relationship.py +51 -28
  50. infrahub/core/query/resource_manager.py +1 -2
  51. infrahub/core/query/subquery.py +2 -4
  52. infrahub/core/relationship/model.py +3 -0
  53. infrahub/core/schema/__init__.py +2 -1
  54. infrahub/core/schema/attribute_parameters.py +36 -0
  55. infrahub/core/schema/attribute_schema.py +83 -8
  56. infrahub/core/schema/basenode_schema.py +25 -1
  57. infrahub/core/schema/definitions/core/__init__.py +21 -0
  58. infrahub/core/schema/definitions/internal.py +13 -3
  59. infrahub/core/schema/generated/attribute_schema.py +9 -3
  60. infrahub/core/schema/schema_branch.py +12 -7
  61. infrahub/core/validators/__init__.py +5 -1
  62. infrahub/core/validators/attribute/choices.py +1 -2
  63. infrahub/core/validators/attribute/enum.py +1 -2
  64. infrahub/core/validators/attribute/kind.py +1 -2
  65. infrahub/core/validators/attribute/length.py +13 -6
  66. infrahub/core/validators/attribute/optional.py +1 -2
  67. infrahub/core/validators/attribute/regex.py +5 -5
  68. infrahub/core/validators/attribute/unique.py +1 -3
  69. infrahub/core/validators/determiner.py +18 -2
  70. infrahub/core/validators/enum.py +7 -0
  71. infrahub/core/validators/node/hierarchy.py +3 -6
  72. infrahub/core/validators/query.py +1 -3
  73. infrahub/core/validators/relationship/count.py +6 -12
  74. infrahub/core/validators/relationship/optional.py +2 -4
  75. infrahub/core/validators/relationship/peer.py +3 -8
  76. infrahub/core/validators/tasks.py +1 -1
  77. infrahub/core/validators/uniqueness/query.py +5 -9
  78. infrahub/database/__init__.py +1 -3
  79. infrahub/events/group_action.py +1 -0
  80. infrahub/graphql/analyzer.py +139 -18
  81. infrahub/graphql/app.py +1 -1
  82. infrahub/graphql/loaders/node.py +1 -1
  83. infrahub/graphql/loaders/peers.py +1 -1
  84. infrahub/graphql/manager.py +4 -0
  85. infrahub/graphql/mutations/action.py +164 -0
  86. infrahub/graphql/mutations/convert_object_type.py +62 -0
  87. infrahub/graphql/mutations/main.py +24 -175
  88. infrahub/graphql/mutations/proposed_change.py +21 -18
  89. infrahub/graphql/queries/convert_object_type_mapping.py +36 -0
  90. infrahub/graphql/queries/relationship.py +1 -1
  91. infrahub/graphql/resolvers/many_relationship.py +4 -4
  92. infrahub/graphql/resolvers/resolver.py +4 -4
  93. infrahub/graphql/resolvers/single_relationship.py +2 -2
  94. infrahub/graphql/schema.py +6 -0
  95. infrahub/graphql/subscription/graphql_query.py +2 -2
  96. infrahub/graphql/types/branch.py +1 -1
  97. infrahub/menu/menu.py +31 -0
  98. infrahub/message_bus/messages/__init__.py +0 -10
  99. infrahub/message_bus/operations/__init__.py +0 -8
  100. infrahub/message_bus/operations/refresh/registry.py +1 -1
  101. infrahub/patch/queries/consolidate_duplicated_nodes.py +3 -6
  102. infrahub/patch/queries/delete_duplicated_edges.py +5 -10
  103. infrahub/prefect_server/models.py +1 -19
  104. infrahub/proposed_change/models.py +68 -3
  105. infrahub/proposed_change/tasks.py +907 -30
  106. infrahub/task_manager/models.py +10 -6
  107. infrahub/telemetry/database.py +1 -1
  108. infrahub/telemetry/tasks.py +1 -1
  109. infrahub/trigger/catalogue.py +2 -0
  110. infrahub/trigger/models.py +18 -2
  111. infrahub/trigger/tasks.py +3 -1
  112. infrahub/workflows/catalogue.py +76 -0
  113. {infrahub_server-1.2.10.dist-info → infrahub_server-1.3.0a0.dist-info}/METADATA +2 -2
  114. {infrahub_server-1.2.10.dist-info → infrahub_server-1.3.0a0.dist-info}/RECORD +121 -118
  115. infrahub_testcontainers/container.py +0 -1
  116. infrahub_testcontainers/docker-compose.test.yml +1 -1
  117. infrahub_testcontainers/helpers.py +8 -2
  118. infrahub/message_bus/messages/check_generator_run.py +0 -26
  119. infrahub/message_bus/messages/finalize_validator_execution.py +0 -15
  120. infrahub/message_bus/messages/proposed_change/base_with_diff.py +0 -16
  121. infrahub/message_bus/messages/proposed_change/request_proposedchange_refreshartifacts.py +0 -11
  122. infrahub/message_bus/messages/request_generatordefinition_check.py +0 -20
  123. infrahub/message_bus/messages/request_proposedchange_pipeline.py +0 -23
  124. infrahub/message_bus/operations/check/__init__.py +0 -3
  125. infrahub/message_bus/operations/check/generator.py +0 -156
  126. infrahub/message_bus/operations/finalize/__init__.py +0 -3
  127. infrahub/message_bus/operations/finalize/validator.py +0 -133
  128. infrahub/message_bus/operations/requests/__init__.py +0 -9
  129. infrahub/message_bus/operations/requests/generator_definition.py +0 -140
  130. infrahub/message_bus/operations/requests/proposed_change.py +0 -629
  131. /infrahub/{message_bus/messages/proposed_change → actions}/__init__.py +0 -0
  132. {infrahub_server-1.2.10.dist-info → infrahub_server-1.3.0a0.dist-info}/LICENSE.txt +0 -0
  133. {infrahub_server-1.2.10.dist-info → infrahub_server-1.3.0a0.dist-info}/WHEEL +0 -0
  134. {infrahub_server-1.2.10.dist-info → infrahub_server-1.3.0a0.dist-info}/entry_points.txt +0 -0
@@ -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)
@@ -1,7 +1,7 @@
1
1
  from __future__ import annotations
2
2
 
3
3
  from dataclasses import dataclass, field
4
- from typing import TYPE_CHECKING, Any, Mapping
4
+ from typing import TYPE_CHECKING, Any
5
5
 
6
6
  from graphene import InputObjectType, Mutation
7
7
  from graphene.types.mutation import MutationOptions
@@ -9,12 +9,15 @@ from infrahub_sdk.utils import extract_fields
9
9
  from typing_extensions import Self
10
10
 
11
11
  from infrahub import config, lock
12
- from infrahub.core import registry
13
- from infrahub.core.constants import InfrahubKind, MutationAction, RelationshipCardinality, RelationshipKind
12
+ from infrahub.core.constants import InfrahubKind, MutationAction
14
13
  from infrahub.core.constraint.node.runner import NodeConstraintRunner
15
14
  from infrahub.core.manager import NodeManager
16
- from infrahub.core.node import Node
17
- from infrahub.core.schema import MainSchemaTypes, NodeSchema, RelationshipSchema
15
+ from infrahub.core.node.create import (
16
+ create_node,
17
+ get_profile_ids,
18
+ refresh_for_profile_update,
19
+ )
20
+ from infrahub.core.schema import MainSchemaTypes, NodeSchema
18
21
  from infrahub.core.schema.generic_schema import GenericSchema
19
22
  from infrahub.core.schema.profile_schema import ProfileSchema
20
23
  from infrahub.core.schema.template_schema import TemplateSchema
@@ -33,8 +36,7 @@ if TYPE_CHECKING:
33
36
  from graphql import GraphQLResolveInfo
34
37
 
35
38
  from infrahub.core.branch import Branch
36
- from infrahub.core.protocols import CoreObjectTemplate
37
- from infrahub.core.relationship.model import RelationshipManager
39
+ from infrahub.core.node import Node
38
40
  from infrahub.core.schema.schema_branch import SchemaBranch
39
41
  from infrahub.database import InfrahubDatabase
40
42
  from infrahub.graphql.types.context import ContextInput
@@ -143,33 +145,6 @@ class InfrahubMutationMixin:
143
145
 
144
146
  return mutation
145
147
 
146
- @classmethod
147
- async def _get_profile_ids(cls, db: InfrahubDatabase, obj: Node) -> set[str]:
148
- if not hasattr(obj, "profiles"):
149
- return set()
150
- profile_rels = await obj.profiles.get_relationships(db=db)
151
- return {pr.peer_id for pr in profile_rels}
152
-
153
- @classmethod
154
- async def _refresh_for_profile_update(
155
- cls, db: InfrahubDatabase, branch: Branch, obj: Node, previous_profile_ids: set[str] | None = None
156
- ) -> Node:
157
- if not hasattr(obj, "profiles"):
158
- return obj
159
- current_profile_ids = await cls._get_profile_ids(db=db, obj=obj)
160
- if previous_profile_ids is None or previous_profile_ids != current_profile_ids:
161
- refreshed_node = await NodeManager.get_one_by_id_or_default_filter(
162
- db=db,
163
- kind=cls._meta.active_schema.kind,
164
- id=obj.get_id(),
165
- branch=branch,
166
- include_owner=True,
167
- include_source=True,
168
- )
169
- refreshed_node._node_changelog = obj.node_changelog
170
- return refreshed_node
171
- return obj
172
-
173
148
  @classmethod
174
149
  async def _call_mutate_create_object(cls, data: InputObjectType, db: InfrahubDatabase, branch: Branch) -> Node:
175
150
  """
@@ -185,100 +160,6 @@ class InfrahubMutationMixin:
185
160
 
186
161
  return await cls.mutate_create_object(data=data, db=db, branch=branch)
187
162
 
188
- @classmethod
189
- async def _get_template_relationship_peers(
190
- cls, db: InfrahubDatabase, template: CoreObjectTemplate, relationship: RelationshipSchema
191
- ) -> Mapping[str, Node]:
192
- """For a given relationship on the template, fetch the related peers."""
193
- template_relationship_manager: RelationshipManager = getattr(template, relationship.name)
194
- if relationship.cardinality == RelationshipCardinality.MANY:
195
- return await template_relationship_manager.get_peers(db=db)
196
-
197
- peers: dict[str, Node] = {}
198
- template_relationship_peer = await template_relationship_manager.get_peer(db=db)
199
- if template_relationship_peer:
200
- peers[template_relationship_peer.id] = template_relationship_peer
201
- return peers
202
-
203
- @classmethod
204
- async def _extract_peer_data(
205
- cls,
206
- db: InfrahubDatabase,
207
- template_peer: Node,
208
- obj_peer_schema: MainSchemaTypes,
209
- parent_obj: Node,
210
- current_template: CoreObjectTemplate,
211
- ) -> Mapping[str, Any]:
212
- obj_peer_data: dict[str, Any] = {}
213
-
214
- for attr in template_peer.get_schema().attribute_names:
215
- if attr not in obj_peer_schema.attribute_names:
216
- continue
217
- obj_peer_data[attr] = {"value": getattr(template_peer, attr).value, "source": template_peer.id}
218
-
219
- for rel in template_peer.get_schema().relationship_names:
220
- rel_manager: RelationshipManager = getattr(template_peer, rel)
221
- if (
222
- rel_manager.schema.kind not in [RelationshipKind.COMPONENT, RelationshipKind.PARENT]
223
- or rel_manager.schema.name not in obj_peer_schema.relationship_names
224
- ):
225
- continue
226
-
227
- if list(await rel_manager.get_peers(db=db)) == [current_template.id]:
228
- obj_peer_data[rel] = {"id": parent_obj.id}
229
-
230
- return obj_peer_data
231
-
232
- @classmethod
233
- async def _handle_template_relationships(
234
- cls,
235
- db: InfrahubDatabase,
236
- branch: Branch,
237
- obj: Node,
238
- template: CoreObjectTemplate,
239
- data: InputObjectType,
240
- constraint_runner: NodeConstraintRunner | None = None,
241
- ) -> None:
242
- if constraint_runner is None:
243
- component_registry = get_component_registry()
244
- constraint_runner = await component_registry.get_component(NodeConstraintRunner, db=db, branch=branch)
245
-
246
- for relationship in obj.get_relationships(kind=RelationshipKind.COMPONENT, exclude=list(data)):
247
- template_relationship_peers = await cls._get_template_relationship_peers(
248
- db=db, template=template, relationship=relationship
249
- )
250
- if not template_relationship_peers:
251
- continue
252
-
253
- for template_relationship_peer in template_relationship_peers.values():
254
- # We retrieve peer schema for each peer in case we are processing a relationship which is based on a generic
255
- obj_peer_schema = registry.schema.get_node_schema(
256
- name=template_relationship_peer.get_schema().kind.removeprefix("Template"),
257
- branch=branch,
258
- duplicate=False,
259
- )
260
- obj_peer_data = await cls._extract_peer_data(
261
- db=db,
262
- template_peer=template_relationship_peer,
263
- obj_peer_schema=obj_peer_schema,
264
- parent_obj=obj,
265
- current_template=template,
266
- )
267
-
268
- obj_peer = await Node.init(schema=obj_peer_schema, db=db, branch=branch)
269
- await obj_peer.new(db=db, **obj_peer_data)
270
- await constraint_runner.check(node=obj_peer, field_filters=list(obj_peer_data))
271
- await obj_peer.save(db=db)
272
-
273
- await cls._handle_template_relationships(
274
- db=db,
275
- branch=branch,
276
- constraint_runner=constraint_runner,
277
- obj=obj_peer,
278
- template=template_relationship_peer,
279
- data=data,
280
- )
281
-
282
163
  @classmethod
283
164
  async def mutate_create(
284
165
  cls,
@@ -301,51 +182,15 @@ class InfrahubMutationMixin:
301
182
  db: InfrahubDatabase,
302
183
  branch: Branch,
303
184
  ) -> Node:
304
- component_registry = get_component_registry()
305
- node_constraint_runner = await component_registry.get_component(
306
- NodeConstraintRunner, db=db.start_session(), branch=branch
185
+ schema = cls._meta.active_schema
186
+ if isinstance(schema, GenericSchema):
187
+ raise ValueError(f"Node of generic schema `{schema.name=}` can not be instantiated.")
188
+ return await create_node(
189
+ data=dict(data),
190
+ db=db,
191
+ branch=branch,
192
+ schema=schema,
307
193
  )
308
- node_class = Node
309
- if cls._meta.active_schema.kind in registry.node:
310
- node_class = registry.node[cls._meta.active_schema.kind]
311
-
312
- fields_to_validate = list(data)
313
- if db.is_transaction:
314
- obj = await node_class.init(db=db, schema=cls._meta.schema, branch=branch)
315
- await obj.new(db=db, **data)
316
- await node_constraint_runner.check(node=obj, field_filters=fields_to_validate)
317
- await obj.save(db=db)
318
-
319
- object_template = await obj.get_object_template(db=db)
320
- if object_template:
321
- await cls._handle_template_relationships(
322
- db=db,
323
- branch=branch,
324
- template=object_template,
325
- obj=obj,
326
- data=data,
327
- )
328
- else:
329
- async with db.start_transaction() as dbt:
330
- obj = await node_class.init(db=dbt, schema=cls._meta.schema, branch=branch)
331
- await obj.new(db=dbt, **data)
332
- await node_constraint_runner.check(node=obj, field_filters=fields_to_validate)
333
- await obj.save(db=dbt)
334
-
335
- object_template = await obj.get_object_template(db=dbt)
336
- if object_template:
337
- await cls._handle_template_relationships(
338
- db=dbt,
339
- branch=branch,
340
- template=object_template,
341
- obj=obj,
342
- data=data,
343
- )
344
-
345
- if await cls._get_profile_ids(db=db, obj=obj):
346
- obj = await cls._refresh_for_profile_update(db=db, branch=branch, obj=obj)
347
-
348
- return obj
349
194
 
350
195
  @classmethod
351
196
  async def mutate_create_to_graphql(cls, info: GraphQLResolveInfo, db: InfrahubDatabase, obj: Node) -> Self:
@@ -439,7 +284,7 @@ class InfrahubMutationMixin:
439
284
  component_registry = get_component_registry()
440
285
  node_constraint_runner = await component_registry.get_component(NodeConstraintRunner, db=db, branch=branch)
441
286
 
442
- before_mutate_profile_ids = await cls._get_profile_ids(db=db, obj=obj)
287
+ before_mutate_profile_ids = await get_profile_ids(db=db, obj=obj)
443
288
  await obj.from_graphql(db=db, data=data)
444
289
  fields_to_validate = list(data)
445
290
  await node_constraint_runner.check(
@@ -453,8 +298,12 @@ class InfrahubMutationMixin:
453
298
 
454
299
  await obj.save(db=db, fields=fields)
455
300
 
456
- obj = await cls._refresh_for_profile_update(
457
- db=db, branch=branch, obj=obj, previous_profile_ids=before_mutate_profile_ids
301
+ obj = await refresh_for_profile_update(
302
+ db=db,
303
+ branch=branch,
304
+ obj=obj,
305
+ previous_profile_ids=before_mutate_profile_ids,
306
+ schema=cls._meta.active_schema,
458
307
  )
459
308
  return obj
460
309
 
@@ -18,10 +18,10 @@ from infrahub.database import InfrahubDatabase, retry_db_transaction
18
18
  from infrahub.exceptions import BranchNotFoundError, PermissionDeniedError, ValidationError
19
19
  from infrahub.graphql.mutations.main import InfrahubMutationMixin
20
20
  from infrahub.graphql.types.enums import CheckType as GraphQLCheckType
21
- from infrahub.message_bus import messages
22
21
  from infrahub.proposed_change.constants import ProposedChangeState
23
- from infrahub.workflows.catalogue import PROPOSED_CHANGE_MERGE
22
+ from infrahub.workflows.catalogue import PROPOSED_CHANGE_MERGE, REQUEST_PROPOSED_CHANGE_PIPELINE
24
23
 
24
+ from ...proposed_change.models import RequestProposedChangePipeline
25
25
  from ..types.task import TaskInfo
26
26
  from .main import InfrahubMutationOptions
27
27
 
@@ -65,18 +65,18 @@ class InfrahubProposedChangeMutation(InfrahubMutationMixin, Mutation):
65
65
  )
66
66
 
67
67
  if graphql_context.service:
68
- message_list = [
69
- messages.RequestProposedChangePipeline(
70
- proposed_change=proposed_change.id,
71
- source_branch=source_branch.name,
72
- source_branch_sync_with_git=source_branch.sync_with_git,
73
- destination_branch=destination_branch,
74
- context=graphql_context.get_context(),
75
- ),
76
- ]
77
-
78
- for message in message_list:
79
- await graphql_context.service.message_bus.send(message=message)
68
+ request_proposed_change_model = RequestProposedChangePipeline(
69
+ proposed_change=proposed_change.id,
70
+ source_branch=source_branch.name,
71
+ source_branch_sync_with_git=source_branch.sync_with_git,
72
+ destination_branch=destination_branch,
73
+ )
74
+
75
+ await graphql_context.service.workflow.submit_workflow(
76
+ workflow=REQUEST_PROPOSED_CHANGE_PIPELINE,
77
+ parameters={"model": request_proposed_change_model},
78
+ context=graphql_context.get_context(),
79
+ )
80
80
 
81
81
  return proposed_change, result
82
82
 
@@ -175,16 +175,19 @@ class ProposedChangeRequestRunCheck(Mutation):
175
175
  destination_branch = proposed_change.destination_branch.value
176
176
  source_branch = await _get_source_branch(db=graphql_context.db, name=proposed_change.source_branch.value)
177
177
 
178
- message = messages.RequestProposedChangePipeline(
178
+ request_proposed_change_model = RequestProposedChangePipeline(
179
179
  proposed_change=proposed_change.id,
180
180
  source_branch=source_branch.name,
181
181
  source_branch_sync_with_git=source_branch.sync_with_git,
182
182
  destination_branch=destination_branch,
183
183
  check_type=check_type,
184
- context=graphql_context.get_context(),
185
184
  )
186
185
  if graphql_context.service:
187
- await graphql_context.service.message_bus.send(message=message)
186
+ await graphql_context.service.workflow.submit_workflow(
187
+ workflow=REQUEST_PROPOSED_CHANGE_PIPELINE,
188
+ parameters={"model": request_proposed_change_model},
189
+ context=graphql_context.get_context(),
190
+ )
188
191
 
189
192
  return {"ok": True}
190
193
 
@@ -222,7 +225,7 @@ class ProposedChangeMerge(Mutation):
222
225
 
223
226
  async with graphql_context.db.start_session() as db:
224
227
  proposed_change.state.value = ProposedChangeState.MERGING.value
225
- proposed_change.save(db=db)
228
+ await proposed_change.save(db=db)
226
229
 
227
230
  if wait_until_completion:
228
231
  await graphql_context.service.workflow.execute_workflow(
@@ -0,0 +1,36 @@
1
+ from graphene import Field, ObjectType, String
2
+ from graphene.types.generic import GenericScalar
3
+ from graphql import GraphQLResolveInfo
4
+
5
+ from infrahub.core import registry
6
+ from infrahub.core.convert_object_type.schema_mapping import get_schema_mapping
7
+
8
+
9
+ class FieldsMapping(ObjectType):
10
+ mapping = GenericScalar(required=True)
11
+
12
+
13
+ async def fields_mapping_type_conversion_resolver(
14
+ root: dict, # noqa: ARG001
15
+ info: GraphQLResolveInfo, # noqa: ARG001
16
+ source_kind: str,
17
+ target_kind: str,
18
+ branch: str,
19
+ ) -> dict:
20
+ source_schema = registry.get_node_schema(name=source_kind, branch=branch)
21
+ target_schema = registry.get_node_schema(name=target_kind, branch=branch)
22
+
23
+ mapping = get_schema_mapping(source_schema=source_schema, target_schema=target_schema)
24
+ mapping_dict = {field_name: model.model_dump(mode="json") for field_name, model in mapping.items()}
25
+ return {"mapping": mapping_dict}
26
+
27
+
28
+ FieldsMappingTypeConversion = Field(
29
+ FieldsMapping,
30
+ source_kind=String(),
31
+ target_kind=String(),
32
+ branch=String(),
33
+ description="Retrieve fields mapping for converting object type",
34
+ resolver=fields_mapping_type_conversion_resolver,
35
+ required=True,
36
+ )
@@ -34,7 +34,7 @@ class Relationships(ObjectType):
34
34
 
35
35
  response: dict[str, Any] = {"edges": [], "count": None}
36
36
 
37
- async with graphql_context.db.start_session() as db:
37
+ async with graphql_context.db.start_session(read_only=True) as db:
38
38
  query = await RelationshipGetByIdentifierQuery.init(
39
39
  db=db,
40
40
  branch=graphql_context.branch,
@@ -33,7 +33,7 @@ class ManyRelationshipResolver:
33
33
  parent_id: str,
34
34
  node_schema: NodeSchema,
35
35
  ) -> list[str]:
36
- async with db.start_session() as dbs:
36
+ async with db.start_session(read_only=True) as dbs:
37
37
  query = await NodeGetHierarchyQuery.init(
38
38
  db=dbs,
39
39
  direction=RelationshipHierarchyDirection.DESCENDANTS,
@@ -55,7 +55,7 @@ class ManyRelationshipResolver:
55
55
  rel_schema: RelationshipSchema,
56
56
  filters: dict[str, Any],
57
57
  ) -> int:
58
- async with db.start_session() as dbs:
58
+ async with db.start_session(read_only=True) as dbs:
59
59
  return await NodeManager.count_peers(
60
60
  db=dbs,
61
61
  ids=ids,
@@ -194,7 +194,7 @@ class ManyRelationshipResolver:
194
194
  offset: int | None = None,
195
195
  limit: int | None = None,
196
196
  ) -> list[dict[str, Any]] | None:
197
- async with db.start_session() as dbs:
197
+ async with db.start_session(read_only=True) as dbs:
198
198
  objs = await NodeManager.query_peers(
199
199
  db=dbs,
200
200
  ids=ids,
@@ -257,7 +257,7 @@ class ManyRelationshipResolver:
257
257
  all_peer_rels.extend(node_peer_rels)
258
258
  if not all_peer_rels:
259
259
  return None
260
- async with db.start_session() as dbs:
260
+ async with db.start_session(read_only=True) as dbs:
261
261
  return [
262
262
  await obj.to_graphql(db=dbs, fields=node_fields, related_node_ids=related_node_ids)
263
263
  for obj in all_peer_rels
@@ -29,7 +29,7 @@ async def account_resolver(
29
29
  fields = await extract_fields(info.field_nodes[0].selection_set)
30
30
  graphql_context: GraphqlContext = info.context
31
31
 
32
- async with graphql_context.db.start_session() as db:
32
+ async with graphql_context.db.start_session(read_only=True) as db:
33
33
  results = await NodeManager.query(
34
34
  schema=InfrahubKind.GENERICACCOUNT,
35
35
  filters={"ids": [graphql_context.account_session.account_id]},
@@ -102,7 +102,7 @@ async def default_resolver(*args: Any, **kwargs) -> dict | list[dict] | None:
102
102
  if "__" in key and value or key in ["id", "ids"]
103
103
  }
104
104
 
105
- async with graphql_context.db.start_session() as db:
105
+ async with graphql_context.db.start_session(read_only=True) as db:
106
106
  objs = await NodeManager.query_peers(
107
107
  db=db,
108
108
  ids=[parent["id"]],
@@ -158,7 +158,7 @@ async def default_paginated_list_resolver(
158
158
  fields = await extract_selection(info.field_nodes[0], schema=schema)
159
159
 
160
160
  graphql_context: GraphqlContext = info.context
161
- async with graphql_context.db.start_session() as db:
161
+ async with graphql_context.db.start_session(read_only=True) as db:
162
162
  response: dict[str, Any] = {"edges": []}
163
163
  filters = {
164
164
  key: value for key, value in kwargs.items() if ("__" in key and value is not None) or key in ("ids", "hfid")
@@ -293,7 +293,7 @@ async def hierarchy_resolver(
293
293
 
294
294
  response: dict[str, Any] = {"edges": [], "count": None}
295
295
 
296
- async with graphql_context.db.start_session() as db:
296
+ async with graphql_context.db.start_session(read_only=True) as db:
297
297
  if "count" in fields:
298
298
  response["count"] = await NodeManager.count_hierarchy(
299
299
  db=db,