infrahub-server 1.5.0b0__py3-none-any.whl → 1.5.0b2__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 (183) hide show
  1. infrahub/actions/tasks.py +8 -0
  2. infrahub/api/diff/diff.py +1 -1
  3. infrahub/api/internal.py +2 -0
  4. infrahub/api/oauth2.py +13 -19
  5. infrahub/api/oidc.py +15 -21
  6. infrahub/api/schema.py +24 -3
  7. infrahub/artifacts/models.py +2 -1
  8. infrahub/auth.py +137 -3
  9. infrahub/cli/__init__.py +2 -0
  10. infrahub/cli/db.py +103 -98
  11. infrahub/cli/db_commands/clean_duplicate_schema_fields.py +212 -0
  12. infrahub/cli/dev.py +118 -0
  13. infrahub/cli/tasks.py +46 -0
  14. infrahub/cli/upgrade.py +30 -3
  15. infrahub/computed_attribute/tasks.py +20 -8
  16. infrahub/core/attribute.py +13 -5
  17. infrahub/core/branch/enums.py +1 -1
  18. infrahub/core/branch/models.py +7 -3
  19. infrahub/core/branch/tasks.py +70 -8
  20. infrahub/core/changelog/models.py +4 -12
  21. infrahub/core/constants/__init__.py +3 -0
  22. infrahub/core/constants/infrahubkind.py +1 -0
  23. infrahub/core/diff/model/path.py +4 -0
  24. infrahub/core/diff/payload_builder.py +1 -1
  25. infrahub/core/diff/query/artifact.py +1 -0
  26. infrahub/core/diff/query/field_summary.py +1 -0
  27. infrahub/core/graph/__init__.py +1 -1
  28. infrahub/core/initialization.py +5 -2
  29. infrahub/core/ipam/utilization.py +1 -1
  30. infrahub/core/manager.py +6 -3
  31. infrahub/core/migrations/__init__.py +3 -0
  32. infrahub/core/migrations/exceptions.py +4 -0
  33. infrahub/core/migrations/graph/__init__.py +12 -11
  34. infrahub/core/migrations/graph/load_schema_branch.py +21 -0
  35. infrahub/core/migrations/graph/m013_convert_git_password_credential.py +1 -1
  36. infrahub/core/migrations/graph/m040_duplicated_attributes.py +81 -0
  37. infrahub/core/migrations/graph/m041_profile_attrs_in_db.py +145 -0
  38. infrahub/core/migrations/graph/m042_create_hfid_display_label_in_db.py +164 -0
  39. infrahub/core/migrations/graph/m043_backfill_hfid_display_label_in_db.py +866 -0
  40. infrahub/core/migrations/query/__init__.py +7 -8
  41. infrahub/core/migrations/query/attribute_add.py +8 -6
  42. infrahub/core/migrations/query/attribute_remove.py +134 -0
  43. infrahub/core/migrations/runner.py +54 -0
  44. infrahub/core/migrations/schema/attribute_kind_update.py +9 -3
  45. infrahub/core/migrations/schema/attribute_supports_profile.py +90 -0
  46. infrahub/core/migrations/schema/node_attribute_add.py +35 -4
  47. infrahub/core/migrations/schema/node_attribute_remove.py +13 -109
  48. infrahub/core/migrations/schema/node_kind_update.py +2 -1
  49. infrahub/core/migrations/schema/node_remove.py +2 -1
  50. infrahub/core/migrations/schema/placeholder_dummy.py +3 -2
  51. infrahub/core/migrations/shared.py +52 -19
  52. infrahub/core/node/__init__.py +158 -51
  53. infrahub/core/node/constraints/attribute_uniqueness.py +3 -1
  54. infrahub/core/node/create.py +46 -63
  55. infrahub/core/node/lock_utils.py +70 -44
  56. infrahub/core/node/node_property_attribute.py +230 -0
  57. infrahub/core/node/resource_manager/ip_address_pool.py +2 -1
  58. infrahub/core/node/resource_manager/ip_prefix_pool.py +2 -1
  59. infrahub/core/node/resource_manager/number_pool.py +2 -1
  60. infrahub/core/node/standard.py +1 -1
  61. infrahub/core/protocols.py +7 -1
  62. infrahub/core/query/attribute.py +55 -0
  63. infrahub/core/query/ipam.py +1 -0
  64. infrahub/core/query/node.py +23 -4
  65. infrahub/core/query/relationship.py +1 -0
  66. infrahub/core/registry.py +2 -2
  67. infrahub/core/relationship/constraints/count.py +1 -1
  68. infrahub/core/relationship/model.py +1 -1
  69. infrahub/core/schema/__init__.py +56 -0
  70. infrahub/core/schema/attribute_schema.py +4 -0
  71. infrahub/core/schema/basenode_schema.py +42 -2
  72. infrahub/core/schema/definitions/core/__init__.py +2 -0
  73. infrahub/core/schema/definitions/core/generator.py +2 -0
  74. infrahub/core/schema/definitions/core/group.py +16 -2
  75. infrahub/core/schema/definitions/internal.py +16 -3
  76. infrahub/core/schema/generated/attribute_schema.py +2 -2
  77. infrahub/core/schema/generated/base_node_schema.py +6 -1
  78. infrahub/core/schema/manager.py +22 -1
  79. infrahub/core/schema/node_schema.py +5 -2
  80. infrahub/core/schema/schema_branch.py +300 -8
  81. infrahub/core/schema/schema_branch_display.py +123 -0
  82. infrahub/core/schema/schema_branch_hfid.py +114 -0
  83. infrahub/core/validators/aggregated_checker.py +1 -1
  84. infrahub/core/validators/determiner.py +12 -1
  85. infrahub/core/validators/relationship/peer.py +1 -1
  86. infrahub/core/validators/tasks.py +1 -1
  87. infrahub/database/graph.py +21 -0
  88. infrahub/display_labels/__init__.py +0 -0
  89. infrahub/display_labels/gather.py +48 -0
  90. infrahub/display_labels/models.py +240 -0
  91. infrahub/display_labels/tasks.py +192 -0
  92. infrahub/display_labels/triggers.py +22 -0
  93. infrahub/events/branch_action.py +27 -1
  94. infrahub/events/group_action.py +1 -1
  95. infrahub/events/node_action.py +1 -1
  96. infrahub/generators/constants.py +7 -0
  97. infrahub/generators/models.py +7 -0
  98. infrahub/generators/tasks.py +34 -22
  99. infrahub/git/base.py +4 -1
  100. infrahub/git/integrator.py +23 -15
  101. infrahub/git/models.py +2 -1
  102. infrahub/git/repository.py +22 -5
  103. infrahub/git/tasks.py +66 -10
  104. infrahub/git/utils.py +123 -1
  105. infrahub/graphql/analyzer.py +1 -1
  106. infrahub/graphql/api/endpoints.py +14 -4
  107. infrahub/graphql/manager.py +4 -9
  108. infrahub/graphql/mutations/convert_object_type.py +11 -1
  109. infrahub/graphql/mutations/display_label.py +118 -0
  110. infrahub/graphql/mutations/generator.py +25 -7
  111. infrahub/graphql/mutations/hfid.py +125 -0
  112. infrahub/graphql/mutations/ipam.py +54 -35
  113. infrahub/graphql/mutations/main.py +27 -28
  114. infrahub/graphql/mutations/relationship.py +2 -2
  115. infrahub/graphql/mutations/resource_manager.py +2 -2
  116. infrahub/graphql/mutations/schema.py +5 -5
  117. infrahub/graphql/queries/resource_manager.py +1 -1
  118. infrahub/graphql/resolvers/resolver.py +2 -0
  119. infrahub/graphql/schema.py +4 -0
  120. infrahub/graphql/schema_sort.py +170 -0
  121. infrahub/graphql/types/branch.py +4 -1
  122. infrahub/graphql/types/enums.py +3 -0
  123. infrahub/groups/tasks.py +1 -1
  124. infrahub/hfid/__init__.py +0 -0
  125. infrahub/hfid/gather.py +48 -0
  126. infrahub/hfid/models.py +240 -0
  127. infrahub/hfid/tasks.py +191 -0
  128. infrahub/hfid/triggers.py +22 -0
  129. infrahub/lock.py +67 -16
  130. infrahub/message_bus/types.py +2 -1
  131. infrahub/middleware.py +26 -1
  132. infrahub/permissions/constants.py +2 -0
  133. infrahub/proposed_change/tasks.py +35 -17
  134. infrahub/server.py +21 -4
  135. infrahub/services/__init__.py +8 -5
  136. infrahub/services/adapters/http/__init__.py +5 -0
  137. infrahub/services/adapters/workflow/worker.py +14 -3
  138. infrahub/task_manager/event.py +5 -0
  139. infrahub/task_manager/models.py +7 -0
  140. infrahub/task_manager/task.py +73 -0
  141. infrahub/trigger/catalogue.py +4 -0
  142. infrahub/trigger/models.py +2 -0
  143. infrahub/trigger/setup.py +13 -4
  144. infrahub/trigger/tasks.py +6 -0
  145. infrahub/workers/dependencies.py +10 -1
  146. infrahub/workers/infrahub_async.py +10 -2
  147. infrahub/workflows/catalogue.py +80 -0
  148. infrahub/workflows/initialization.py +21 -0
  149. infrahub/workflows/utils.py +2 -1
  150. infrahub_sdk/checks.py +1 -1
  151. infrahub_sdk/client.py +13 -10
  152. infrahub_sdk/config.py +29 -2
  153. infrahub_sdk/ctl/cli_commands.py +2 -0
  154. infrahub_sdk/ctl/generator.py +4 -0
  155. infrahub_sdk/ctl/graphql.py +184 -0
  156. infrahub_sdk/ctl/schema.py +28 -9
  157. infrahub_sdk/generator.py +7 -1
  158. infrahub_sdk/graphql/__init__.py +12 -0
  159. infrahub_sdk/graphql/constants.py +1 -0
  160. infrahub_sdk/graphql/plugin.py +85 -0
  161. infrahub_sdk/graphql/query.py +77 -0
  162. infrahub_sdk/{graphql.py → graphql/renderers.py} +81 -73
  163. infrahub_sdk/graphql/utils.py +40 -0
  164. infrahub_sdk/protocols.py +14 -0
  165. infrahub_sdk/schema/__init__.py +70 -4
  166. infrahub_sdk/schema/repository.py +8 -0
  167. infrahub_sdk/spec/models.py +7 -0
  168. infrahub_sdk/spec/object.py +53 -44
  169. infrahub_sdk/spec/processors/__init__.py +0 -0
  170. infrahub_sdk/spec/processors/data_processor.py +10 -0
  171. infrahub_sdk/spec/processors/factory.py +34 -0
  172. infrahub_sdk/spec/processors/range_expand_processor.py +56 -0
  173. infrahub_sdk/spec/range_expansion.py +1 -1
  174. infrahub_sdk/transforms.py +1 -1
  175. {infrahub_server-1.5.0b0.dist-info → infrahub_server-1.5.0b2.dist-info}/METADATA +7 -4
  176. {infrahub_server-1.5.0b0.dist-info → infrahub_server-1.5.0b2.dist-info}/RECORD +182 -143
  177. infrahub_testcontainers/container.py +115 -3
  178. infrahub_testcontainers/docker-compose-cluster.test.yml +6 -1
  179. infrahub_testcontainers/docker-compose.test.yml +6 -1
  180. infrahub/core/migrations/graph/m040_profile_attrs_in_db.py +0 -166
  181. {infrahub_server-1.5.0b0.dist-info → infrahub_server-1.5.0b2.dist-info}/LICENSE.txt +0 -0
  182. {infrahub_server-1.5.0b0.dist-info → infrahub_server-1.5.0b2.dist-info}/WHEEL +0 -0
  183. {infrahub_server-1.5.0b0.dist-info → infrahub_server-1.5.0b2.dist-info}/entry_points.txt +0 -0
@@ -81,7 +81,7 @@ class SchemaDropdownAdd(Mutation):
81
81
  _validate_schema_permission(graphql_context=graphql_context)
82
82
  await apply_external_context(graphql_context=graphql_context, context_input=context)
83
83
 
84
- kind = graphql_context.db.schema.get(name=str(data.kind), branch=graphql_context.branch.name)
84
+ kind = graphql_context.db.schema.get(name=str(data.kind), branch=graphql_context.branch.name, duplicate=False)
85
85
  attribute = str(data.attribute)
86
86
  validate_kind_dropdown(kind=kind, attribute=attribute)
87
87
  dropdown = str(data.dropdown)
@@ -104,7 +104,7 @@ class SchemaDropdownAdd(Mutation):
104
104
  context=graphql_context.get_context(),
105
105
  )
106
106
 
107
- kind = graphql_context.db.schema.get(name=str(data.kind), branch=graphql_context.branch.name)
107
+ kind = graphql_context.db.schema.get(name=str(data.kind), branch=graphql_context.branch.name, duplicate=False)
108
108
  attrib = kind.get_attribute(attribute)
109
109
  dropdown_entry = {}
110
110
  success = False
@@ -141,7 +141,7 @@ class SchemaDropdownRemove(Mutation):
141
141
  graphql_context: GraphqlContext = info.context
142
142
 
143
143
  _validate_schema_permission(graphql_context=graphql_context)
144
- kind = graphql_context.db.schema.get(name=str(data.kind), branch=graphql_context.branch.name)
144
+ kind = graphql_context.db.schema.get(name=str(data.kind), branch=graphql_context.branch.name, duplicate=False)
145
145
  await apply_external_context(graphql_context=graphql_context, context_input=context)
146
146
 
147
147
  attribute = str(data.attribute)
@@ -197,7 +197,7 @@ class SchemaEnumAdd(Mutation):
197
197
  graphql_context: GraphqlContext = info.context
198
198
 
199
199
  _validate_schema_permission(graphql_context=graphql_context)
200
- kind = graphql_context.db.schema.get(name=str(data.kind), branch=graphql_context.branch.name)
200
+ kind = graphql_context.db.schema.get(name=str(data.kind), branch=graphql_context.branch.name, duplicate=False)
201
201
  await apply_external_context(graphql_context=graphql_context, context_input=context)
202
202
 
203
203
  attribute = str(data.attribute)
@@ -243,7 +243,7 @@ class SchemaEnumRemove(Mutation):
243
243
  graphql_context: GraphqlContext = info.context
244
244
 
245
245
  _validate_schema_permission(graphql_context=graphql_context)
246
- kind = graphql_context.db.schema.get(name=str(data.kind), branch=graphql_context.branch.name)
246
+ kind = graphql_context.db.schema.get(name=str(data.kind), branch=graphql_context.branch.name, duplicate=False)
247
247
  await apply_external_context(graphql_context=graphql_context, context_input=context)
248
248
 
249
249
  attribute = str(data.attribute)
@@ -242,7 +242,7 @@ class PoolUtilization(ObjectType):
242
242
  if "kind" in node_fields:
243
243
  node_response["kind"] = resource_node.get_kind()
244
244
  if "display_label" in node_fields:
245
- node_response["display_label"] = await resource_node.render_display_label(db=db)
245
+ node_response["display_label"] = await resource_node.get_display_label(db=db)
246
246
  if "weight" in node_fields:
247
247
  node_response["weight"] = await resource_node.get_resource_weight(db=db) # type: ignore[attr-defined]
248
248
  if "utilization" in node_fields:
@@ -166,6 +166,8 @@ async def default_paginated_list_resolver(
166
166
 
167
167
  edges = fields.get("edges", {})
168
168
  node_fields = edges.get("node", {})
169
+ if "hfid" in node_fields:
170
+ node_fields["human_friendly_id"] = None
169
171
 
170
172
  permission_set: dict[str, Any] | None = None
171
173
  permissions = (
@@ -19,7 +19,9 @@ from .mutations.computed_attribute import RecomputeComputedAttribute, UpdateComp
19
19
  from .mutations.convert_object_type import ConvertObjectType
20
20
  from .mutations.diff import DiffUpdateMutation
21
21
  from .mutations.diff_conflict import ResolveDiffConflict
22
+ from .mutations.display_label import UpdateDisplayLabel
22
23
  from .mutations.generator import GeneratorDefinitionRequestRun
24
+ from .mutations.hfid import UpdateHFID
23
25
  from .mutations.profile import InfrahubProfilesRefresh
24
26
  from .mutations.proposed_change import (
25
27
  ProposedChangeCheckForApprovalRevoke,
@@ -114,6 +116,8 @@ class InfrahubBaseMutation(ObjectType):
114
116
  InfrahubRepositoryProcess = ProcessRepository.Field()
115
117
  InfrahubRepositoryConnectivity = ValidateRepositoryConnectivity.Field()
116
118
  InfrahubUpdateComputedAttribute = UpdateComputedAttribute.Field()
119
+ InfrahubUpdateDisplayLabel = UpdateDisplayLabel.Field()
120
+ InfrahubUpdateHFID = UpdateHFID.Field()
117
121
  InfrahubRecomputeComputedAttribute = RecomputeComputedAttribute.Field()
118
122
 
119
123
  RelationshipAdd = RelationshipAdd.Field()
@@ -0,0 +1,170 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from graphql.language.ast import (
6
+ DocumentNode,
7
+ EnumTypeDefinitionNode,
8
+ EnumValueDefinitionNode,
9
+ FieldDefinitionNode,
10
+ InputObjectTypeDefinitionNode,
11
+ InputValueDefinitionNode,
12
+ InterfaceTypeDefinitionNode,
13
+ NamedTypeNode,
14
+ ObjectTypeDefinitionNode,
15
+ )
16
+
17
+ if TYPE_CHECKING:
18
+ from graphql import DefinitionNode
19
+
20
+
21
+ def _sort_arguments(args: tuple[InputValueDefinitionNode, ...] | None) -> list[InputValueDefinitionNode] | None:
22
+ """Sort arguments (filters) of a field alphabetically by name.
23
+
24
+ Args:
25
+ args: List of input value definition nodes to sort, or None.
26
+
27
+ Returns:
28
+ Sorted list of input value definition nodes, or None if input was None.
29
+ """
30
+ if not args:
31
+ return None
32
+ return sorted(args, key=lambda a: a.name.value)
33
+
34
+
35
+ def _sort_fields(fields: tuple[FieldDefinitionNode, ...] | None) -> list[FieldDefinitionNode] | None:
36
+ """Sort fields and their arguments alphabetically.
37
+
38
+ Args:
39
+ fields: List of field definition nodes to sort, or None.
40
+
41
+ Returns:
42
+ Sorted list of field definition nodes with sorted arguments, or None if input was None.
43
+ """
44
+ if not fields:
45
+ return None
46
+ sorted_fields = []
47
+ for field in sorted(fields, key=lambda fld: fld.name.value):
48
+ sorted_args = _sort_arguments(field.arguments)
49
+ sorted_fields.append(
50
+ FieldDefinitionNode(
51
+ name=field.name,
52
+ type=field.type,
53
+ arguments=sorted_args,
54
+ directives=field.directives,
55
+ description=field.description,
56
+ loc=field.loc,
57
+ )
58
+ )
59
+ return sorted_fields
60
+
61
+
62
+ def _sort_enum_values(values: tuple[EnumValueDefinitionNode, ...] | None) -> list[EnumValueDefinitionNode] | None:
63
+ """Sort enum values alphabetically by name.
64
+
65
+ Args:
66
+ values: List of enum value definition nodes to sort, or None.
67
+
68
+ Returns:
69
+ Sorted list of enum value definition nodes, or None if input was None.
70
+ """
71
+ if not values:
72
+ return None
73
+ return sorted(values, key=lambda v: v.name.value)
74
+
75
+
76
+ def _sort_input_fields(fields: tuple[InputValueDefinitionNode, ...] | None) -> list[InputValueDefinitionNode] | None:
77
+ """Sort input object fields alphabetically by name.
78
+
79
+ Args:
80
+ fields: List of input value definition nodes to sort, or None.
81
+
82
+ Returns:
83
+ Sorted list of input value definition nodes, or None if input was None.
84
+ """
85
+ if not fields:
86
+ return None
87
+ return sorted(fields, key=lambda f: f.name.value)
88
+
89
+
90
+ def _sort_interfaces(interfaces: tuple[NamedTypeNode, ...] | None) -> list[NamedTypeNode] | None:
91
+ """Sort interface implementations alphabetically by name.
92
+
93
+ Args:
94
+ interfaces: Tuple of named type nodes representing interfaces, or None.
95
+
96
+ Returns:
97
+ Sorted list of named type nodes, or None if input was None.
98
+ """
99
+ if not interfaces:
100
+ return None
101
+ return sorted(interfaces, key=lambda i: i.name.value)
102
+
103
+
104
+ def sort_schema_ast(document: DocumentNode) -> DocumentNode:
105
+ """Return a new DocumentNode with all definitions, fields, and arguments sorted alphabetically.
106
+
107
+ This function recursively sorts all GraphQL schema elements including:
108
+ - Type definitions (objects, interfaces, enums, input objects)
109
+ - Field definitions and their arguments
110
+ - Enum values
111
+ - Input object fields
112
+
113
+ Args:
114
+ document: The GraphQL document node containing schema definitions.
115
+
116
+ Returns:
117
+ A new DocumentNode with all elements sorted alphabetically by name.
118
+ """
119
+
120
+ sorted_definitions: list[
121
+ ObjectTypeDefinitionNode
122
+ | InterfaceTypeDefinitionNode
123
+ | EnumTypeDefinitionNode
124
+ | InputObjectTypeDefinitionNode
125
+ | DefinitionNode
126
+ ] = []
127
+
128
+ for definition in sorted(
129
+ document.definitions, key=lambda d: getattr(d.name, "value", "") if hasattr(d, "name") and d.name else ""
130
+ ):
131
+ if isinstance(definition, (ObjectTypeDefinitionNode, InterfaceTypeDefinitionNode)):
132
+ sorted_fields = _sort_fields(definition.fields)
133
+ sorted_interfaces = _sort_interfaces(definition.interfaces)
134
+ sorted_definitions.append(
135
+ definition.__class__(
136
+ name=definition.name,
137
+ interfaces=sorted_interfaces,
138
+ directives=definition.directives,
139
+ fields=sorted_fields,
140
+ description=definition.description,
141
+ loc=definition.loc,
142
+ )
143
+ )
144
+
145
+ elif isinstance(definition, EnumTypeDefinitionNode):
146
+ sorted_values = _sort_enum_values(definition.values)
147
+ sorted_definitions.append(
148
+ EnumTypeDefinitionNode(
149
+ name=definition.name,
150
+ directives=definition.directives,
151
+ values=sorted_values,
152
+ description=definition.description,
153
+ loc=definition.loc,
154
+ )
155
+ )
156
+ elif isinstance(definition, InputObjectTypeDefinitionNode):
157
+ sorted_inputs = _sort_input_fields(definition.fields)
158
+ sorted_definitions.append(
159
+ InputObjectTypeDefinitionNode(
160
+ name=definition.name,
161
+ directives=definition.directives,
162
+ fields=sorted_inputs,
163
+ description=definition.description,
164
+ loc=definition.loc,
165
+ )
166
+ )
167
+ else:
168
+ sorted_definitions.append(definition)
169
+
170
+ return DocumentNode(definitions=sorted_definitions)
@@ -2,11 +2,12 @@ from __future__ import annotations
2
2
 
3
3
  from typing import TYPE_CHECKING, Any
4
4
 
5
- from graphene import Boolean, Field, String
5
+ from graphene import Boolean, Field, Int, String
6
6
 
7
7
  from infrahub.core.branch import Branch
8
8
  from infrahub.core.constants import GLOBAL_BRANCH_NAME
9
9
 
10
+ from .enums import InfrahubBranchStatus
10
11
  from .standard_node import InfrahubObjectType
11
12
 
12
13
  if TYPE_CHECKING:
@@ -19,6 +20,8 @@ class BranchType(InfrahubObjectType):
19
20
  description = String(required=False)
20
21
  origin_branch = String(required=False)
21
22
  branched_from = String(required=False)
23
+ status = InfrahubBranchStatus(required=True)
24
+ graph_version = Int(required=False)
22
25
  created_at = String(required=False)
23
26
  sync_with_git = Boolean(required=False)
24
27
  is_default = Boolean(required=False)
@@ -1,6 +1,7 @@
1
1
  from graphene import Enum
2
2
 
3
3
  from infrahub.core import constants
4
+ from infrahub.core.branch.enums import BranchStatus
4
5
  from infrahub.permissions import constants as permission_constants
5
6
 
6
7
  CheckType = Enum.from_enum(constants.CheckType)
@@ -10,3 +11,5 @@ DiffAction = Enum.from_enum(constants.DiffAction)
10
11
  Severity = Enum.from_enum(constants.Severity)
11
12
 
12
13
  BranchRelativePermissionDecision = Enum.from_enum(permission_constants.BranchRelativePermissionDecision)
14
+
15
+ InfrahubBranchStatus = Enum.from_enum(BranchStatus)
infrahub/groups/tasks.py CHANGED
@@ -20,7 +20,7 @@ async def update_graphql_query_group(model: RequestGraphQLQueryGroupUpdate) -> N
20
20
  if len(model.subscribers) == 1:
21
21
  related_nodes.append(model.subscribers[0])
22
22
 
23
- await add_tags(branches=[model.branch], nodes=related_nodes)
23
+ await add_tags(branches=[model.branch], nodes=related_nodes, namespace=False)
24
24
 
25
25
  params_hash = dict_hash(model.params)
26
26
  group_name = f"{model.query_name}__{params_hash}"
File without changes
@@ -0,0 +1,48 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+
5
+ from prefect import task
6
+ from prefect.cache_policies import NONE
7
+ from prefect.logging import get_run_logger
8
+
9
+ from infrahub.core.registry import registry
10
+ from infrahub.database import InfrahubDatabase # noqa: TC001 needed for prefect flow
11
+
12
+ from .models import HFIDTriggerDefinition
13
+
14
+
15
+ @dataclass
16
+ class BranchScope:
17
+ name: str
18
+ out_of_scope: list[str] = field(default_factory=list)
19
+
20
+
21
+ @task(
22
+ name="gather-trigger-hfid",
23
+ cache_policy=NONE,
24
+ )
25
+ async def gather_trigger_hfid(
26
+ db: InfrahubDatabase | None = None, # noqa: ARG001 Needed to have a common function signature for gathering functions
27
+ ) -> list[HFIDTriggerDefinition]:
28
+ log = get_run_logger()
29
+
30
+ # Build a list of all branches to process based on which branch is different from main
31
+ branches_with_diff_from_main = registry.get_altered_schema_branches()
32
+ branches_to_process: list[BranchScope] = [BranchScope(name=branch) for branch in branches_with_diff_from_main]
33
+ branches_to_process.append(BranchScope(name=registry.default_branch, out_of_scope=branches_with_diff_from_main))
34
+
35
+ triggers: list[HFIDTriggerDefinition] = []
36
+
37
+ for branch in branches_to_process:
38
+ schema_branch = registry.schema.get_schema_branch(name=branch.name)
39
+ branch_triggers = HFIDTriggerDefinition.from_schema_hfids(
40
+ branch=branch.name,
41
+ hfids=schema_branch.hfids,
42
+ branches_out_of_scope=branch.out_of_scope,
43
+ )
44
+ log.info(f"Generating {len(branch_triggers)} HFID trigger for {branch.name} (except {branch.out_of_scope})")
45
+
46
+ triggers.extend(branch_triggers)
47
+
48
+ return triggers
@@ -0,0 +1,240 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import TYPE_CHECKING, Any, Self
5
+
6
+ from infrahub_sdk.graphql import Query
7
+ from pydantic import BaseModel, Field
8
+
9
+ from infrahub.core.constants import RelationshipCardinality
10
+ from infrahub.core.registry import registry
11
+ from infrahub.core.schema import NodeSchema # noqa: TC001
12
+ from infrahub.events import NodeUpdatedEvent
13
+ from infrahub.trigger.constants import NAME_SEPARATOR
14
+ from infrahub.trigger.models import (
15
+ EventTrigger,
16
+ ExecuteWorkflow,
17
+ TriggerBranchDefinition,
18
+ TriggerType,
19
+ )
20
+ from infrahub.workflows.catalogue import HFID_PROCESS
21
+
22
+ if TYPE_CHECKING:
23
+ from infrahub.core.schema.schema_branch_hfid import HFIDs, RelationshipTriggers
24
+
25
+
26
+ @dataclass
27
+ class AttributeTarget:
28
+ hash: str
29
+ fields: set[str]
30
+
31
+
32
+ class HFIDTriggerDefinition(TriggerBranchDefinition):
33
+ type: TriggerType = TriggerType.HUMAN_FRIENDLY_ID
34
+ hfid_hash: str
35
+ target_kind: str | None = Field(default=None)
36
+
37
+ def get_description(self) -> str:
38
+ return f"{super().get_description()} | hash:{self.hfid_hash}"
39
+
40
+ @classmethod
41
+ def from_schema_hfids(
42
+ cls,
43
+ branch: str,
44
+ hfids: HFIDs,
45
+ branches_out_of_scope: list[str] | None = None,
46
+ ) -> list[HFIDTriggerDefinition]:
47
+ """
48
+ This function is used to create a trigger definition for a display labels of type Jinja2.
49
+ """
50
+
51
+ definitions: list[HFIDTriggerDefinition] = []
52
+
53
+ for node_kind, hfid_definition in hfids.get_template_nodes().items():
54
+ definitions.append(
55
+ cls.new(
56
+ branch=branch,
57
+ node_kind=node_kind,
58
+ target_kind=node_kind,
59
+ fields=[
60
+ "_trigger_placeholder"
61
+ ], # Triggers for the nodes themselves are only used to determine if all nodes should be regenerated
62
+ hfid_hash=hfid_definition.get_hash(),
63
+ branches_out_of_scope=branches_out_of_scope,
64
+ )
65
+ )
66
+
67
+ for related_kind, relationship_trigger in hfids.get_related_trigger_nodes().items():
68
+ definitions.extend(
69
+ cls.from_related_node(
70
+ branch=branch,
71
+ related_kind=related_kind,
72
+ relationship_trigger=relationship_trigger,
73
+ hfids=hfids,
74
+ branches_out_of_scope=branches_out_of_scope,
75
+ )
76
+ )
77
+
78
+ return definitions
79
+
80
+ @classmethod
81
+ def from_related_node(
82
+ cls,
83
+ branch: str,
84
+ related_kind: str,
85
+ relationship_trigger: RelationshipTriggers,
86
+ hfids: HFIDs,
87
+ branches_out_of_scope: list[str] | None = None,
88
+ ) -> list[HFIDTriggerDefinition]:
89
+ targets_by_attribute: dict[str, AttributeTarget] = {}
90
+ definitions: list[HFIDTriggerDefinition] = []
91
+ for attribute, relationship_identifiers in relationship_trigger.attributes.items():
92
+ for relationship_identifier in relationship_identifiers:
93
+ actual_node = hfids.get_node_definition(kind=relationship_identifier.kind)
94
+ if relationship_identifier.kind not in targets_by_attribute:
95
+ targets_by_attribute[relationship_identifier.kind] = AttributeTarget(
96
+ actual_node.get_hash(), fields=set()
97
+ )
98
+ targets_by_attribute[relationship_identifier.kind].fields.add(attribute)
99
+
100
+ for target_kind, attribute_target in targets_by_attribute.items():
101
+ definitions.append(
102
+ cls.new(
103
+ branch=branch,
104
+ node_kind=related_kind,
105
+ target_kind=target_kind,
106
+ fields=sorted(attribute_target.fields),
107
+ hfid_hash=attribute_target.hash,
108
+ branches_out_of_scope=branches_out_of_scope,
109
+ )
110
+ )
111
+
112
+ return definitions
113
+
114
+ @classmethod
115
+ def new(
116
+ cls,
117
+ branch: str,
118
+ node_kind: str,
119
+ target_kind: str,
120
+ hfid_hash: str,
121
+ fields: list[str],
122
+ branches_out_of_scope: list[str] | None = None,
123
+ ) -> Self:
124
+ event_trigger = EventTrigger()
125
+ event_trigger.events.add(NodeUpdatedEvent.event_name)
126
+ event_trigger.match = {"infrahub.node.kind": node_kind}
127
+ if branches_out_of_scope:
128
+ event_trigger.match["infrahub.branch.name"] = [f"!{branch}" for branch in branches_out_of_scope]
129
+ elif not branches_out_of_scope and branch != registry.default_branch:
130
+ event_trigger.match["infrahub.branch.name"] = branch
131
+
132
+ event_trigger.match_related = {
133
+ "prefect.resource.role": ["infrahub.node.attribute_update", "infrahub.node.relationship_update"],
134
+ "infrahub.field.name": fields,
135
+ }
136
+
137
+ workflow = ExecuteWorkflow(
138
+ workflow=HFID_PROCESS,
139
+ parameters={
140
+ "branch_name": "{{ event.resource['infrahub.branch.name'] }}",
141
+ "node_kind": node_kind,
142
+ "object_id": "{{ event.resource['infrahub.node.id'] }}",
143
+ "target_kind": target_kind,
144
+ "context": {
145
+ "__prefect_kind": "json",
146
+ "value": {
147
+ "__prefect_kind": "jinja",
148
+ "template": "{{ event.payload['context'] | tojson }}",
149
+ },
150
+ },
151
+ },
152
+ )
153
+
154
+ trigger_definition_target_kind = target_kind if target_kind == node_kind else None
155
+
156
+ return cls(
157
+ name=f"{target_kind}{NAME_SEPARATOR}by{NAME_SEPARATOR}{node_kind}",
158
+ hfid_hash=hfid_hash,
159
+ branch=branch,
160
+ trigger=event_trigger,
161
+ actions=[workflow],
162
+ target_kind=trigger_definition_target_kind,
163
+ )
164
+
165
+
166
+ class HFIDGraphQLResponse(BaseModel):
167
+ node_id: str
168
+ hfid_value: list[str] | None = Field(default=None)
169
+ variables: dict[str, str] = Field(default_factory=dict)
170
+
171
+
172
+ class HFIDGraphQL(BaseModel):
173
+ filter_key: str
174
+ node_schema: NodeSchema = Field(..., description="The node kind where the computed attribute is defined")
175
+ variables: list[str] = Field(..., description="The list of variable names used within the computed attribute")
176
+
177
+ def render_graphql_query(self, filter_id: str) -> str:
178
+ query_fields = self.query_fields
179
+ query_fields["id"] = None
180
+ query_fields["hfid"] = None
181
+ query = Query(
182
+ name="HFIDFilter",
183
+ query={
184
+ self.node_schema.kind: {
185
+ "@filters": {self.filter_key: filter_id},
186
+ "edges": {"node": query_fields},
187
+ }
188
+ },
189
+ )
190
+
191
+ return query.render()
192
+
193
+ @property
194
+ def query_fields(self) -> dict[str, Any]:
195
+ output: dict[str, Any] = {}
196
+ for variable in self.variables:
197
+ field_name, remainder = variable.split("__", maxsplit=1)
198
+ if field_name in self.node_schema.attribute_names:
199
+ output[field_name] = {remainder: None}
200
+ elif field_name in self.node_schema.relationship_names:
201
+ related_attribute, related_value = remainder.split("__", maxsplit=1)
202
+ relationship = self.node_schema.get_relationship(name=field_name)
203
+ if relationship.cardinality == RelationshipCardinality.ONE:
204
+ if field_name not in output:
205
+ output[field_name] = {"node": {}}
206
+ output[field_name]["node"][related_attribute] = {related_value: None}
207
+ return output
208
+
209
+ def parse_response(self, response: dict[str, Any]) -> list[HFIDGraphQLResponse]:
210
+ rendered_response: list[HFIDGraphQLResponse] = []
211
+ if kind_payload := response.get(self.node_schema.kind):
212
+ edges = kind_payload.get("edges", [])
213
+ for node in edges:
214
+ if node_response := self.to_node_response(node_dict=node):
215
+ rendered_response.append(node_response)
216
+ return rendered_response
217
+
218
+ def to_node_response(self, node_dict: dict[str, Any]) -> HFIDGraphQLResponse | None:
219
+ if node := node_dict.get("node"):
220
+ node_id = node.get("id")
221
+ else:
222
+ return None
223
+
224
+ hfid = node.get("hfid")
225
+ response = HFIDGraphQLResponse(node_id=node_id, hfid_value=hfid)
226
+ for variable in self.variables:
227
+ field_name, remainder = variable.split("__", maxsplit=1)
228
+ # response.variables[variable] = None
229
+ if field_content := node.get(field_name):
230
+ if field_name in self.node_schema.attribute_names:
231
+ response.variables[variable] = str(field_content.get(remainder, ""))
232
+ elif field_name in self.node_schema.relationship_names:
233
+ relationship = self.node_schema.get_relationship(name=field_name)
234
+ if relationship.cardinality == RelationshipCardinality.ONE:
235
+ related_attribute, related_value = remainder.split("__", maxsplit=1)
236
+ node_content = field_content.get("node") or {}
237
+ related_attribute_content = node_content.get(related_attribute) or {}
238
+ response.variables[variable] = str(related_attribute_content.get(related_value, ""))
239
+
240
+ return response